blob: b450a995b0b6468509423893cb7b53ba95dd72eb [file] [log] [blame]
Tommifef05002018-02-27 13:51:08 +01001/*
2 * Copyright 2018 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#ifndef RTC_BASE_STRINGS_STRING_BUILDER_H_
12#define RTC_BASE_STRINGS_STRING_BUILDER_H_
13
14#include <cstdio>
Karl Wiberg881f1682018-03-08 15:03:23 +010015#include <cstring>
Tommifef05002018-02-27 13:51:08 +010016#include <string>
17
Karl Wiberg881f1682018-03-08 15:03:23 +010018#include "api/array_view.h"
Tommifef05002018-02-27 13:51:08 +010019#include "rtc_base/checks.h"
Karl Wiberg881f1682018-03-08 15:03:23 +010020#include "rtc_base/numerics/safe_minmax.h"
Tommifef05002018-02-27 13:51:08 +010021#include "rtc_base/stringutils.h"
22
23namespace rtc {
24
Karl Wiberg881f1682018-03-08 15:03:23 +010025// This is a minimalistic string builder class meant to cover the most cases of
26// when you might otherwise be tempted to use a stringstream (discouraged for
27// anything except logging). It uses a fixed-size buffer provided by the caller
28// and concatenates strings and numbers into it, allowing the results to be
29// read via |str()|.
Tommifef05002018-02-27 13:51:08 +010030class SimpleStringBuilder {
31 public:
Karl Wiberg881f1682018-03-08 15:03:23 +010032 explicit SimpleStringBuilder(rtc::ArrayView<char> buffer);
Tommifef05002018-02-27 13:51:08 +010033 SimpleStringBuilder(const SimpleStringBuilder&) = delete;
34 SimpleStringBuilder& operator=(const SimpleStringBuilder&) = delete;
35
36 SimpleStringBuilder& operator<<(const char* str) { return Append(str); }
37
38 SimpleStringBuilder& operator<<(char ch) { return Append(&ch, 1); }
39
40 SimpleStringBuilder& operator<<(const std::string& str) {
41 return Append(str.c_str(), str.length());
42 }
43
44 // Numeric conversion routines.
45 //
46 // We use std::[v]snprintf instead of std::to_string because:
47 // * std::to_string relies on the current locale for formatting purposes,
48 // and therefore concurrent calls to std::to_string from multiple threads
49 // may result in partial serialization of calls
50 // * snprintf allows us to print the number directly into our buffer.
51 // * avoid allocating a std::string (potential heap alloc).
52 // TODO(tommi): Switch to std::to_chars in C++17.
53
54 SimpleStringBuilder& operator<<(int i) { return AppendFormat("%d", i); }
55
56 SimpleStringBuilder& operator<<(unsigned i) { return AppendFormat("%u", i); }
57
58 SimpleStringBuilder& operator<<(long i) { // NOLINT
59 return AppendFormat("%ld", i);
60 }
61
62 SimpleStringBuilder& operator<<(long long i) { // NOLINT
63 return AppendFormat("%lld", i);
64 }
65
66 SimpleStringBuilder& operator<<(unsigned long i) { // NOLINT
67 return AppendFormat("%lu", i);
68 }
69
70 SimpleStringBuilder& operator<<(unsigned long long i) { // NOLINT
71 return AppendFormat("%llu", i);
72 }
73
74 SimpleStringBuilder& operator<<(float f) { return AppendFormat("%f", f); }
75
76 SimpleStringBuilder& operator<<(double f) { return AppendFormat("%f", f); }
77
78 SimpleStringBuilder& operator<<(long double f) {
79 return AppendFormat("%Lf", f);
80 }
81
82 // Returns a pointer to the built string. The name |str()| is borrowed for
83 // compatibility reasons as we replace usage of stringstream throughout the
84 // code base.
Karl Wiberg881f1682018-03-08 15:03:23 +010085 const char* str() const { return buffer_.data(); }
Tommifef05002018-02-27 13:51:08 +010086
87 // Returns the length of the string. The name |size()| is picked for STL
88 // compatibility reasons.
89 size_t size() const { return size_; }
90
91 // Allows appending a printf style formatted string.
Karl Wiberg881f1682018-03-08 15:03:23 +010092#if defined(__GNUC__)
93 __attribute__((__format__(__printf__, 2, 3)))
94#endif
95 SimpleStringBuilder&
96 AppendFormat(const char* fmt, ...) {
Tommifef05002018-02-27 13:51:08 +010097 va_list args;
98 va_start(args, fmt);
Karl Wiberg881f1682018-03-08 15:03:23 +010099 const int len =
100 std::vsnprintf(&buffer_[size_], buffer_.size() - size_, fmt, args);
101 if (len >= 0) {
102 const size_t chars_added = rtc::SafeMin(len, buffer_.size() - 1 - size_);
103 size_ += chars_added;
104 RTC_DCHECK_EQ(len, chars_added) << "Buffer size was insufficient";
105 } else {
106 // This should never happen, but we're paranoid, so re-write the
107 // terminator in case vsnprintf() overwrote it.
108 RTC_NOTREACHED();
109 buffer_[size_] = '\0';
110 }
Tommifef05002018-02-27 13:51:08 +0100111 va_end(args);
Karl Wiberg881f1682018-03-08 15:03:23 +0100112 RTC_DCHECK(IsConsistent());
Tommifef05002018-02-27 13:51:08 +0100113 return *this;
114 }
115
116 // An alternate way from operator<<() to append a string. This variant is
117 // slightly more efficient when the length of the string to append, is known.
118 SimpleStringBuilder& Append(const char* str, size_t length = SIZE_UNKNOWN) {
Karl Wiberg881f1682018-03-08 15:03:23 +0100119 const size_t chars_added =
120 rtc::strcpyn(&buffer_[size_], buffer_.size() - size_, str, length);
121 size_ += chars_added;
122 RTC_DCHECK_EQ(chars_added,
123 length == SIZE_UNKNOWN ? std::strlen(str) : length)
124 << "Buffer size was insufficient";
125 RTC_DCHECK(IsConsistent());
Tommifef05002018-02-27 13:51:08 +0100126 return *this;
127 }
128
129 private:
Karl Wiberg881f1682018-03-08 15:03:23 +0100130 bool IsConsistent() const {
131 return size_ <= buffer_.size() - 1 && buffer_[size_] == '\0';
Tommifef05002018-02-27 13:51:08 +0100132 }
133
Karl Wiberg881f1682018-03-08 15:03:23 +0100134 // An always-zero-terminated fixed-size buffer that we write to. The fixed
135 // size allows the buffer to be stack allocated, which helps performance.
Tommifef05002018-02-27 13:51:08 +0100136 // Having a fixed size is furthermore useful to avoid unnecessary resizing
137 // while building it.
Karl Wiberg881f1682018-03-08 15:03:23 +0100138 const rtc::ArrayView<char> buffer_;
Tommifef05002018-02-27 13:51:08 +0100139
140 // Represents the number of characters written to the buffer.
141 // This does not include the terminating '\0'.
142 size_t size_ = 0;
143};
144
145} // namespace rtc
146
147#endif // RTC_BASE_STRINGS_STRING_BUILDER_H_