1 // Stream buffer classes -*- C++ -*-
3 // Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003
4 // Free Software Foundation, Inc.
6 // This file is part of the GNU ISO C++ Library. This library is free
7 // software; you can redistribute it and/or modify it under the
8 // terms of the GNU General Public License as published by the
9 // Free Software Foundation; either version 2, or (at your option)
12 // This library is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU General Public License for more details.
17 // You should have received a copy of the GNU General Public License along
18 // with this library; see the file COPYING. If not, write to the Free
19 // Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
22 // As a special exception, you may use this file as part of a free software
23 // library without restriction. Specifically, if other files instantiate
24 // templates or use macros or inline functions from this file, or you compile
25 // this file and link it with other files to produce an executable, this
26 // file does not by itself cause the resulting executable to be covered by
27 // the GNU General Public License. This exception does not however
28 // invalidate any other reasons why the executable file might be covered by
29 // the GNU General Public License.
32 // ISO C++ 14882: 27.5 Stream buffers
36 * This is a Standard C++ Library header. You should @c #include this header
37 * in your programs, rather than any of the "st[dl]_*.h" implementation files.
40 #ifndef _CPP_STREAMBUF
41 #define _CPP_STREAMBUF 1
43 #pragma GCC system_header
45 #include <bits/c++config.h>
47 #include <cstdio> // For SEEK_SET, SEEK_CUR, SEEK_END
48 #include <bits/localefwd.h>
49 #include <bits/ios_base.h>
58 template<typename _CharT, typename _Traits>
60 __copy_streambufs(basic_ios<_CharT, _Traits>& _ios,
61 basic_streambuf<_CharT, _Traits>* __sbin,
62 basic_streambuf<_CharT, _Traits>* __sbout);
65 * @brief The actual work of input and output (interface).
67 * This is a base class. Derived stream buffers each control a
68 * pair of character sequences: one for input, and one for output.
70 * Section [27.5.1] of the standard describes the requirements and
71 * behavior of stream buffer classes. That section (three paragraphs)
72 * is reproduced here, for simplicity and accuracy.
74 * -# Stream buffers can impose various constraints on the sequences
75 * they control. Some constraints are:
76 * - The controlled input sequence can be not readable.
77 * - The controlled output sequence can be not writable.
78 * - The controlled sequences can be associated with the contents of
79 * other representations for character sequences, such as external
81 * - The controlled sequences can support operations @e directly to or
82 * from associated sequences.
83 * - The controlled sequences can impose limitations on how the
84 * program can read characters from a sequence, write characters to
85 * a sequence, put characters back into an input sequence, or alter
86 * the stream position.
88 * -# Each sequence is characterized by three pointers which, if non-null,
89 * all point into the same @c charT array object. The array object
90 * represents, at any moment, a (sub)sequence of characters from the
91 * sequence. Operations performed on a sequence alter the values
92 * stored in these pointers, perform reads and writes directly to or
93 * from associated sequences, and alter "the stream position" and
94 * conversion state as needed to maintain this subsequence relationship.
95 * The three pointers are:
96 * - the <em>beginning pointer</em>, or lowest element address in the
97 * array (called @e xbeg here);
98 * - the <em>next pointer</em>, or next element address that is a
99 * current candidate for reading or writing (called @e xnext here);
100 * - the <em>end pointer</em>, or first element address beyond the
101 * end of the array (called @e xend here).
103 * -# The following semantic constraints shall always apply for any set
104 * of three pointers for a sequence, using the pointer names given
106 * - If @e xnext is not a null pointer, then @e xbeg and @e xend shall
107 * also be non-null pointers into the same @c charT array, as
108 * described above; otherwise, @e xbeg and @e xend shall also be null.
109 * - If @e xnext is not a null pointer and @e xnext < @e xend for an
110 * output sequence, then a <em>write position</em> is available.
111 * In this case, @e *xnext shall be assignable as the next element
112 * to write (to put, or to store a character value, into the sequence).
113 * - If @e xnext is not a null pointer and @e xbeg < @e xnext for an
114 * input sequence, then a <em>putback position</em> is available.
115 * In this case, @e xnext[-1] shall have a defined value and is the
116 * next (preceding) element to store a character that is put back
117 * into the input sequence.
118 * - If @e xnext is not a null pointer and @e xnext< @e xend for an
119 * input sequence, then a <em>read position</em> is available.
120 * In this case, @e *xnext shall have a defined value and is the
121 * next element to read (to get, or to obtain a character value,
122 * from the sequence).
124 template<typename _CharT, typename _Traits>
125 class basic_streambuf
130 * These are standard types. They permit a standardized way of
131 * referring to names of (or names dependant on) the template
132 * parameters, which are specific to the implementation.
134 typedef _CharT char_type;
135 typedef _Traits traits_type;
136 typedef typename traits_type::int_type int_type;
137 typedef typename traits_type::pos_type pos_type;
138 typedef typename traits_type::off_type off_type;
144 * These are non-standard types.
147 typedef ctype<char_type> __ctype_type;
148 typedef basic_streambuf<char_type, traits_type> __streambuf_type;
149 typedef typename traits_type::state_type __state_type;
152 friend class basic_ios<char_type, traits_type>;
153 friend class basic_istream<char_type, traits_type>;
154 friend class basic_ostream<char_type, traits_type>;
155 friend class istreambuf_iterator<char_type, traits_type>;
156 friend class ostreambuf_iterator<char_type, traits_type>;
159 __copy_streambufs<>(basic_ios<char_type, traits_type>& __ios,
160 __streambuf_type* __sbin,__streambuf_type* __sbout);
165 * Pointer to the beginning of internally-allocated space. Filebuf
166 * manually allocates/deallocates this, whereas stringstreams attempt
167 * to use the built-in intelligence of the string class. If you are
168 * managing memory, set this. If not, leave it NULL.
175 * Actual size of allocated internal buffer. Unused for sstreams,
176 * which have readily available _M_string.capacity().
183 * True iff _M_in_* and _M_out_* buffers should always point to
184 * the same place. True for fstreams, false for sstreams.
192 * This is based on _IO_FILE, just reordered to be more consistent,
193 * and is intended to be the most minimal abstraction for an
195 * - get == input == read
196 * - put == output == write
199 char_type* _M_in_beg; // Start of get area.
200 char_type* _M_in_cur; // Current read area.
201 char_type* _M_in_end; // End of get area.
202 char_type* _M_out_beg; // Start of put area.
203 char_type* _M_out_cur; // Current put area.
204 char_type* _M_out_end; // End of put area.
209 * _M_set_indeterminate and setp set it equal to _M_out_beg, then
210 * at each put operation it may be moved forward (toward _M_out_end)
211 * by _M_out_cur_move.
214 char_type* _M_out_lim; // End limit of used put area.
220 * Place to stash in || out || in | out settings for current streambuf.
223 ios_base::openmode _M_mode;
227 * Current locale setting.
230 locale _M_buf_locale;
235 * Necessary bits for putback buffer management. Only used in
236 * the basic_filebuf class, as necessary for the standard
239 * @note pbacks of over one character are not currently supported.
242 static const size_t _S_pback_size = 1;
243 char_type _M_pback[_S_pback_size];
244 char_type* _M_pback_cur_save;
245 char_type* _M_pback_end_save;
254 fpos<__state_type> _M_pos;
256 // Initializes pback buffers, and moves normal buffers to safety.
258 // _M_in_cur has already been moved back
264 size_t __dist = _M_in_end - _M_in_cur;
265 size_t __len = std::min(_S_pback_size, __dist);
266 traits_type::copy(_M_pback, _M_in_cur, __len);
267 _M_pback_cur_save = _M_in_cur;
268 _M_pback_end_save = _M_in_end;
269 this->setg(_M_pback, _M_pback, _M_pback + __len);
270 _M_pback_init = true;
274 // Deactivates pback buffer contents, and restores normal buffer.
276 // The pback buffer has only moved forward.
282 // Length _M_in_cur moved in the pback buffer.
283 size_t __off_cur = _M_in_cur - _M_pback;
285 // For in | out buffers, the end can be pushed back...
286 size_t __off_end = 0;
287 size_t __pback_len = _M_in_end - _M_pback;
288 size_t __save_len = _M_pback_end_save - _M_buf;
289 if (__pback_len > __save_len)
290 __off_end = __pback_len - __save_len;
292 this->setg(_M_buf, _M_pback_cur_save + __off_cur,
293 _M_pback_end_save + __off_end);
294 _M_pback_cur_save = NULL;
295 _M_pback_end_save = NULL;
296 _M_pback_init = false;
300 // Correctly sets the _M_in_cur pointer, and bumps the
301 // _M_out_cur pointer as well if necessary.
303 _M_in_cur_move(off_type __n) // argument needs to be +-
305 const bool __testout = _M_out_cur;
307 if (__testout && _M_buf_unified)
311 // Correctly sets the _M_out_cur pointer, and bumps the
312 // appropriate _M_out_lim and _M_in_end pointers as well. Necessary
313 // for the un-tied stringbufs, in in|out mode.
315 // __n + _M_out_[cur, lim] <= _M_out_end
316 // Assuming all _M_out_[beg, cur, lim] pointers are operating on
318 // _M_buf <= _M_*_ <= _M_out_end
320 _M_out_cur_move(off_type __n) // argument needs to be +-
322 const bool __testin = _M_in_cur;
325 if (__testin && _M_buf_unified)
327 if (_M_out_cur > _M_out_lim)
329 _M_out_lim = _M_out_cur;
330 // NB: in | out buffers drag the _M_in_end pointer along...
337 /// Destructor deallocates no buffer space.
341 _M_buf_unified = false;
343 _M_mode = ios_base::openmode(0);
346 // [27.5.2.2.1] locales
348 * @brief Entry point for imbue().
349 * @param loc The new locale.
350 * @return The previous locale.
352 * Calls the derived imbue(loc).
355 pubimbue(const locale &__loc)
357 locale __tmp(this->getloc());
363 * @brief Locale access.
364 * @return The current locale in effect.
366 * If pubimbue(loc) has been called, then the most recent @c loc
367 * is returned. Otherwise the global locale in effect at the time
368 * of construction is returned.
372 { return _M_buf_locale; }
374 // [27.5.2.2.2] buffer management and positioning
377 * @brief Entry points for derived buffer functions.
379 * The public versions of @c pubfoo dispatch to the protected
380 * derived @c foo member functions, passing the arguments (if any)
381 * and returning the result unchanged.
384 pubsetbuf(char_type* __s, streamsize __n)
385 { return this->setbuf(__s, __n); }
388 pubseekoff(off_type __off, ios_base::seekdir __way,
389 ios_base::openmode __mode = ios_base::in | ios_base::out)
390 { return this->seekoff(__off, __way, __mode); }
393 pubseekpos(pos_type __sp,
394 ios_base::openmode __mode = ios_base::in | ios_base::out)
395 { return this->seekpos(__sp, __mode); }
398 pubsync() { return this->sync(); }
401 // [27.5.2.2.3] get area
403 * @brief Looking ahead into the stream.
404 * @return The number of characters available.
406 * If a read position is available, returns the number of characters
407 * available for reading before the buffer must be refilled.
408 * Otherwise returns the derived @c showmanyc().
413 streamsize __ret = _M_in_end - _M_in_cur;
414 return __ret ? __ret : this->showmanyc();
418 * @brief Getting the next character.
419 * @return The next character, or eof.
421 * Calls @c sbumpc(), and if that function returns
422 * @c traits::eof(), so does this function. Otherwise, @c sgetc().
427 int_type __eof = traits_type::eof();
428 return (traits_type::eq_int_type(this->sbumpc(), __eof)
429 ? __eof : this->sgetc());
433 * @brief Getting the next character.
434 * @return The next character, or eof.
436 * If the input read position is available, returns that character
437 * and increments the read pointer, otherwise calls and returns
444 * @brief Getting the next character.
445 * @return The next character, or eof.
447 * If the input read position is available, returns that character,
448 * otherwise calls and returns @c underflow(). Does not move the
449 * read position after fetching the character.
455 if (_M_in_cur < _M_in_end)
456 __ret = traits_type::to_int_type(*(this->gptr()));
458 __ret = this->underflow();
463 * @brief Entry point for xsgetn.
464 * @param s A buffer area.
467 * Returns xsgetn(s,n). The effect is to fill @a s[0] through
468 * @a s[n-1] with characters from the input sequence, if possible.
471 sgetn(char_type* __s, streamsize __n)
472 { return this->xsgetn(__s, __n); }
474 // [27.5.2.2.4] putback
476 * @brief Pushing characters back into the input stream.
477 * @param c The character to push back.
478 * @return The previous character, if possible.
480 * Similar to sungetc(), but @a c is pushed onto the stream instead
481 * of "the previous character". If successful, the next character
482 * fetched from the input stream will be @a c.
485 sputbackc(char_type __c);
488 * @brief Moving backwards in the input stream.
489 * @return The previous character, if possible.
491 * If a putback position is available, this function decrements the
492 * input pointer and returns that character. Otherwise, calls and
493 * returns pbackfail(). The effect is to "unget" the last character
499 // [27.5.2.2.5] put area
501 * @brief Entry point for all single-character output functions.
502 * @param c A character to output.
503 * @return @a c, if possible.
505 * One of two public output functions.
507 * If a write position is available for the output sequence (i.e.,
508 * the buffer is not full), stores @a c in that position, increments
509 * the position, and returns @c traits::to_int_type(c). If a write
510 * position is not available, returns @c overflow(c).
513 sputc(char_type __c);
516 * @brief Entry point for all single-character output functions.
517 * @param s A buffer read area.
520 * One of two public output functions.
523 * Returns xsputn(s,n). The effect is to write @a s[0] through
524 * @a s[n-1] to the output sequence, if possible.
527 sputn(const char_type* __s, streamsize __n)
528 { return this->xsputn(__s, __n); }
532 * @brief Base constructor.
534 * Only called from derived constructors, and sets up all the
535 * buffer data to zero, including the pointers described in the
536 * basic_streambuf class description. Note that, as a result,
537 * - the class starts with no read nor write positions available,
538 * - this is not an error
541 : _M_buf(NULL), _M_buf_size(BUFSIZ), _M_buf_unified(false),
542 _M_in_beg(0), _M_in_cur(0), _M_in_end(0), _M_out_beg(0),
543 _M_out_cur(0), _M_out_end(0), _M_out_lim(0),
544 _M_mode(ios_base::openmode(0)), _M_buf_locale(locale()),
545 _M_pback_cur_save(0), _M_pback_end_save(0),
549 // [27.5.2.3.1] get area access
552 * @brief Access to the get area.
554 * These functions are only available to other protected functions,
555 * including derived classes.
557 * - eback() returns the beginning pointer for the input sequence
558 * - gptr() returns the next pointer for the input sequence
559 * - egptr() returns the end pointer for the input sequence
562 eback() const { return _M_in_beg; }
565 gptr() const { return _M_in_cur; }
568 egptr() const { return _M_in_end; }
572 * @brief Moving the read position.
573 * @param n The delta by which to move.
575 * This just advances the read position without returning any data.
578 gbump(int __n) { _M_in_cur += __n; }
581 * @brief Setting the three read area pointers.
582 * @param gbeg A pointer.
583 * @param gnext A pointer.
584 * @param gend A pointer.
585 * @post @a gbeg == @c eback(), @a gnext == @c gptr(), and
586 * @a gend == @c egptr()
589 setg(char_type* __gbeg, char_type* __gnext, char_type* __gend)
594 if (!(_M_mode & ios_base::in) && __gbeg && __gnext && __gend)
595 _M_mode = _M_mode | ios_base::in;
598 // [27.5.2.3.2] put area access
601 * @brief Access to the put area.
603 * These functions are only available to other protected functions,
604 * including derived classes.
606 * - pbase() returns the beginning pointer for the output sequence
607 * - pptr() returns the next pointer for the output sequence
608 * - epptr() returns the end pointer for the output sequence
611 pbase() const { return _M_out_beg; }
614 pptr() const { return _M_out_cur; }
617 epptr() const { return _M_out_end; }
621 * @brief Moving the write position.
622 * @param n The delta by which to move.
624 * This just advances the write position without returning any data.
627 pbump(int __n) { _M_out_cur += __n; }
630 * @brief Setting the three write area pointers.
631 * @param pbeg A pointer.
632 * @param pend A pointer.
633 * @post @a pbeg == @c pbase(), @a pbeg == @c pptr(), and
634 * @a pend == @c epptr()
637 setp(char_type* __pbeg, char_type* __pend)
639 _M_out_beg = _M_out_cur = _M_out_lim = __pbeg;
641 if (!(_M_mode & ios_base::out) && __pbeg && __pend)
642 _M_mode = _M_mode | ios_base::out;
645 // [27.5.2.4] virtual functions
646 // [27.5.2.4.1] locales
648 * @brief Changes translations.
649 * @param loc A new locale.
651 * Translations done during I/O which depend on the current locale
652 * are changed by this call. The standard adds, "Between invocations
653 * of this function a class derived from streambuf can safely cache
654 * results of calls to locale functions and to members of facets
655 * so obtained." This function simply stores the new locale for use
656 * by derived classes.
659 imbue(const locale& __loc)
661 if (_M_buf_locale != __loc)
662 _M_buf_locale = __loc;
665 // [27.5.2.4.2] buffer management and positioning
667 * @brief Maniuplates the buffer.
669 * Each derived class provides its own appropriate behavior. See
670 * the next-to-last paragraph of
671 * http://gcc.gnu.org/onlinedocs/libstdc++/27_io/howto.html#2 for
672 * more on this function.
674 * @note Base class version does nothing, returns @c this.
676 virtual basic_streambuf<char_type,_Traits>*
677 setbuf(char_type*, streamsize)
681 * @brief Alters the stream positions.
683 * Each derived class provides its own appropriate behavior.
684 * @note Base class version does nothing, returns a @c pos_type
685 * that represents an invalid stream position.
688 seekoff(off_type, ios_base::seekdir,
689 ios_base::openmode /*__mode*/ = ios_base::in | ios_base::out)
690 { return pos_type(off_type(-1)); }
693 * @brief Alters the stream positions.
695 * Each derived class provides its own appropriate behavior.
696 * @note Base class version does nothing, returns a @c pos_type
697 * that represents an invalid stream position.
701 ios_base::openmode /*__mode*/ = ios_base::in | ios_base::out)
702 { return pos_type(off_type(-1)); }
705 * @brief Synchronizes the buffer arrays with the controlled sequences.
706 * @return -1 on failure.
708 * Each derived class provides its own appropriate behavior,
709 * including the definition of "failure".
710 * @note Base class version does nothing, returns zero.
715 // [27.5.2.4.3] get area
717 * @brief Investigating the data available.
718 * @return An estimate of the number of characters available in the
719 * input sequence, or -1.
721 * "If it returns a positive value, then successive calls to
722 * @c underflow() will not return @c traits::eof() until at least that
723 * number of characters have been supplied. If @c showmanyc()
724 * returns -1, then calls to @c underflow() or @c uflow() will fail."
727 * @note Base class version does nothing, returns zero.
728 * @note The standard adds that "the intention is not only that the
729 * calls [to underflow or uflow] will not return @c eof() but
730 * that they will return "immediately".
731 * @note The standard adds that "the morphemes of @c showmanyc are
732 * "es-how-many-see", not "show-manic".
735 showmanyc() { return 0; }
738 * @brief Multiple character extraction.
739 * @param s A buffer area.
740 * @param n Maximum number of characters to assign.
741 * @return The number of characters assigned.
743 * Fills @a s[0] through @a s[n-1] with characters from the input
744 * sequence, as if by @c sbumpc(). Stops when either @a n characters
745 * have been copied, or when @c traits::eof() would be copied.
747 * It is expected that derived classes provide a more efficient
748 * implementation by overriding this definition.
751 xsgetn(char_type* __s, streamsize __n);
754 * @brief Fetches more data from the controlled sequence.
755 * @return The first character from the <em>pending sequence</em>.
757 * Informally, this function is called when the input buffer is
758 * exhausted (or does not exist, as buffering need not actually be
759 * done). If a buffer exists, it is "refilled". In either case, the
760 * next available character is returned, or @c traits::eof() to
761 * indicate a null pending sequence.
763 * For a formal definiton of the pending sequence, see a good text
764 * such as Langer & Kreft, or [27.5.2.4.3]/7-14.
766 * A functioning input streambuf can be created by overriding only
767 * this function (no buffer area will be used). For an example, see
768 * http://gcc.gnu.org/onlinedocs/libstdc++/27_io/howto.html#6
770 * @note Base class version does nothing, returns eof().
774 { return traits_type::eof(); }
777 * @brief Fetches more data from the controlled sequence.
778 * @return The first character from the <em>pending sequence</em>.
780 * Informally, this function does the same thing as @c underflow(),
781 * and in fact is required to call that function. It also returns
782 * the new character, like @c underflow() does. However, this
783 * function also moves the read position forward by one.
788 int_type __ret = traits_type::eof();
789 const bool __testeof =
790 traits_type::eq_int_type(this->underflow(), __ret);
791 if (!__testeof && _M_in_cur < _M_in_end)
793 __ret = traits_type::to_int_type(*_M_in_cur);
799 // [27.5.2.4.4] putback
801 * @brief Tries to back up the input sequence.
802 * @param c The character to be inserted back into the sequence.
803 * @return eof() on failure, "some other value" on success
804 * @post The constraints of @c gptr(), @c eback(), and @c pptr()
805 * are the same as for @c underflow().
807 * @note Base class version does nothing, returns eof().
810 pbackfail(int_type /* __c */ = traits_type::eof())
811 { return traits_type::eof(); }
815 * @brief Multiple character insertion.
816 * @param s A buffer area.
817 * @param n Maximum number of characters to write.
818 * @return The number of characters written.
820 * Writes @a s[0] through @a s[n-1] to the output sequence, as if
821 * by @c sputc(). Stops when either @a n characters have been
822 * copied, or when @c sputc() would return @c traits::eof().
824 * It is expected that derived classes provide a more efficient
825 * implementation by overriding this definition.
828 xsputn(const char_type* __s, streamsize __n);
831 * @brief Consumes data from the buffer; writes to the
832 * controlled sequence.
833 * @param c An additional character to consume.
834 * @return eof() to indicate failure, something else (usually
835 * @a c, or not_eof())
837 * Informally, this function is called when the output buffer is full
838 * (or does not exist, as buffering need not actually be done). If a
839 * buffer exists, it is "consumed", with "some effect" on the
840 * controlled sequence. (Typically, the buffer is written out to the
841 * sequence verbatim.) In either case, the character @a c is also
842 * written out, if @a c is not @c eof().
844 * For a formal definiton of this function, see a good text
845 * such as Langer & Kreft, or [27.5.2.4.5]/3-7.
847 * A functioning output streambuf can be created by overriding only
848 * this function (no buffer area will be used).
850 * @note Base class version does nothing, returns eof().
853 overflow(int_type /* __c */ = traits_type::eof())
854 { return traits_type::eof(); }
856 #ifdef _GLIBCPP_DEPRECATED
860 * @brief Tosses a character.
862 * Advances the read pointer, ignoring the character that would have
865 * See http://gcc.gnu.org/ml/libstdc++/2002-05/msg00168.html
867 * @note This function has been deprecated by the standard. You
868 * must define @c _GLIBCPP_DEPRECATED to make this visible; see
874 if (_M_in_cur < _M_in_end)
881 #ifdef _GLIBCPP_RESOLVE_LIB_DEFECTS
882 // Side effect of DR 50.
884 basic_streambuf(const __streambuf_type&) { };
887 operator=(const __streambuf_type&) { return *this; };
892 #ifdef _GLIBCPP_NO_TEMPLATE_EXPORT
895 #ifdef _GLIBCPP_FULLY_COMPLIANT_HEADERS
896 #include <bits/streambuf.tcc>