2005-01-06 Benjamin Kosnik <bkoz@redhat.com>
[official-gcc.git] / libstdc++-v3 / include / bits / fstream.tcc
bloba9d157403fe6fb97c103608bd7158f8d75e94518
1 // File based streams -*- C++ -*-
3 // Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
4 // Free Software Foundation, Inc.
5 //
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)
10 // any later version.
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,
20 // USA.
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.
31 /** @file fstream.tcc
32  *  This is an internal header file, included by other library headers.
33  *  You should not attempt to use it directly.
34  */
37 // ISO C++ 14882: 27.8  File-based streams
40 #ifndef _FSTREAM_TCC
41 #define _FSTREAM_TCC 1
43 #pragma GCC system_header
45 namespace std
47   template<typename _CharT, typename _Traits>
48     void
49     basic_filebuf<_CharT, _Traits>::
50     _M_allocate_internal_buffer()
51     {
52       // Allocate internal buffer only if one doesn't already exist
53       // (either allocated or provided by the user via setbuf).
54       if (!_M_buf_allocated && !_M_buf)
55         {
56           _M_buf = new char_type[_M_buf_size];
57           _M_buf_allocated = true;
58         }
59     }
61   template<typename _CharT, typename _Traits>
62     void
63     basic_filebuf<_CharT, _Traits>::
64     _M_destroy_internal_buffer() throw()
65     {
66       if (_M_buf_allocated)
67         {
68           delete [] _M_buf;
69           _M_buf = NULL;
70           _M_buf_allocated = false;
71         }
72       delete [] _M_ext_buf;
73       _M_ext_buf = NULL;
74       _M_ext_buf_size = 0;
75       _M_ext_next = NULL;
76       _M_ext_end = NULL;
77     }
79   template<typename _CharT, typename _Traits>
80     basic_filebuf<_CharT, _Traits>::
81     basic_filebuf() : __streambuf_type(), _M_lock(), _M_file(&_M_lock),
82     _M_mode(ios_base::openmode(0)), _M_state_beg(), _M_state_cur(),
83     _M_state_last(), _M_buf(NULL), _M_buf_size(BUFSIZ),
84     _M_buf_allocated(false), _M_reading(false), _M_writing(false), _M_pback(), 
85     _M_pback_cur_save(0), _M_pback_end_save(0), _M_pback_init(false),
86     _M_codecvt(0), _M_ext_buf(0), _M_ext_buf_size(0), _M_ext_next(0),
87     _M_ext_end(0)
88     {
89       if (has_facet<__codecvt_type>(this->_M_buf_locale))
90         _M_codecvt = &use_facet<__codecvt_type>(this->_M_buf_locale);
91     }
93   template<typename _CharT, typename _Traits>
94     typename basic_filebuf<_CharT, _Traits>::__filebuf_type*
95     basic_filebuf<_CharT, _Traits>::
96     open(const char* __s, ios_base::openmode __mode)
97     {
98       __filebuf_type *__ret = NULL;
99       if (!this->is_open())
100         {
101           _M_file.open(__s, __mode);
102           if (this->is_open())
103             {
104               _M_allocate_internal_buffer();
105               _M_mode = __mode;
107               // Setup initial buffer to 'uncommitted' mode.
108               _M_reading = false;
109               _M_writing = false;
110               _M_set_buffer(-1);
112               // Reset to initial state.
113               _M_state_last = _M_state_cur = _M_state_beg;
115               // 27.8.1.3,4
116               if ((__mode & ios_base::ate)
117                   && this->seekoff(0, ios_base::end, __mode)
118                   == pos_type(off_type(-1)))
119                 this->close();
120               else
121                 __ret = this;
122             }
123         }
124       return __ret;
125     }
127   template<typename _CharT, typename _Traits>
128     typename basic_filebuf<_CharT, _Traits>::__filebuf_type*
129     basic_filebuf<_CharT, _Traits>::
130     close() throw()
131     {
132       __filebuf_type* __ret = NULL;
133       if (this->is_open())
134         {
135           bool __testfail = false;
136           try
137             {
138               if (!_M_terminate_output())
139                 __testfail = true;
140             }
141           catch(...)
142             { __testfail = true; }
144           // NB: Do this here so that re-opened filebufs will be cool...
145           _M_mode = ios_base::openmode(0);
146           _M_pback_init = false;
147           _M_destroy_internal_buffer();
148           _M_reading = false;
149           _M_writing = false;
150           _M_set_buffer(-1);
151           _M_state_last = _M_state_cur = _M_state_beg;
153           if (!_M_file.close())
154             __testfail = true;
156           if (!__testfail)
157             __ret = this;
158         }
159       return __ret;
160     }
162   template<typename _CharT, typename _Traits>
163     streamsize
164     basic_filebuf<_CharT, _Traits>::
165     showmanyc()
166     {
167       streamsize __ret = -1;
168       const bool __testin = _M_mode & ios_base::in;
169       if (__testin && this->is_open())
170         {
171           // For a stateful encoding (-1) the pending sequence might be just
172           // shift and unshift prefixes with no actual character.
173           __ret = this->egptr() - this->gptr();
174           if (__check_facet(_M_codecvt).encoding() >= 0)
175             __ret += _M_file.showmanyc() / _M_codecvt->max_length();
176         }
177       return __ret;
178     }
180   template<typename _CharT, typename _Traits>
181     typename basic_filebuf<_CharT, _Traits>::int_type
182     basic_filebuf<_CharT, _Traits>::
183     underflow()
184     {
185       int_type __ret = traits_type::eof();
186       const bool __testin = _M_mode & ios_base::in;
187       if (__testin && !_M_writing)
188         {
189           // Check for pback madness, and if so swich back to the
190           // normal buffers and jet outta here before expensive
191           // fileops happen...
192           _M_destroy_pback();
194           if (this->gptr() < this->egptr())
195             return traits_type::to_int_type(*this->gptr());
197           // Get and convert input sequence.
198           const size_t __buflen = _M_buf_size > 1
199                                   ? _M_buf_size - 1 : 1;
201           // Will be set to true if ::read() returns 0 indicating EOF.
202           bool __got_eof = false;
203           // Number of internal characters produced.
204           streamsize __ilen = 0;
205           codecvt_base::result __r = codecvt_base::ok;
206           if (__check_facet(_M_codecvt).always_noconv())
207             {
208               __ilen = _M_file.xsgetn(reinterpret_cast<char*>(this->eback()),
209                                       __buflen);
210               if (__ilen == 0)
211                 __got_eof = true;
212             }
213           else
214             {
215               // Worst-case number of external bytes.
216               // XXX Not done encoding() == -1.
217               const int __enc = _M_codecvt->encoding();
218               streamsize __blen; // Minimum buffer size.
219               streamsize __rlen; // Number of chars to read.
220               if (__enc > 0)
221                 __blen = __rlen = __buflen * __enc;
222               else
223                 {
224                   __blen = __buflen + _M_codecvt->max_length() - 1;
225                   __rlen = __buflen;
226                 }
227               const streamsize __remainder = _M_ext_end - _M_ext_next;
228               __rlen = __rlen > __remainder ? __rlen - __remainder : 0;
230               // An imbue in 'read' mode implies first converting the external
231               // chars already present.
232               if (_M_reading && this->egptr() == this->eback() && __remainder)
233                 __rlen = 0;
235               // Allocate buffer if necessary and move unconverted
236               // bytes to front.
237               if (_M_ext_buf_size < __blen)
238                 {
239                   char* __buf = new char[__blen];
240                   if (__remainder)
241                     std::memcpy(__buf, _M_ext_next, __remainder);
243                   delete [] _M_ext_buf;
244                   _M_ext_buf = __buf;
245                   _M_ext_buf_size = __blen;
246                 }
247               else if (__remainder)
248                 std::memmove(_M_ext_buf, _M_ext_next, __remainder);
250               _M_ext_next = _M_ext_buf;
251               _M_ext_end = _M_ext_buf + __remainder;
252               _M_state_last = _M_state_cur;
254               do
255                 {
256                   if (__rlen > 0)
257                     {
258                       // Sanity check!
259                       // This may fail if the return value of
260                       // codecvt::max_length() is bogus.
261                       if (_M_ext_end - _M_ext_buf + __rlen > _M_ext_buf_size)
262                         {
263                           __throw_ios_failure(__N("basic_filebuf::underflow "
264                                               "codecvt::max_length() "
265                                               "is not valid"));
266                         }
267                       streamsize __elen = _M_file.xsgetn(_M_ext_end, __rlen);
268                       if (__elen == 0)
269                         __got_eof = true;
270                       else if (__elen == -1)
271                         break;
272                       _M_ext_end += __elen;
273                     }
275                   char_type* __iend;
276                   __r = _M_codecvt->in(_M_state_cur, _M_ext_next,
277                                        _M_ext_end, _M_ext_next, this->eback(),
278                                        this->eback() + __buflen, __iend);
279                   if (__r == codecvt_base::noconv)
280                     {
281                       size_t __avail = _M_ext_end - _M_ext_buf;
282                       __ilen = std::min(__avail, __buflen);
283                       traits_type::copy(this->eback(),
284                                         reinterpret_cast<char_type*>(_M_ext_buf), __ilen);
285                       _M_ext_next = _M_ext_buf + __ilen;
286                     }
287                   else
288                     __ilen = __iend - this->eback();
290                   // _M_codecvt->in may return error while __ilen > 0: this is
291                   // ok, and actually occurs in case of mixed encodings (e.g.,
292                   // XML files).
293                   if (__r == codecvt_base::error)
294                     break;
296                   __rlen = 1;
297                 }
298               while (__ilen == 0 && !__got_eof);
299             }
301           if (__ilen > 0)
302             {
303               _M_set_buffer(__ilen);
304               _M_reading = true;
305               __ret = traits_type::to_int_type(*this->gptr());
306             }
307           else if (__got_eof)
308             {
309               // If the actual end of file is reached, set 'uncommitted'
310               // mode, thus allowing an immediate write without an
311               // intervening seek.
312               _M_set_buffer(-1);
313               _M_reading = false;
314               // However, reaching it while looping on partial means that
315               // the file has got an incomplete character.
316               if (__r == codecvt_base::partial)
317                 __throw_ios_failure(__N("basic_filebuf::underflow "
318                                     "incomplete character in file"));
319             }
320           else if (__r == codecvt_base::error)
321             __throw_ios_failure(__N("basic_filebuf::underflow "
322                                 "invalid byte sequence in file"));
323           else
324             __throw_ios_failure(__N("basic_filebuf::underflow "
325                                 "error reading the file"));
326         }
327       return __ret;
328     }
330   template<typename _CharT, typename _Traits>
331     typename basic_filebuf<_CharT, _Traits>::int_type
332     basic_filebuf<_CharT, _Traits>::
333     pbackfail(int_type __i)
334     {
335       int_type __ret = traits_type::eof();
336       const bool __testin = _M_mode & ios_base::in;
337       if (__testin && !_M_writing)
338         {
339           // Remember whether the pback buffer is active, otherwise below
340           // we may try to store in it a second char (libstdc++/9761).
341           const bool __testpb = _M_pback_init;
342           const bool __testeof = traits_type::eq_int_type(__i, __ret);
343           int_type __tmp;
344           if (this->eback() < this->gptr())
345             {
346               this->gbump(-1);
347               __tmp = traits_type::to_int_type(*this->gptr());
348             }
349           else if (this->seekoff(-1, ios_base::cur) != pos_type(off_type(-1)))
350             {
351               __tmp = this->underflow();
352               if (traits_type::eq_int_type(__tmp, __ret))
353                 return __ret;
354             }
355           else
356             {
357               // At the beginning of the buffer, need to make a
358               // putback position available.  But the seek may fail
359               // (f.i., at the beginning of a file, see
360               // libstdc++/9439) and in that case we return
361               // traits_type::eof().
362               return __ret;
363             }
365           // Try to put back __i into input sequence in one of three ways.
366           // Order these tests done in is unspecified by the standard.
367           if (!__testeof && traits_type::eq_int_type(__i, __tmp))
368             __ret = __i;
369           else if (__testeof)
370             __ret = traits_type::not_eof(__i);
371           else if (!__testpb)
372             {
373               _M_create_pback();
374               _M_reading = true;
375               *this->gptr() = traits_type::to_char_type(__i);
376               __ret = __i;
377             }
378         }
379       return __ret;
380     }
382   template<typename _CharT, typename _Traits>
383     typename basic_filebuf<_CharT, _Traits>::int_type
384     basic_filebuf<_CharT, _Traits>::
385     overflow(int_type __c)
386     {
387       int_type __ret = traits_type::eof();
388       const bool __testeof = traits_type::eq_int_type(__c, __ret);
389       const bool __testout = _M_mode & ios_base::out;
390       if (__testout && !_M_reading)
391         {
392           if (this->pbase() < this->pptr())
393             {
394               // If appropriate, append the overflow char.
395               if (!__testeof)
396                 {
397                   *this->pptr() = traits_type::to_char_type(__c);
398                   this->pbump(1);
399                 }
401               // Convert pending sequence to external representation,
402               // and output.
403               if (_M_convert_to_external(this->pbase(),
404                                          this->pptr() - this->pbase()))
405                 {
406                   _M_set_buffer(0);
407                   __ret = traits_type::not_eof(__c);
408                 }
409             }
410           else if (_M_buf_size > 1)
411             {
412               // Overflow in 'uncommitted' mode: set _M_writing, set
413               // the buffer to the initial 'write' mode, and put __c
414               // into the buffer.
415               _M_set_buffer(0);
416               _M_writing = true;
417               if (!__testeof)
418                 {
419                   *this->pptr() = traits_type::to_char_type(__c);
420                   this->pbump(1);
421                 }
422               __ret = traits_type::not_eof(__c);
423             }
424           else
425             {
426               // Unbuffered.
427               char_type __conv = traits_type::to_char_type(__c);
428               if (__testeof || _M_convert_to_external(&__conv, 1))
429                 {
430                   _M_writing = true;
431                   __ret = traits_type::not_eof(__c);
432                 }
433             }
434         }
435       return __ret;
436     }
438   template<typename _CharT, typename _Traits>
439     bool
440     basic_filebuf<_CharT, _Traits>::
441     _M_convert_to_external(_CharT* __ibuf, streamsize __ilen)
442     {
443       // Sizes of external and pending output.
444       streamsize __elen;
445       streamsize __plen;
446       if (__check_facet(_M_codecvt).always_noconv())
447         {
448           __elen = _M_file.xsputn(reinterpret_cast<char*>(__ibuf), __ilen);
449           __plen = __ilen;
450         }
451       else
452         {
453           // Worst-case number of external bytes needed.
454           // XXX Not done encoding() == -1.
455           streamsize __blen = __ilen * _M_codecvt->max_length();
456           char* __buf = static_cast<char*>(__builtin_alloca(__blen));
458           char* __bend;
459           const char_type* __iend;
460           codecvt_base::result __r;
461           __r = _M_codecvt->out(_M_state_cur, __ibuf, __ibuf + __ilen,
462                                 __iend, __buf, __buf + __blen, __bend);
464           if (__r == codecvt_base::ok || __r == codecvt_base::partial)
465             __blen = __bend - __buf;
466           else if (__r == codecvt_base::noconv)
467             {
468               // Same as the always_noconv case above.
469               __buf = reinterpret_cast<char*>(__ibuf);
470               __blen = __ilen;
471             }
472           else
473             __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external "
474                                     "conversion error"));
475   
476           __elen = _M_file.xsputn(__buf, __blen);
477           __plen = __blen;
479           // Try once more for partial conversions.
480           if (__r == codecvt_base::partial && __elen == __plen)
481             {
482               const char_type* __iresume = __iend;
483               streamsize __rlen = this->pptr() - __iend;
484               __r = _M_codecvt->out(_M_state_cur, __iresume,
485                                     __iresume + __rlen, __iend, __buf,
486                                     __buf + __blen, __bend);
487               if (__r != codecvt_base::error)
488                 {
489                   __rlen = __bend - __buf;
490                   __elen = _M_file.xsputn(__buf, __rlen);
491                   __plen = __rlen;
492                 }
493               else
494                 __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external "
495                                         "conversion error"));
496             }
497         }
498       return __elen == __plen;
499     }
501    template<typename _CharT, typename _Traits>
502      streamsize
503      basic_filebuf<_CharT, _Traits>::
504      xsgetn(_CharT* __s, streamsize __n)
505      {
506        // Clear out pback buffer before going on to the real deal...
507        streamsize __ret = 0;
508        if (_M_pback_init)
509          {
510            if (__n > 0 && this->gptr() == this->eback())
511              {
512                *__s++ = *this->gptr();
513                this->gbump(1);
514                __ret = 1;
515                --__n;
516              }
517            _M_destroy_pback();
518          }
519        
520        // Optimization in the always_noconv() case, to be generalized in the
521        // future: when __n > __buflen we read directly instead of using the
522        // buffer repeatedly.
523        const bool __testin = _M_mode & ios_base::in;
524        const streamsize __buflen = _M_buf_size > 1 ? _M_buf_size - 1
525                                                          : 1;
526        if (__n > __buflen && __check_facet(_M_codecvt).always_noconv()
527            && __testin && !_M_writing)
528          {
529            // First, copy the chars already present in the buffer.
530            const streamsize __avail = this->egptr() - this->gptr();
531            if (__avail != 0)
532              {
533                if (__avail == 1)
534                  *__s = *this->gptr();
535                else
536                  traits_type::copy(__s, this->gptr(), __avail);
537                __s += __avail;
538                this->gbump(__avail);
539                __ret += __avail;
540                __n -= __avail;
541              }
543            const streamsize __len = _M_file.xsgetn(reinterpret_cast<char*>(__s),
544                                                    __n);
545            if (__len == -1)
546              __throw_ios_failure(__N("basic_filebuf::xsgetn "
547                                      "error reading the file"));
548            __ret += __len;
549            if (__len == __n)
550              {
551                _M_set_buffer(0);
552                _M_reading = true;
553              }
554            else if (__len == 0)
555              {
556                // If end of file is reached, set 'uncommitted'
557                // mode, thus allowing an immediate write without
558                // an intervening seek.
559                _M_set_buffer(-1);
560                _M_reading = false;
561              }
562          }
563        else
564          __ret += __streambuf_type::xsgetn(__s, __n);
566        return __ret;
567      }
569    template<typename _CharT, typename _Traits>
570      streamsize
571      basic_filebuf<_CharT, _Traits>::
572      xsputn(const _CharT* __s, streamsize __n)
573      {
574        // Optimization in the always_noconv() case, to be generalized in the
575        // future: when __n is sufficiently large we write directly instead of
576        // using the buffer.
577        streamsize __ret = 0;
578        const bool __testout = _M_mode & ios_base::out;
579        if (__check_facet(_M_codecvt).always_noconv()
580            && __testout && !_M_reading)
581         {
582           // Measurement would reveal the best choice.
583           const streamsize __chunk = 1ul << 10;
584           streamsize __bufavail = this->epptr() - this->pptr();
586           // Don't mistake 'uncommitted' mode buffered with unbuffered.
587           if (!_M_writing && _M_buf_size > 1)
588             __bufavail = _M_buf_size - 1;
590           const streamsize __limit = std::min(__chunk, __bufavail);
591           if (__n >= __limit)
592             {
593               const streamsize __buffill = this->pptr() - this->pbase();
594               const char* __buf = reinterpret_cast<const char*>(this->pbase());
595               __ret = _M_file.xsputn_2(__buf, __buffill,
596                                        reinterpret_cast<const char*>(__s),
597                                        __n);
598               if (__ret == __buffill + __n)
599                 {
600                   _M_set_buffer(0);
601                   _M_writing = true;
602                 }
603               if (__ret > __buffill)
604                 __ret -= __buffill;
605               else
606                 __ret = 0;
607             }
608           else
609             __ret = __streambuf_type::xsputn(__s, __n);
610         }
611        else
612          __ret = __streambuf_type::xsputn(__s, __n);
613        return __ret;
614     }
616   template<typename _CharT, typename _Traits>
617     typename basic_filebuf<_CharT, _Traits>::__streambuf_type*
618     basic_filebuf<_CharT, _Traits>::
619     setbuf(char_type* __s, streamsize __n)
620     {
621       if (!this->is_open())
622         if (__s == 0 && __n == 0)
623           _M_buf_size = 1;
624         else if (__s && __n > 0)
625           {
626             // This is implementation-defined behavior, and assumes that
627             // an external char_type array of length __n exists and has
628             // been pre-allocated. If this is not the case, things will
629             // quickly blow up. When __n > 1, __n - 1 positions will be
630             // used for the get area, __n - 1 for the put area and 1
631             // position to host the overflow char of a full put area.
632             // When __n == 1, 1 position will be used for the get area
633             // and 0 for the put area, as in the unbuffered case above.
634             _M_buf = __s;
635             _M_buf_size = __n;
636           }
637       return this;
638     }
641   // According to 27.8.1.4 p11 - 13, seekoff should ignore the last
642   // argument (of type openmode).
643   template<typename _CharT, typename _Traits>
644     typename basic_filebuf<_CharT, _Traits>::pos_type
645     basic_filebuf<_CharT, _Traits>::
646     seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode)
647     {
648       int __width = 0;
649       if (_M_codecvt)
650         __width = _M_codecvt->encoding();
651       if (__width < 0)
652         __width = 0;
654       pos_type __ret =  pos_type(off_type(-1));
655       const bool __testfail = __off != 0 && __width <= 0;
656       if (this->is_open() && !__testfail)
657         {
658           // Ditch any pback buffers to avoid confusion.
659           _M_destroy_pback();
661           // Correct state at destination. Note that this is the correct
662           // state for the current position during output, because
663           // codecvt::unshift() returns the state to the initial state.
664           // This is also the correct state at the end of the file because
665           // an unshift sequence should have been written at the end.
666           __state_type __state = _M_state_beg;
667           off_type __computed_off = __off * __width;
668           if (_M_reading && __way == ios_base::cur)
669             {
670               if (_M_codecvt->always_noconv())
671                 __computed_off += this->gptr() - this->egptr();
672               else
673                 {
674                   // Calculate offset from _M_ext_buf that corresponds
675                   // to gptr(). Note: uses _M_state_last, which
676                   // corresponds to eback().
677                   const int __gptr_off =
678                     _M_codecvt->length(_M_state_last, _M_ext_buf, _M_ext_next,
679                                        this->gptr() - this->eback());
680                   __computed_off += _M_ext_buf + __gptr_off - _M_ext_end;
682                   // _M_state_last is modified by codecvt::length() so
683                   // it now corresponds to gptr().
684                   __state = _M_state_last;
685                 }
686             }
687           __ret = _M_seek(__computed_off, __way, __state);
688         }
689       return __ret;
690     }
692   // _GLIBCXX_RESOLVE_LIB_DEFECTS
693   // 171. Strange seekpos() semantics due to joint position
694   // According to the resolution of DR 171, seekpos should ignore the last
695   // argument (of type openmode).
696   template<typename _CharT, typename _Traits>
697     typename basic_filebuf<_CharT, _Traits>::pos_type
698     basic_filebuf<_CharT, _Traits>::
699     seekpos(pos_type __pos, ios_base::openmode)
700     {
701       pos_type __ret =  pos_type(off_type(-1));
702       if (this->is_open())
703         {
704           // Ditch any pback buffers to avoid confusion.
705           _M_destroy_pback();
706           __ret = _M_seek(off_type(__pos), ios_base::beg, __pos.state());
707         }
708       return __ret;
709     }
711   template<typename _CharT, typename _Traits>
712     typename basic_filebuf<_CharT, _Traits>::pos_type
713     basic_filebuf<_CharT, _Traits>::
714     _M_seek(off_type __off, ios_base::seekdir __way, __state_type __state)
715     {
716       pos_type __ret = pos_type(off_type(-1));
717       if (_M_terminate_output())
718         {
719           // Returns pos_type(off_type(-1)) in case of failure.
720           __ret = pos_type(_M_file.seekoff(__off, __way));
721           _M_reading = false;
722           _M_writing = false;
723           _M_ext_next = _M_ext_end = _M_ext_buf;
724           _M_set_buffer(-1);
725           _M_state_cur = __state;
726           __ret.state(_M_state_cur);
727         }
728       return __ret;
729     }
731   template<typename _CharT, typename _Traits>
732     bool
733     basic_filebuf<_CharT, _Traits>::
734     _M_terminate_output()
735     {
736       // Part one: update the output sequence.
737       bool __testvalid = true;
738       if (this->pbase() < this->pptr())
739         {
740           const int_type __tmp = this->overflow();
741           if (traits_type::eq_int_type(__tmp, traits_type::eof()))
742             __testvalid = false;
743         }
745       // Part two: output unshift sequence.
746       if (_M_writing && !__check_facet(_M_codecvt).always_noconv()
747           && __testvalid)
748         {
749           // Note: this value is arbitrary, since there is no way to
750           // get the length of the unshift sequence from codecvt,
751           // without calling unshift.
752           const size_t __blen = 128;
753           char __buf[__blen];
754           codecvt_base::result __r;
755           streamsize __ilen = 0;
757           do
758             {
759               char* __next;
760               __r = _M_codecvt->unshift(_M_state_cur, __buf,
761                                         __buf + __blen, __next);
762               if (__r == codecvt_base::error)
763                 __testvalid = false;
764               else if (__r == codecvt_base::ok ||
765                        __r == codecvt_base::partial)
766                 {
767                   __ilen = __next - __buf;
768                   if (__ilen > 0)
769                     {
770                       const streamsize __elen = _M_file.xsputn(__buf, __ilen);
771                       if (__elen != __ilen)
772                         __testvalid = false;
773                     }
774                 }
775             }
776           while (__r == codecvt_base::partial && __ilen > 0 && __testvalid);
778           if (__testvalid)
779             {
780               // This second call to overflow() is required by the standard,
781               // but it's not clear why it's needed, since the output buffer
782               // should be empty by this point (it should have been emptied
783               // in the first call to overflow()).
784               const int_type __tmp = this->overflow();
785               if (traits_type::eq_int_type(__tmp, traits_type::eof()))
786                 __testvalid = false;
787             }
788         }
789       return __testvalid;
790     }
792   template<typename _CharT, typename _Traits>
793     int
794     basic_filebuf<_CharT, _Traits>::
795     sync()
796     {
797       // Make sure that the internal buffer resyncs its idea of
798       // the file position with the external file.
799       int __ret = 0;
800       if (this->pbase() < this->pptr())
801         {
802           const int_type __tmp = this->overflow();
803           if (traits_type::eq_int_type(__tmp, traits_type::eof()))
804             __ret = -1;
805         }
806       return __ret;
807     }
809   template<typename _CharT, typename _Traits>
810     void
811     basic_filebuf<_CharT, _Traits>::
812     imbue(const locale& __loc)
813     {
814       bool __testvalid = true;
816       const __codecvt_type* _M_codecvt_tmp = 0;
817       if (__builtin_expect(has_facet<__codecvt_type>(__loc), true))
818         _M_codecvt_tmp = &use_facet<__codecvt_type>(__loc);
820       if (this->is_open())
821         {
822           // encoding() == -1 is ok only at the beginning.
823           if ((_M_reading || _M_writing)
824               && __check_facet(_M_codecvt).encoding() == -1)
825             __testvalid = false;
826           else
827             {
828               if (_M_reading)
829                 {
830                   if (__check_facet(_M_codecvt).always_noconv())
831                     {
832                       if (_M_codecvt_tmp
833                           && !__check_facet(_M_codecvt_tmp).always_noconv())
834                         __testvalid = this->seekoff(0, ios_base::cur, _M_mode)
835                                       != pos_type(off_type(-1));
836                     }
837                   else
838                     {
839                       // External position corresponding to gptr().
840                       _M_ext_next = _M_ext_buf
841                         + _M_codecvt->length(_M_state_last, _M_ext_buf, _M_ext_next,
842                                              this->gptr() - this->eback());
843                       const streamsize __remainder = _M_ext_end - _M_ext_next;
844                       if (__remainder)
845                         std::memmove(_M_ext_buf, _M_ext_next, __remainder);
847                       _M_ext_next = _M_ext_buf;
848                       _M_ext_end = _M_ext_buf + __remainder;
849                       _M_set_buffer(-1);
850                       _M_state_last = _M_state_cur = _M_state_beg;
851                     }
852                 }
853               else if (_M_writing && (__testvalid = _M_terminate_output()))
854                 _M_set_buffer(-1);
855             }
856         }
858       if (__testvalid)
859         _M_codecvt = _M_codecvt_tmp;
860       else
861         _M_codecvt = 0;
862     }
864   // Inhibit implicit instantiations for required instantiations,
865   // which are defined via explicit instantiations elsewhere.
866   // NB:  This syntax is a GNU extension.
867 #if _GLIBCXX_EXTERN_TEMPLATE
868   extern template class basic_filebuf<char>;
869   extern template class basic_ifstream<char>;
870   extern template class basic_ofstream<char>;
871   extern template class basic_fstream<char>;
873 #ifdef _GLIBCXX_USE_WCHAR_T
874   extern template class basic_filebuf<wchar_t>;
875   extern template class basic_ifstream<wchar_t>;
876   extern template class basic_ofstream<wchar_t>;
877   extern template class basic_fstream<wchar_t>;
878 #endif
879 #endif
880 } // namespace std
882 #endif