2 * Copyright (C) 1996-2019 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 #ifndef SQUID_SRC_BASE_PACKABLESTREAM_H
10 #define SQUID_SRC_BASE_PACKABLESTREAM_H
12 #include "base/Packable.h"
17 * Provides a streambuf interface for writing to Packable objects.
18 * Typical use is via a PackableStream rather than direct manipulation
20 class PackableStreamBuf
: public std::streambuf
23 explicit PackableStreamBuf(Packable
&p
) : buf_(p
) { buf_
.buffer(); }
24 virtual ~PackableStreamBuf() = default;
27 /** flush the current buffer and the character that is overflowing
30 virtual int_type
overflow(int_type aChar
= traits_type::eof()) override
{
31 std::streamsize
pending(pptr() - pbase());
33 if (pending
&& sync())
34 return traits_type::eof();
36 if (aChar
!= traits_type::eof()) {
37 const char C
= static_cast<char>(aChar
);
41 pbump(-pending
); // Reset pptr().
45 /** push the buffer to the Packable */
46 virtual int sync() override
{
47 std::streamsize
pending(pptr() - pbase());
48 lowAppend(pbase(), pending
);
53 /** write multiple characters to the Packable
54 * - this is an optimisation method.
56 virtual std::streamsize
xsputn(const char * chars
, std::streamsize number
) override
{
57 lowAppend(chars
, number
);
62 void lowAppend(const char *s
, const std::streamsize n
) {buf_
.append(s
,n
);}
67 class PackableStream
: public std::ostream
70 /* create a stream for writing text etc into theBuffer */
71 // See http://www.codecomments.com/archive292-2005-2-396222.html
72 explicit PackableStream(Packable
&p
) : std::ostream(0), theBuffer(p
) {
73 rdbuf(&theBuffer
); // set the buffer to now-initialized theBuffer
74 clear(); //clear badbit set by calling init(0)
78 PackableStreamBuf theBuffer
;
81 #endif /* SQUID_SRC_BASE_PACKABLESTREAM_H */