• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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_VERIFICATION_UTIL_STR_H_
17 #define PANDA_VERIFICATION_UTIL_STR_H_
18 
19 #include "lazy.h"
20 #include "include/mem/panda_containers.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 Str, typename Int, typename = std::enable_if_t<std::is_integral_v<Int>>>
39 Str NumToStr(Int val, Int Base = 0x0A, int width = -1)
40 {
41     Str 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         if (c >= 0x0A) {
50             c -= 0x0A;
51             c += 'a';
52         } else {
53             c += '0';
54         }
55         result = Str {c} + result;
56         val = val / Base;
57     } while (val);
58     if (width > 0) {
59         while (result.length() < static_cast<size_t>(width - (neg ? 1 : 0))) {
60             result = "0" + result;
61         }
62     }
63     if (neg) {
64         result = "-" + result;
65     }
66     return result;
67 }
68 }  // namespace panda::verifier
69 
70 #endif  // PANDA_VERIFICATION_UTIL_STR_H_
71