1 /*
2 * Copyright 2020 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 <bluetooth/log.h>
20 #include <limits.h>
21 #include <string.h>
22
23 #include <charconv>
24 #include <chrono>
25 #include <iomanip>
26 #include <iterator>
27 #include <limits>
28 #include <optional>
29 #include <sstream>
30 #include <string>
31 #include <type_traits>
32 #include <vector>
33
34 #include "common/type_helper.h"
35
36 namespace bluetooth {
37 namespace common {
38
39 template <typename T>
ToString(const T & value)40 inline std::string ToString(const T& value) {
41 std::stringstream tmp;
42 tmp << value;
43 return tmp.str();
44 }
45
46 // Convert number into a hex string prefixed with 0x
47 template <typename T>
ToHexString(T x)48 std::string ToHexString(T x) {
49 if (x < 0) {
50 if (x == INT_MIN) {
51 return "INT_MIN";
52 }
53 return "-" + ToHexString(-x);
54 }
55 std::stringstream tmp;
56 tmp << "0x" << std::internal << std::hex << std::setfill('0') << std::setw(sizeof(T) * 2)
57 << (unsigned long)x;
58 return tmp.str();
59 }
60
61 template <>
62 inline std::string ToHexString<>(signed long x) {
63 if (x < 0) {
64 if (x == LONG_MIN) {
65 return "LONG_MIN";
66 }
67 return "-" + ToHexString<signed long>(-x);
68 }
69 std::stringstream tmp;
70 tmp << "0x" << std::internal << std::hex << std::setfill('0')
71 << std::setw(sizeof(signed long) * 2) << (unsigned long)x;
72 return tmp.str();
73 }
74
75 template <>
76 inline std::string ToHexString<>(unsigned int x) {
77 std::stringstream tmp;
78 tmp << "0x" << std::internal << std::hex << std::setfill('0')
79 << std::setw(sizeof(unsigned int) * 2) << (unsigned long)x;
80 return tmp.str();
81 }
82
83 // Convert value into a hex decimal formatted string in lower case, prefixed with 0s
84 template <class InputIt>
ToHexString(InputIt first,InputIt last)85 std::string ToHexString(InputIt first, InputIt last) {
86 static_assert(std::is_same_v<typename std::iterator_traits<InputIt>::value_type, uint8_t>,
87 "Must use uint8_t iterator");
88 std::stringstream ss;
89 for (InputIt it = first; it != last; ++it) {
90 // +(byte) to prevent an uint8_t to be interpreted as a char
91 ss << std::hex << std::setw(2) << std::setfill('0') << +(*it);
92 }
93 return ss.str();
94 }
95 // Convenience method for normal cases and initializer list, e.g. ToHexString({0x12, 0x34, 0x56,
96 // 0xab})
97 std::string ToHexString(const std::vector<uint8_t>& value);
98
99 // Return true if |str| is a valid hex demical strings contains only hex decimal chars [0-9a-fA-F]
100 bool IsValidHexString(const std::string& str);
101
102 // Parse |str| into a vector of uint8_t, |str| must contains only hex decimal
103 std::optional<std::vector<uint8_t>> FromHexString(const std::string& str);
104
105 // Remove whitespace from both ends of the |str|, returning a copy
106 std::string StringTrim(std::string str);
107
108 // Split |str| into at most |max_token| tokens delimited by |delim|, unlimited tokens when
109 // |max_token| is 0
110 std::vector<std::string> StringSplit(const std::string& str, const std::string& delim,
111 size_t max_token = 0);
112
113 // Join |strings| into a single string using |delim|
114 std::string StringJoin(const std::vector<std::string>& strings, const std::string& delim);
115
116 // Various number comparison functions, only base 10 is supported
117 std::optional<int64_t> Int64FromString(const std::string& str);
118 std::string ToString(int64_t value);
119 std::optional<uint64_t> Uint64FromString(const std::string& str);
120 std::string ToString(uint64_t value);
121 std::optional<bool> BoolFromString(const std::string& str);
122 std::string ToString(bool value);
123
124 // Migrate this method to std::format when C++20 becomes available
125 // printf like formatting to std::string
126 // format must contains format information, to print a string use StringFormat("%s", str)
127 template <typename... Args>
StringFormat(const std::string & format,Args...args)128 std::string StringFormat(const std::string& format, Args... args) {
129 auto size = std::snprintf(nullptr, 0, format.c_str(), args...);
130 log::assert_that(size >= 0, "return value {}, error {}, text '{}'", size, errno, strerror(errno));
131 // Add 1 for terminating null byte
132 std::vector<char> buffer(size + 1);
133 auto actual_size = std::snprintf(buffer.data(), buffer.size(), format.c_str(), args...);
134 log::assert_that(size == actual_size, "asked size {}, actual size {}, error {}, text '{}'", size,
135 actual_size, errno, strerror(errno));
136 // Exclude the terminating null byte
137 return std::string(buffer.data(), size);
138 }
139
StringFormatTime(const std::string & format,const struct std::tm & tm)140 inline std::string StringFormatTime(const std::string& format, const struct std::tm& tm) {
141 std::ostringstream os;
142 os << std::put_time(&tm, format.c_str());
143 return os.str();
144 }
145
146 inline std::string StringFormatTimeWithMilliseconds(
147 const std::string& format, std::chrono::time_point<std::chrono::system_clock> time_point,
148 struct tm* (*calendar_to_tm)(const time_t* timep) = localtime) {
149 std::time_t epoch_time = std::chrono::system_clock::to_time_t(time_point);
150 auto millis = time_point.time_since_epoch() / std::chrono::milliseconds(1) % 1000;
151 std::tm tm = *calendar_to_tm(&epoch_time);
152 std::ostringstream os;
153 os << std::put_time(&tm, format.c_str()) << StringFormat(".%03u", millis);
154 return os.str();
155 }
156
157 } // namespace common
158 } // namespace bluetooth
159