blob: 97d2fea52b676c89702d2517b32f423b97950494 [file] [log] [blame]
Tyler Chatowfcf16f42020-07-26 12:41:36 -07001#include "fast_string_builder.h"
2
3namespace aos {
4
5FastStringBuilder::FastStringBuilder(std::size_t initial_size) {
6 str_.reserve(initial_size);
7}
8
9void FastStringBuilder::Reset() { str_.resize(0); }
10
11std::string_view FastStringBuilder::Result() const {
12 return std::string_view(str_);
13}
14
15std::string FastStringBuilder::MoveResult() {
16 std::string result;
17 result.swap(str_);
18 return result;
19}
20
21void FastStringBuilder::Resize(std::size_t chars_needed) {
22 str_.resize(str_.size() + chars_needed);
23}
24
25void 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
31void 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
40void 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
49void FastStringBuilder::AppendChar(char val) {
50 Resize(1);
51 str_[str_.size() - 1] = val;
52}
53
54void FastStringBuilder::AppendBool(bool val) {
55 if (bool_to_str_) {
56 Append(val ? kTrue : kFalse);
57 } else {
58 AppendChar(val ? '1' : '0');
59 }
60}
61
62std::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