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