xref: /llvm-project/flang/runtime/tools.cpp (revision 352d347aa5f5f1ba9b17aedd90daa5c110b8a50e)
1 //===-- runtime/tools.cpp ---------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "tools.h"
10 #include <cstring>
11 
12 namespace Fortran::runtime {
13 
14 OwningPtr<char> SaveDefaultCharacter(
15     const char *s, std::size_t length, Terminator &terminator) {
16   if (s) {
17     auto *p{static_cast<char *>(AllocateMemoryOrCrash(terminator, length + 1))};
18     std::memcpy(p, s, length);
19     p[length] = '\0';
20     return OwningPtr<char>{p};
21   } else {
22     return OwningPtr<char>{};
23   }
24 }
25 
26 static bool CaseInsensitiveMatch(
27     const char *value, std::size_t length, const char *possibility) {
28   for (; length-- > 0; ++value, ++possibility) {
29     char ch{*value};
30     if (ch >= 'a' && ch <= 'z') {
31       ch += 'A' - 'a';
32     }
33     if (*possibility == '\0' || ch != *possibility) {
34       return false;
35     }
36   }
37   return *possibility == '\0';
38 }
39 
40 int IdentifyValue(
41     const char *value, std::size_t length, const char *possibilities[]) {
42   if (value) {
43     for (int j{0}; possibilities[j]; ++j) {
44       if (CaseInsensitiveMatch(value, length, possibilities[j])) {
45         return j;
46       }
47     }
48   }
49   return -1;
50 }
51 }
52