• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <functional>
20 #include <string_view>
21 
22 #include <ftl/details/type_traits.h>
23 #include <ftl/string.h>
24 
25 namespace android::ftl::details {
26 
27 template <typename T, typename = void>
28 struct StaticString;
29 
30 // Booleans.
31 template <typename T>
32 struct StaticString<T, std::enable_if_t<is_bool_v<T>>> {
33   static constexpr std::size_t N = 5;  // Length of "false".
34 
35   explicit constexpr StaticString(bool b) : view(b ? "true" : "false") {}
36 
37   const std::string_view view;
38 };
39 
40 // Characters.
41 template <typename T>
42 struct StaticString<T, std::enable_if_t<is_char_v<T>>> {
43   static constexpr std::size_t N = 1;
44 
45   explicit constexpr StaticString(char c) : character(c) {}
46 
47   const char character;
48   const std::string_view view{&character, 1u};
49 };
50 
51 // Integers, including the integer value of other character types like char32_t.
52 template <typename T>
53 struct StaticString<
54     T, std::enable_if_t<std::is_integral_v<remove_cvref_t<T>> && !is_bool_v<T> && !is_char_v<T>>> {
55   using U = remove_cvref_t<T>;
56   static constexpr std::size_t N = to_chars_length_v<U>;
57 
58   // TODO: Mark this and to_chars as `constexpr` in C++23.
59   explicit StaticString(U v) : view(to_chars(buffer, v)) {}
60 
61   to_chars_buffer_t<U> buffer;
62   const std::string_view view;
63 };
64 
65 // Character arrays.
66 template <std::size_t M>
67 struct StaticString<const char (&)[M], void> {
68   static constexpr std::size_t N = M - 1;
69 
70   explicit constexpr StaticString(const char (&str)[M]) : view(str, N) {}
71 
72   const std::string_view view;
73 };
74 
75 template <std::size_t N>
76 struct Truncated {
77   std::string_view view;
78 };
79 
80 // Strings with constrained length.
81 template <std::size_t M>
82 struct StaticString<Truncated<M>, void> {
83   static constexpr std::size_t N = M;
84 
85   explicit constexpr StaticString(Truncated<M> str) : view(str.view.substr(0, N)) {}
86 
87   const std::string_view view;
88 };
89 
90 }  // namespace android::ftl::details
91