Tyler Chatow | fcf16f4 | 2020-07-26 12:41:36 -0700 | [diff] [blame^] | 1 | #include "fast_string_builder.h" |
| 2 | |
| 3 | namespace aos { |
| 4 | |
| 5 | FastStringBuilder::FastStringBuilder(std::size_t initial_size) { |
| 6 | str_.reserve(initial_size); |
| 7 | } |
| 8 | |
| 9 | void FastStringBuilder::Reset() { str_.resize(0); } |
| 10 | |
| 11 | std::string_view FastStringBuilder::Result() const { |
| 12 | return std::string_view(str_); |
| 13 | } |
| 14 | |
| 15 | std::string FastStringBuilder::MoveResult() { |
| 16 | std::string result; |
| 17 | result.swap(str_); |
| 18 | return result; |
| 19 | } |
| 20 | |
| 21 | void FastStringBuilder::Resize(std::size_t chars_needed) { |
| 22 | str_.resize(str_.size() + chars_needed); |
| 23 | } |
| 24 | |
| 25 | void FastStringBuilder::Append(std::string_view str) { |
| 26 | std::size_t index = str_.size(); |
| 27 | Resize(str.size()); |
| 28 | str_.replace(index, str.size(), str, 0); |
| 29 | } |
| 30 | |
| 31 | void FastStringBuilder::Append(float val) { |
| 32 | std::size_t index = str_.size(); |
| 33 | Resize(17); |
| 34 | int result = absl::SNPrintF(str_.data() + index, 17, "%.6g", val); |
| 35 | PCHECK(result != -1); |
| 36 | CHECK(result < 17); |
| 37 | str_.resize(index + result); |
| 38 | } |
| 39 | |
| 40 | void FastStringBuilder::Append(double val) { |
| 41 | std::size_t index = str_.size(); |
| 42 | Resize(25); |
| 43 | int result = absl::SNPrintF(str_.data() + index, 25, "%.15g", val); |
| 44 | PCHECK(result != -1); |
| 45 | CHECK(result < 25); |
| 46 | str_.resize(index + result); |
| 47 | } |
| 48 | |
| 49 | void FastStringBuilder::AppendChar(char val) { |
| 50 | Resize(1); |
| 51 | str_[str_.size() - 1] = val; |
| 52 | } |
| 53 | |
| 54 | void FastStringBuilder::AppendBool(bool val) { |
| 55 | if (bool_to_str_) { |
| 56 | Append(val ? kTrue : kFalse); |
| 57 | } else { |
| 58 | AppendChar(val ? '1' : '0'); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | std::ostream &operator<<(std::ostream &os, const FastStringBuilder &builder) { |
| 63 | os.write(builder.str_.data(), builder.str_.size()); |
| 64 | return os; |
| 65 | } |
| 66 | |
| 67 | } // namespace aos |