• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef PANDA_VERIFIER_UTIL_STR_HPP
17 #define PANDA_VERIFIER_UTIL_STR_HPP
18 
19 #include "lazy.h"
20 #include "include/mem/panda_string.h"
21 
22 #include <type_traits>
23 
24 namespace panda::verifier {
25 
26 template <typename StrT, typename Gen>
27 StrT Join(Gen gen, StrT delim = {", "})
28 {
29     return FoldLeft(gen, StrT {""}, [needDelim = false, &delim](StrT accum, StrT str) mutable {
30         if (needDelim) {
31             accum += delim;
32         }
33         needDelim = true;
34         return accum + str;
35     });
36 }
37 
38 template <typename Int, typename = std::enable_if_t<std::is_integral_v<Int>>>
39 // NOLINTNEXTLINE(readability-magic-numbers)
40 PandaString NumToStr(Int val, Int base = 10, size_t width = 0)
41 {
42     PandaString result {};
43     if (base <= 0) {
44         return result;
45     }
46     bool neg = false;
47     if (val < 0) {
48         neg = true;
49         val = -val;
50     }
51     do {
52         char c = static_cast<char>(val % base);
53         constexpr char LETTER_DIGIT_START = static_cast<char>(10);
54         if (c >= LETTER_DIGIT_START) {
55             c += 'a' - LETTER_DIGIT_START;
56         } else {
57             c += '0';
58         }
59         result.insert(0, 1, c);
60         val = val / base;
61     } while (val);
62     if (width > 0) {
63         if (neg) {
64             width -= 1;
65         }
66         if (result.length() < width) {
67             result.insert(0, width - result.length(), '0');
68         }
69     }
70     if (neg) {
71         result.insert(0, "-");
72     }
73     return result;
74 }
75 
76 template <typename Offset>
OffsetToHexStr(Offset offset)77 PandaString OffsetToHexStr(Offset offset)
78 {
79     constexpr Offset BASE = 16U;
80     // leave space for - if needed
81     constexpr size_t WIDTH = sizeof(Offset) + (std::is_signed_v<Offset> ? 1 : 0);
82     return NumToStr(offset, BASE, WIDTH);
83 }
84 }  // namespace panda::verifier
85 
86 #endif  // !PANDA_VERIFIER_UTIL_STR_HPP
87