2 //===----------------------------------------------------------------------===//
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8 //===----------------------------------------------------------------------===//
10 #ifndef _LIBCPP_SYNCSTREAM
11 #define _LIBCPP_SYNCSTREAM
16 #include <ostream> // see [ostream.syn]
19 template<class charT, class traits, class Allocator>
22 // [syncstream.syncbuf.special], specialized algorithms
23 template<class charT, class traits, class Allocator>
24 void swap(basic_syncbuf<charT, traits, Allocator>&,
25 basic_syncbuf<charT, traits, Allocator>&);
27 using syncbuf = basic_syncbuf<char>;
28 using wsyncbuf = basic_syncbuf<wchar_t>;
30 template<class charT, class traits, class Allocator>
31 class basic_osyncstream;
33 using osyncstream = basic_osyncstream<char>;
34 using wosyncstream = basic_osyncstream<wchar_t>;
36 template<class charT, class traits, class Allocator>
37 class basic_syncbuf : public basic_streambuf<charT, traits> {
39 using char_type = charT;
40 using int_type = typename traits::int_type;
41 using pos_type = typename traits::pos_type;
42 using off_type = typename traits::off_type;
43 using traits_type = traits;
44 using allocator_type = Allocator;
46 using streambuf_type = basic_streambuf<charT, traits>;
48 // [syncstream.syncbuf.cons], construction and destruction
49 explicit basic_syncbuf(streambuf_type* obuf = nullptr)
50 : basic_syncbuf(obuf, Allocator()) {}
51 basic_syncbuf(streambuf_type*, const Allocator&);
52 basic_syncbuf(basic_syncbuf&&);
55 // [syncstream.syncbuf.assign], assignment and swap
56 basic_syncbuf& operator=(basic_syncbuf&&);
57 void swap(basic_syncbuf&);
59 // [syncstream.syncbuf.members], member functions
61 streambuf_type* get_wrapped() const noexcept;
62 allocator_type get_allocator() const noexcept;
63 void set_emit_on_sync(bool) noexcept;
66 // [syncstream.syncbuf.virtuals], overridden virtual functions
70 streambuf_type* wrapped; // exposition only
71 bool emit_on_sync{}; // exposition only
74 // [syncstream.syncbuf.special], specialized algorithms
75 template<class charT, class traits, class Allocator>
76 void swap(basic_syncbuf<charT, traits, Allocator>&,
77 basic_syncbuf<charT, traits, Allocator>&);
79 template<class charT, class traits, class Allocator>
80 class basic_osyncstream : public basic_ostream<charT, traits> {
82 using char_type = charT;
83 using int_type = typename traits::int_type;
84 using pos_type = typename traits::pos_type;
85 using off_type = typename traits::off_type;
86 using traits_type = traits;
88 using allocator_type = Allocator;
89 using streambuf_type = basic_streambuf<charT, traits>;
90 using syncbuf_type = basic_syncbuf<charT, traits, Allocator>;
92 // [syncstream.osyncstream.cons], construction and destruction
93 basic_osyncstream(streambuf_type*, const Allocator&);
94 explicit basic_osyncstream(streambuf_type* obuf)
95 : basic_osyncstream(obuf, Allocator()) {}
96 basic_osyncstream(basic_ostream<charT, traits>& os, const Allocator& allocator)
97 : basic_osyncstream(os.rdbuf(), allocator) {}
98 explicit basic_osyncstream(basic_ostream<charT, traits>& os)
99 : basic_osyncstream(os, Allocator()) {}
100 basic_osyncstream(basic_osyncstream&&) noexcept;
101 ~basic_osyncstream();
103 // [syncstream.osyncstream.assign], assignment
104 basic_osyncstream& operator=(basic_osyncstream&&);
106 // [syncstream.osyncstream.members], member functions
108 streambuf_type* get_wrapped() const noexcept;
109 syncbuf_type* rdbuf() const noexcept { return const_cast<syncbuf_type*>(addressof(sb)); }
112 syncbuf_type sb; // exposition only
119 #include <__utility/move.h>
120 #include <iosfwd> // required for declaration of default arguments
123 #ifndef _LIBCPP_HAS_NO_THREADS
126 # include <shared_mutex>
129 // standard-mandated includes
134 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
135 # pragma GCC system_header
139 #include <__undef_macros>
141 _LIBCPP_BEGIN_NAMESPACE_STD
143 #if _LIBCPP_STD_VER >= 20 && !defined(_LIBCPP_HAS_NO_EXPERIMENTAL_SYNCSTREAM)
145 // [syncstream.syncbuf.overview]/1
146 // Class template basic_syncbuf stores character data written to it,
147 // known as the associated output, into internal buffers allocated
148 // using the object's allocator. The associated output is transferred
149 // to the wrapped stream buffer object *wrapped when emit() is called
150 // or when the basic_syncbuf object is destroyed. Such transfers are
151 // atomic with respect to transfers by other basic_syncbuf objects
152 // with the same wrapped stream buffer object.
154 // This helper singleton is used to implement the required
155 // synchronisation guarantees.
156 # ifndef _LIBCPP_HAS_NO_THREADS
157 class __wrapped_streambuf_mutex {
158 _LIBCPP_HIDE_FROM_ABI __wrapped_streambuf_mutex() = default;
161 __wrapped_streambuf_mutex(const __wrapped_streambuf_mutex&) = delete;
162 __wrapped_streambuf_mutex& operator=(const __wrapped_streambuf_mutex&) = delete;
164 _LIBCPP_HIDE_FROM_ABI void __inc_reference([[maybe_unused]] void* __ptr) {
165 _LIBCPP_ASSERT_INTERNAL(__ptr != nullptr, "non-wrapped streambufs are never written to");
166 unique_lock __lock{__mutex_};
167 ++__lut_[reinterpret_cast<uintptr_t>(__ptr)].__count;
170 // pre: __ptr is in __lut_
171 _LIBCPP_HIDE_FROM_ABI void __dec_reference([[maybe_unused]] void* __ptr) noexcept {
172 unique_lock __lock{__mutex_};
174 auto __it = __get_it(__ptr);
175 if (__it->second.__count == 1)
178 --__it->second.__count;
182 // This function causes emit() aquire two mutexes:
184 // _ __get_it(__ptr)->second.__mutex exclusive
186 // Instead store a pointer to __get_it(__ptr)->second.__mutex when
187 // calling __inc_reference.
189 // pre: __ptr is in __lut_
190 [[nodiscard]] _LIBCPP_HIDE_FROM_ABI lock_guard<mutex> __get_lock([[maybe_unused]] void* __ptr) noexcept {
191 shared_lock __lock{__mutex_};
192 return lock_guard{__get_it(__ptr)->second.__mutex};
195 // This function is used for testing.
197 // It is allowed to call this function with a non-registered pointer.
198 [[nodiscard]] _LIBCPP_HIDE_FROM_ABI size_t __get_count([[maybe_unused]] void* __ptr) noexcept {
199 _LIBCPP_ASSERT_INTERNAL(__ptr != nullptr, "non-wrapped streambufs are never written to");
200 shared_lock __lock{__mutex_};
202 auto __it = __lut_.find(reinterpret_cast<uintptr_t>(__ptr));
203 return __it != __lut_.end() ? __it->second.__count : 0;
206 [[nodiscard]] static _LIBCPP_HIDE_FROM_ABI __wrapped_streambuf_mutex& __instance() noexcept {
207 static __wrapped_streambuf_mutex __result;
217 shared_mutex __mutex_;
218 map<uintptr_t, __value> __lut_;
220 [[nodiscard]] _LIBCPP_HIDE_FROM_ABI map<uintptr_t, __value>::iterator __get_it(void* __ptr) noexcept {
221 _LIBCPP_ASSERT_INTERNAL(__ptr != nullptr, "non-wrapped streambufs are never written to");
223 auto __it = __lut_.find(reinterpret_cast<uintptr_t>(__ptr));
224 _LIBCPP_ASSERT_INTERNAL(__it != __lut_.end(), "using a wrapped streambuf that has not been registered");
225 _LIBCPP_ASSERT_INTERNAL(__it->second.__count >= 1, "found an inactive streambuf wrapper");
229 # endif // _LIBCPP_HAS_NO_THREADS
233 // The class uses a basic_string<_CharT, _Traits, _Allocator> as
234 // internal buffer. Per [syncstream.syncbuf.cons]/4
235 // Remarks: A copy of allocator is used to allocate memory for
236 // internal buffers holding the associated output.
238 // Therefore the allocator used in the constructor is passed to the
239 // basic_string. The class does not keep a copy of this allocator.
240 template <class _CharT, class _Traits, class _Allocator>
241 class _LIBCPP_TEMPLATE_VIS basic_syncbuf : public basic_streambuf<_CharT, _Traits> {
243 using char_type = _CharT;
244 using traits_type = _Traits;
245 using int_type = typename traits_type::int_type;
246 using pos_type = typename traits_type::pos_type;
247 using off_type = typename traits_type::off_type;
248 using allocator_type = _Allocator;
250 using streambuf_type = basic_streambuf<_CharT, _Traits>;
252 // [syncstream.syncbuf.cons], construction and destruction
254 _LIBCPP_HIDE_FROM_ABI explicit basic_syncbuf(streambuf_type* __obuf = nullptr)
255 : basic_syncbuf(__obuf, _Allocator()) {}
257 _LIBCPP_HIDE_FROM_ABI basic_syncbuf(streambuf_type* __obuf, _Allocator const& __alloc)
258 : __wrapped_(__obuf), __str_(__alloc) {
262 _LIBCPP_HIDE_FROM_ABI basic_syncbuf(basic_syncbuf&& __other)
263 : __wrapped_(__other.get_wrapped()), __str_(std::move(__other.__str_)), __emit_on_sync_(__other.__emit_on_sync_) {
264 __move_common(__other);
267 _LIBCPP_HIDE_FROM_ABI ~basic_syncbuf() {
268 # ifndef _LIBCPP_HAS_NO_EXCEPTIONS
270 # endif // _LIBCPP_HAS_NO_EXCEPTIONS
272 # ifndef _LIBCPP_HAS_NO_EXCEPTIONS
275 # endif // _LIBCPP_HAS_NO_EXCEPTIONS
279 // [syncstream.syncbuf.assign], assignment and swap
281 _LIBCPP_HIDE_FROM_ABI basic_syncbuf& operator=(basic_syncbuf&& __other) {
282 // The function is specified to call emit. This call should
283 // propagate the exception thrown.
287 __wrapped_ = __other.get_wrapped();
288 __str_ = std::move(__other.__str_);
289 __emit_on_sync_ = __other.__emit_on_sync_;
291 __move_common(__other);
296 _LIBCPP_HIDE_FROM_ABI void swap(basic_syncbuf& __other) {
297 _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(
298 allocator_traits<_Allocator>::propagate_on_container_swap::value || get_allocator() == __other.get_allocator(),
299 "violates the mandated swap precondition");
301 basic_syncbuf __tmp(std::move(__other));
302 __other = std::move(*this);
303 *this = std::move(__tmp);
306 // [syncstream.syncbuf.members], member functions
308 _LIBCPP_HIDE_FROM_ABI bool emit() { return emit(false); }
310 _LIBCPP_HIDE_FROM_ABI streambuf_type* get_wrapped() const noexcept { return __wrapped_; }
312 _LIBCPP_HIDE_FROM_ABI allocator_type get_allocator() const noexcept { return __str_.get_allocator(); }
314 _LIBCPP_HIDE_FROM_ABI void set_emit_on_sync(bool __b) noexcept { __emit_on_sync_ = __b; }
317 // [syncstream.syncbuf.virtuals], overridden virtual functions
319 _LIBCPP_HIDE_FROM_ABI_VIRTUAL
320 int sync() override {
321 if (__emit_on_sync_ && !emit(true))
326 _LIBCPP_HIDE_FROM_ABI_VIRTUAL
327 int_type overflow(int_type __c = traits_type::eof()) override {
328 if (traits_type::eq_int_type(__c, traits_type::eof()))
329 return traits_type::not_eof(__c);
331 if (this->pptr() == this->epptr()) {
332 # ifndef _LIBCPP_HAS_NO_EXCEPTIONS
335 size_t __size = __str_.size();
336 __str_.resize(__str_.capacity() + 1);
337 _LIBCPP_ASSERT_INTERNAL(__str_.size() > __size, "the buffer hasn't grown");
339 char_type* __p = static_cast<char_type*>(__str_.data());
340 this->setp(__p, __p + __str_.size());
343 # ifndef _LIBCPP_HAS_NO_EXCEPTIONS
345 return traits_type::eof();
350 return this->sputc(traits_type::to_char_type(__c));
354 streambuf_type* __wrapped_;
356 // TODO Use a more generic buffer.
357 // That buffer should be light with almost no additional headers. Then
358 // it can be use here, the __retarget_buffer, and place that use
359 // the now deprecated get_temporary_buffer
361 basic_string<_CharT, _Traits, _Allocator> __str_;
362 bool __emit_on_sync_{false};
364 _LIBCPP_HIDE_FROM_ABI bool emit(bool __flush) {
368 # ifndef _LIBCPP_HAS_NO_THREADS
369 lock_guard<mutex> __lock = __wrapped_streambuf_mutex::__instance().__get_lock(__wrapped_);
372 bool __result = true;
373 if (this->pptr() != this->pbase()) {
374 _LIBCPP_ASSERT_INTERNAL(this->pbase() && this->pptr() && this->epptr(), "all put area pointers shold be valid");
376 // The __str_ does not know how much of its buffer is used. This
377 // information is extracted from the information of the base class.
378 __result &= (__wrapped_->sputn(this->pbase(), this->pptr() - this->pbase()) != -1);
379 // Clears the buffer, but keeps the contents (and) size of the
381 this->setp(this->pbase(), this->epptr());
385 __result &= (__wrapped_->pubsync() != -1);
390 _LIBCPP_HIDE_FROM_ABI void __move_common(basic_syncbuf& __other) {
391 // Adjust the put area pointers to our buffer.
392 char_type* __p = static_cast<char_type*>(__str_.data());
393 this->setp(__p, __p + __str_.size());
394 this->pbump(__other.pptr() - __other.pbase());
396 // Clear __other_ so the destructor will act as a NOP.
397 __other.setp(nullptr, nullptr);
398 __other.__wrapped_ = nullptr;
401 _LIBCPP_HIDE_FROM_ABI void __inc_reference() {
402 # ifndef _LIBCPP_HAS_NO_THREADS
404 __wrapped_streambuf_mutex::__instance().__inc_reference(__wrapped_);
408 _LIBCPP_HIDE_FROM_ABI void __dec_reference() noexcept {
409 # ifndef _LIBCPP_HAS_NO_THREADS
411 __wrapped_streambuf_mutex::__instance().__dec_reference(__wrapped_);
417 # ifndef _LIBCPP_HAS_NO_WIDE_CHARACTERS
421 // [syncstream.syncbuf.special], specialized algorithms
422 template <class _CharT, class _Traits, class _Allocator>
423 _LIBCPP_HIDE_FROM_ABI void
424 swap(basic_syncbuf<_CharT, _Traits, _Allocator>& __lhs, basic_syncbuf<_CharT, _Traits, _Allocator>& __rhs) {
430 template <class _CharT, class _Traits, class _Allocator>
431 class _LIBCPP_TEMPLATE_VIS basic_osyncstream : public basic_ostream<_CharT, _Traits> {
433 using char_type = _CharT;
434 using traits_type = _Traits;
435 using int_type = typename traits_type::int_type;
436 using pos_type = typename traits_type::pos_type;
437 using off_type = typename traits_type::off_type;
439 using allocator_type = _Allocator;
440 using streambuf_type = basic_streambuf<char_type, traits_type>;
441 using syncbuf_type = basic_syncbuf<char_type, traits_type, allocator_type>;
443 // [syncstream.osyncstream.cons], construction and destruction
445 _LIBCPP_HIDE_FROM_ABI basic_osyncstream(streambuf_type* __obuf, allocator_type const& __alloc)
446 : basic_ostream<_CharT, _Traits>(std::addressof(__sb_)), __sb_(__obuf, __alloc) {}
448 _LIBCPP_HIDE_FROM_ABI explicit basic_osyncstream(streambuf_type* __obuf)
449 : basic_osyncstream(__obuf, allocator_type()) {}
451 _LIBCPP_HIDE_FROM_ABI basic_osyncstream(basic_ostream<char_type, traits_type>& __os, allocator_type const& __alloc)
452 : basic_osyncstream(__os.rdbuf(), __alloc) {}
454 _LIBCPP_HIDE_FROM_ABI explicit basic_osyncstream(basic_ostream<char_type, traits_type>& __os)
455 : basic_osyncstream(__os, allocator_type()) {}
457 _LIBCPP_HIDE_FROM_ABI basic_osyncstream(basic_osyncstream&& __other) noexcept
458 : basic_ostream<_CharT, _Traits>(std::addressof(__sb_)), __sb_(std::move(__other.__sb_)) {
459 this->set_rdbuf(std::addressof(__sb_));
462 // [syncstream.osyncstream.assign], assignment
464 _LIBCPP_HIDE_FROM_ABI basic_osyncstream& operator=(basic_osyncstream&& __other) = default;
466 // [syncstream.osyncstream.members], member functions
468 _LIBCPP_HIDE_FROM_ABI void emit() {
469 // The basic_ostream::put places the sentry in a try
470 // catch, this does not match the wording of the standard
471 // [ostream.unformatted]
472 // TODO validate other unformatted output functions.
473 typename basic_ostream<char_type, traits_type>::sentry __s(*this);
475 # ifndef _LIBCPP_HAS_NO_EXCEPTIONS
479 if (__sb_.emit() == false)
480 this->setstate(ios::badbit);
481 # ifndef _LIBCPP_HAS_NO_EXCEPTIONS
483 this->__set_badbit_and_consider_rethrow();
489 _LIBCPP_HIDE_FROM_ABI streambuf_type* get_wrapped() const noexcept { return __sb_.get_wrapped(); }
491 _LIBCPP_HIDE_FROM_ABI syncbuf_type* rdbuf() const noexcept {
492 return const_cast<syncbuf_type*>(std::addressof(__sb_));
499 using std::osyncstream;
500 # ifndef _LIBCPP_HAS_NO_WIDE_CHARACTERS
501 using std::wosyncstream;
504 #endif // _LIBCPP_STD_VER >= 20 && !defined(_LIBCPP_HAS_NO_EXPERIMENTAL_SYNCSTREAM)
506 _LIBCPP_END_NAMESPACE_STD
510 #endif // _LIBCPP_SYNCSTREAM