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