Philipp Schrader | 790cb54 | 2023-07-05 21:06:52 -0700 | [diff] [blame] | 1 | #include "aos/fast_string_builder.h" |
Tyler Chatow | fcf16f4 | 2020-07-26 12:41:36 -0700 | [diff] [blame] | 2 | |
James Kuszmaul | 98c798d | 2024-04-24 15:58:09 -0700 | [diff] [blame] | 3 | #include <charconv> |
| 4 | |
Tyler Chatow | fcf16f4 | 2020-07-26 12:41:36 -0700 | [diff] [blame] | 5 | namespace aos { |
| 6 | |
| 7 | FastStringBuilder::FastStringBuilder(std::size_t initial_size) { |
| 8 | str_.reserve(initial_size); |
| 9 | } |
| 10 | |
| 11 | void FastStringBuilder::Reset() { str_.resize(0); } |
| 12 | |
| 13 | std::string_view FastStringBuilder::Result() const { |
| 14 | return std::string_view(str_); |
| 15 | } |
| 16 | |
| 17 | std::string FastStringBuilder::MoveResult() { |
| 18 | std::string result; |
| 19 | result.swap(str_); |
| 20 | return result; |
| 21 | } |
| 22 | |
| 23 | void FastStringBuilder::Resize(std::size_t chars_needed) { |
| 24 | str_.resize(str_.size() + chars_needed); |
| 25 | } |
| 26 | |
| 27 | void 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 | |
| 33 | void FastStringBuilder::Append(float val) { |
| 34 | std::size_t index = str_.size(); |
James Kuszmaul | 98c798d | 2024-04-24 15:58:09 -0700 | [diff] [blame] | 35 | 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 Chatow | fcf16f4 | 2020-07-26 12:41:36 -0700 | [diff] [blame] | 41 | } |
| 42 | |
| 43 | void FastStringBuilder::Append(double val) { |
| 44 | std::size_t index = str_.size(); |
James Kuszmaul | 98c798d | 2024-04-24 15:58:09 -0700 | [diff] [blame] | 45 | 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 Chatow | fcf16f4 | 2020-07-26 12:41:36 -0700 | [diff] [blame] | 51 | } |
| 52 | |
| 53 | void FastStringBuilder::AppendChar(char val) { |
| 54 | Resize(1); |
| 55 | str_[str_.size() - 1] = val; |
| 56 | } |
| 57 | |
| 58 | void FastStringBuilder::AppendBool(bool val) { |
| 59 | if (bool_to_str_) { |
| 60 | Append(val ? kTrue : kFalse); |
| 61 | } else { |
| 62 | AppendChar(val ? '1' : '0'); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | std::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 |