blob: 00fe001292961d396a246af6a027dbb78a109c12 [file] [log] [blame]
Philipp Schrader790cb542023-07-05 21:06:52 -07001#include "aos/fast_string_builder.h"
Tyler Chatowfcf16f42020-07-26 12:41:36 -07002
James Kuszmaul98c798d2024-04-24 15:58:09 -07003#include <charconv>
4
Tyler Chatowfcf16f42020-07-26 12:41:36 -07005namespace aos {
6
7FastStringBuilder::FastStringBuilder(std::size_t initial_size) {
8 str_.reserve(initial_size);
9}
10
11void FastStringBuilder::Reset() { str_.resize(0); }
12
13std::string_view FastStringBuilder::Result() const {
14 return std::string_view(str_);
15}
16
17std::string FastStringBuilder::MoveResult() {
18 std::string result;
19 result.swap(str_);
20 return result;
21}
22
23void FastStringBuilder::Resize(std::size_t chars_needed) {
24 str_.resize(str_.size() + chars_needed);
25}
26
27void FastStringBuilder::Append(std::string_view str) {
28 std::size_t index = str_.size();
29 Resize(str.size());
30 str_.replace(index, str.size(), str, 0);
31}
32
33void FastStringBuilder::Append(float val) {
34 std::size_t index = str_.size();
James Kuszmaul98c798d2024-04-24 15:58:09 -070035 constexpr std::size_t kMaxSize = 17;
36 Resize(kMaxSize);
37 const std::to_chars_result result =
38 std::to_chars(str_.data() + index, str_.data() + index + kMaxSize, val);
39 CHECK(result.ec == std::errc()) << std::make_error_code(result.ec).message();
40 str_.resize(result.ptr - str_.data());
Tyler Chatowfcf16f42020-07-26 12:41:36 -070041}
42
43void FastStringBuilder::Append(double val) {
44 std::size_t index = str_.size();
James Kuszmaul98c798d2024-04-24 15:58:09 -070045 constexpr std::size_t kMaxSize = 25;
46 Resize(kMaxSize);
47 const std::to_chars_result result =
48 std::to_chars(str_.data() + index, str_.data() + index + kMaxSize, val);
49 CHECK(result.ec == std::errc()) << std::make_error_code(result.ec).message();
50 str_.resize(result.ptr - str_.data());
Tyler Chatowfcf16f42020-07-26 12:41:36 -070051}
52
53void FastStringBuilder::AppendChar(char val) {
54 Resize(1);
55 str_[str_.size() - 1] = val;
56}
57
58void FastStringBuilder::AppendBool(bool val) {
59 if (bool_to_str_) {
60 Append(val ? kTrue : kFalse);
61 } else {
62 AppendChar(val ? '1' : '0');
63 }
64}
65
66std::ostream &operator<<(std::ostream &os, const FastStringBuilder &builder) {
67 os.write(builder.str_.data(), builder.str_.size());
68 return os;
69}
70
71} // namespace aos