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