1 // Copyright 2017 The Abseil Authors.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 #ifndef ABSL_STRINGS_INTERNAL_OSTRINGSTREAM_H_
16 #define ABSL_STRINGS_INTERNAL_OSTRINGSTREAM_H_
23 #include "absl/base/port.h"
26 namespace strings_internal {
28 // The same as std::ostringstream but appends to a user-specified std::string,
29 // and is faster. It is ~70% faster to create, ~50% faster to write to, and
30 // completely free to extract the result std::string.
33 // OStringStream strm(&s);
34 // strm << 42 << ' ' << 3.14; // appends to `s`
36 // The stream object doesn't have to be named. Starting from C++11 operator<<
37 // works with rvalues of std::ostream.
40 // OStringStream(&s) << 42 << ' ' << 3.14; // appends to `s`
42 // OStringStream is faster to create than std::ostringstream but it's still
43 // relatively slow. Avoid creating multiple streams where a single stream will
46 // Creates unnecessary instances of OStringStream: slow.
49 // OStringStream(&s) << 42;
50 // OStringStream(&s) << ' ';
51 // OStringStream(&s) << 3.14;
53 // Creates a single instance of OStringStream and reuses it: fast.
56 // OStringStream strm(&s);
61 // Note: flush() has no effect. No reason to call it.
62 class OStringStream : private std::basic_streambuf<char>, public std::ostream {
64 // The argument can be null, in which case you'll need to call str(p) with a
65 // non-null argument before you can write to the stream.
67 // The destructor of OStringStream doesn't use the std::string. It's OK to
68 // destroy the std::string before the stream.
69 explicit OStringStream(std::string* s) : std::ostream(this), s_(s) {}
71 std::string* str() { return s_; }
72 const std::string* str() const { return s_; }
73 void str(std::string* s) { s_ = s; }
76 using Buf = std::basic_streambuf<char>;
78 Buf::int_type overflow(int c) override;
79 std::streamsize xsputn(const char* s, std::streamsize n) override;
84 } // namespace strings_internal
87 #endif // ABSL_STRINGS_INTERNAL_OSTRINGSTREAM_H_