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 {""}, [need_delim = false, &delim](StrT accum, StrT str) mutable {
30 if (need_delim) {
31 accum += delim;
32 }
33 need_delim = true;
34 return accum + str;
35 });
36 }
37
38 template <typename Int, typename = std::enable_if_t<std::is_integral_v<Int>>>
39 PandaString NumToStr(Int val, Int base = 10, size_t width = 0)
40 {
41 PandaString result = "";
42 bool neg = false;
43 if (val < 0) {
44 neg = true;
45 val = -val;
46 }
47 do {
48 char c = static_cast<char>(val % base);
49 constexpr char LETTER_DIGIT_START = static_cast<char>(10);
50 if (c >= LETTER_DIGIT_START) {
51 c += 'a' - LETTER_DIGIT_START;
52 } else {
53 c += '0';
54 }
55 result.insert(0, 1, c);
56 val = val / base;
57 } while (val);
58 if (width > 0) {
59 if (neg) {
60 width -= 1;
61 }
62 if (result.length() < width) {
63 result.insert(0, width - result.length(), '0');
64 }
65 }
66 if (neg) {
67 result.insert(0, "-");
68 }
69 return result;
70 }
71
72 template <typename Offset>
OffsetToHexStr(Offset offset)73 PandaString OffsetToHexStr(Offset offset)
74 {
75 constexpr Offset base = 16U;
76 // leave space for - if needed
77 constexpr size_t width = sizeof(Offset) + (std::is_signed_v<Offset> ? 1 : 0);
78 return NumToStr(offset, base, width);
79 }
80 } // namespace panda::verifier
81
82 #endif // !PANDA_VERIFIER_UTIL_STR_HPP_
83