1 /**
2  * Copyright (c) 2021-2024 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 ark::verifier {
25 
26 template <typename StrT, typename Gen>
Join(Gen gen, StrT delim = {�})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     bool neg = false;
44     if (val < 0) {
45         neg = true;
46         val = -val;
47     }
48     do {
49         char c = static_cast<char>(val % base);
50         constexpr char LETTER_DIGIT_START = static_cast<char>(10);
51         if (c >= LETTER_DIGIT_START) {
52             c += 'a' - LETTER_DIGIT_START;
53         } else {
54             c += '0';
55         }
56         result.insert(0, 1, c);
57         val = val / base;
58     } while (val);
59     if (width > 0) {
60         if (neg) {
61             width -= 1;
62         }
63         if (result.length() < width) {
64             result.insert(0, width - result.length(), '0');
65         }
66     }
67     if (neg) {
68         result.insert(0, "-");
69     }
70     return result;
71 }
72 
73 template <typename Offset>
74 PandaString OffsetToHexStr(Offset offset)
75 {
76     constexpr Offset BASE = 16U;
77     // leave space for - if needed
78     constexpr size_t WIDTH = sizeof(Offset) + (std::is_signed_v<Offset> ? 1 : 0);
79     return NumToStr(offset, BASE, WIDTH);
80 }
81 }  // namespace ark::verifier
82 
83 #endif  // !PANDA_VERIFIER_UTIL_STR_HPP_
84