Import stripped gcc-4.0.1 sources.
[dragonfly.git] / contrib / gcc-4.0 / libstdc++-v3 / include / bits / fstream.tcc
blob40bf428e2c1f726206fbdb47be9d003f077a0897
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();
175 #if _GLIBCXX_HAVE_DOS_BASED_FILESYSTEM
176           // About this workaround, see libstdc++/20806.
177           const bool __testbinary = _M_mode & ios_base::binary;
178           if (__check_facet(_M_codecvt).encoding() >= 0
179               && __testbinary)
180 #else
181           if (__check_facet(_M_codecvt).encoding() >= 0)
182 #endif
183             __ret += _M_file.showmanyc() / _M_codecvt->max_length();
184         }
185       return __ret;
186     }
188   template<typename _CharT, typename _Traits>
189     typename basic_filebuf<_CharT, _Traits>::int_type
190     basic_filebuf<_CharT, _Traits>::
191     underflow()
192     {
193       int_type __ret = traits_type::eof();
194       const bool __testin = _M_mode & ios_base::in;
195       if (__testin && !_M_writing)
196         {
197           // Check for pback madness, and if so swich back to the
198           // normal buffers and jet outta here before expensive
199           // fileops happen...
200           _M_destroy_pback();
202           if (this->gptr() < this->egptr())
203             return traits_type::to_int_type(*this->gptr());
205           // Get and convert input sequence.
206           const size_t __buflen = _M_buf_size > 1
207                                   ? _M_buf_size - 1 : 1;
209           // Will be set to true if ::read() returns 0 indicating EOF.
210           bool __got_eof = false;
211           // Number of internal characters produced.
212           streamsize __ilen = 0;
213           codecvt_base::result __r = codecvt_base::ok;
214           if (__check_facet(_M_codecvt).always_noconv())
215             {
216               __ilen = _M_file.xsgetn(reinterpret_cast<char*>(this->eback()),
217                                       __buflen);
218               if (__ilen == 0)
219                 __got_eof = true;
220             }
221           else
222             {
223               // Worst-case number of external bytes.
224               // XXX Not done encoding() == -1.
225               const int __enc = _M_codecvt->encoding();
226               streamsize __blen; // Minimum buffer size.
227               streamsize __rlen; // Number of chars to read.
228               if (__enc > 0)
229                 __blen = __rlen = __buflen * __enc;
230               else
231                 {
232                   __blen = __buflen + _M_codecvt->max_length() - 1;
233                   __rlen = __buflen;
234                 }
235               const streamsize __remainder = _M_ext_end - _M_ext_next;
236               __rlen = __rlen > __remainder ? __rlen - __remainder : 0;
238               // An imbue in 'read' mode implies first converting the external
239               // chars already present.
240               if (_M_reading && this->egptr() == this->eback() && __remainder)
241                 __rlen = 0;
243               // Allocate buffer if necessary and move unconverted
244               // bytes to front.
245               if (_M_ext_buf_size < __blen)
246                 {
247                   char* __buf = new char[__blen];
248                   if (__remainder)
249                     std::memcpy(__buf, _M_ext_next, __remainder);
251                   delete [] _M_ext_buf;
252                   _M_ext_buf = __buf;
253                   _M_ext_buf_size = __blen;
254                 }
255               else if (__remainder)
256                 std::memmove(_M_ext_buf, _M_ext_next, __remainder);
258               _M_ext_next = _M_ext_buf;
259               _M_ext_end = _M_ext_buf + __remainder;
260               _M_state_last = _M_state_cur;
262               do
263                 {
264                   if (__rlen > 0)
265                     {
266                       // Sanity check!
267                       // This may fail if the return value of
268                       // codecvt::max_length() is bogus.
269                       if (_M_ext_end - _M_ext_buf + __rlen > _M_ext_buf_size)
270                         {
271                           __throw_ios_failure(__N("basic_filebuf::underflow "
272                                               "codecvt::max_length() "
273                                               "is not valid"));
274                         }
275                       streamsize __elen = _M_file.xsgetn(_M_ext_end, __rlen);
276                       if (__elen == 0)
277                         __got_eof = true;
278                       else if (__elen == -1)
279                         break;
280                       _M_ext_end += __elen;
281                     }
283                   char_type* __iend;
284                   __r = _M_codecvt->in(_M_state_cur, _M_ext_next,
285                                        _M_ext_end, _M_ext_next, this->eback(),
286                                        this->eback() + __buflen, __iend);
287                   if (__r == codecvt_base::noconv)
288                     {
289                       size_t __avail = _M_ext_end - _M_ext_buf;
290                       __ilen = std::min(__avail, __buflen);
291                       traits_type::copy(this->eback(),
292                                         reinterpret_cast<char_type*>(_M_ext_buf), __ilen);
293                       _M_ext_next = _M_ext_buf + __ilen;
294                     }
295                   else
296                     __ilen = __iend - this->eback();
298                   // _M_codecvt->in may return error while __ilen > 0: this is
299                   // ok, and actually occurs in case of mixed encodings (e.g.,
300                   // XML files).
301                   if (__r == codecvt_base::error)
302                     break;
304                   __rlen = 1;
305                 }
306               while (__ilen == 0 && !__got_eof);
307             }
309           if (__ilen > 0)
310             {
311               _M_set_buffer(__ilen);
312               _M_reading = true;
313               __ret = traits_type::to_int_type(*this->gptr());
314             }
315           else if (__got_eof)
316             {
317               // If the actual end of file is reached, set 'uncommitted'
318               // mode, thus allowing an immediate write without an
319               // intervening seek.
320               _M_set_buffer(-1);
321               _M_reading = false;
322               // However, reaching it while looping on partial means that
323               // the file has got an incomplete character.
324               if (__r == codecvt_base::partial)
325                 __throw_ios_failure(__N("basic_filebuf::underflow "
326                                     "incomplete character in file"));
327             }
328           else if (__r == codecvt_base::error)
329             __throw_ios_failure(__N("basic_filebuf::underflow "
330                                 "invalid byte sequence in file"));
331           else
332             __throw_ios_failure(__N("basic_filebuf::underflow "
333                                 "error reading the file"));
334         }
335       return __ret;
336     }
338   template<typename _CharT, typename _Traits>
339     typename basic_filebuf<_CharT, _Traits>::int_type
340     basic_filebuf<_CharT, _Traits>::
341     pbackfail(int_type __i)
342     {
343       int_type __ret = traits_type::eof();
344       const bool __testin = _M_mode & ios_base::in;
345       if (__testin && !_M_writing)
346         {
347           // Remember whether the pback buffer is active, otherwise below
348           // we may try to store in it a second char (libstdc++/9761).
349           const bool __testpb = _M_pback_init;
350           const bool __testeof = traits_type::eq_int_type(__i, __ret);
351           int_type __tmp;
352           if (this->eback() < this->gptr())
353             {
354               this->gbump(-1);
355               __tmp = traits_type::to_int_type(*this->gptr());
356             }
357           else if (this->seekoff(-1, ios_base::cur) != pos_type(off_type(-1)))
358             {
359               __tmp = this->underflow();
360               if (traits_type::eq_int_type(__tmp, __ret))
361                 return __ret;
362             }
363           else
364             {
365               // At the beginning of the buffer, need to make a
366               // putback position available.  But the seek may fail
367               // (f.i., at the beginning of a file, see
368               // libstdc++/9439) and in that case we return
369               // traits_type::eof().
370               return __ret;
371             }
373           // Try to put back __i into input sequence in one of three ways.
374           // Order these tests done in is unspecified by the standard.
375           if (!__testeof && traits_type::eq_int_type(__i, __tmp))
376             __ret = __i;
377           else if (__testeof)
378             __ret = traits_type::not_eof(__i);
379           else if (!__testpb)
380             {
381               _M_create_pback();
382               _M_reading = true;
383               *this->gptr() = traits_type::to_char_type(__i);
384               __ret = __i;
385             }
386         }
387       return __ret;
388     }
390   template<typename _CharT, typename _Traits>
391     typename basic_filebuf<_CharT, _Traits>::int_type
392     basic_filebuf<_CharT, _Traits>::
393     overflow(int_type __c)
394     {
395       int_type __ret = traits_type::eof();
396       const bool __testeof = traits_type::eq_int_type(__c, __ret);
397       const bool __testout = _M_mode & ios_base::out;
398       if (__testout && !_M_reading)
399         {
400           if (this->pbase() < this->pptr())
401             {
402               // If appropriate, append the overflow char.
403               if (!__testeof)
404                 {
405                   *this->pptr() = traits_type::to_char_type(__c);
406                   this->pbump(1);
407                 }
409               // Convert pending sequence to external representation,
410               // and output.
411               if (_M_convert_to_external(this->pbase(),
412                                          this->pptr() - this->pbase()))
413                 {
414                   _M_set_buffer(0);
415                   __ret = traits_type::not_eof(__c);
416                 }
417             }
418           else if (_M_buf_size > 1)
419             {
420               // Overflow in 'uncommitted' mode: set _M_writing, set
421               // the buffer to the initial 'write' mode, and put __c
422               // into the buffer.
423               _M_set_buffer(0);
424               _M_writing = true;
425               if (!__testeof)
426                 {
427                   *this->pptr() = traits_type::to_char_type(__c);
428                   this->pbump(1);
429                 }
430               __ret = traits_type::not_eof(__c);
431             }
432           else
433             {
434               // Unbuffered.
435               char_type __conv = traits_type::to_char_type(__c);
436               if (__testeof || _M_convert_to_external(&__conv, 1))
437                 {
438                   _M_writing = true;
439                   __ret = traits_type::not_eof(__c);
440                 }
441             }
442         }
443       return __ret;
444     }
446   template<typename _CharT, typename _Traits>
447     bool
448     basic_filebuf<_CharT, _Traits>::
449     _M_convert_to_external(_CharT* __ibuf, streamsize __ilen)
450     {
451       // Sizes of external and pending output.
452       streamsize __elen;
453       streamsize __plen;
454       if (__check_facet(_M_codecvt).always_noconv())
455         {
456           __elen = _M_file.xsputn(reinterpret_cast<char*>(__ibuf), __ilen);
457           __plen = __ilen;
458         }
459       else
460         {
461           // Worst-case number of external bytes needed.
462           // XXX Not done encoding() == -1.
463           streamsize __blen = __ilen * _M_codecvt->max_length();
464           char* __buf = static_cast<char*>(__builtin_alloca(__blen));
466           char* __bend;
467           const char_type* __iend;
468           codecvt_base::result __r;
469           __r = _M_codecvt->out(_M_state_cur, __ibuf, __ibuf + __ilen,
470                                 __iend, __buf, __buf + __blen, __bend);
472           if (__r == codecvt_base::ok || __r == codecvt_base::partial)
473             __blen = __bend - __buf;
474           else if (__r == codecvt_base::noconv)
475             {
476               // Same as the always_noconv case above.
477               __buf = reinterpret_cast<char*>(__ibuf);
478               __blen = __ilen;
479             }
480           else
481             __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external "
482                                     "conversion error"));
483   
484           __elen = _M_file.xsputn(__buf, __blen);
485           __plen = __blen;
487           // Try once more for partial conversions.
488           if (__r == codecvt_base::partial && __elen == __plen)
489             {
490               const char_type* __iresume = __iend;
491               streamsize __rlen = this->pptr() - __iend;
492               __r = _M_codecvt->out(_M_state_cur, __iresume,
493                                     __iresume + __rlen, __iend, __buf,
494                                     __buf + __blen, __bend);
495               if (__r != codecvt_base::error)
496                 {
497                   __rlen = __bend - __buf;
498                   __elen = _M_file.xsputn(__buf, __rlen);
499                   __plen = __rlen;
500                 }
501               else
502                 __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external "
503                                         "conversion error"));
504             }
505         }
506       return __elen == __plen;
507     }
509    template<typename _CharT, typename _Traits>
510      streamsize
511      basic_filebuf<_CharT, _Traits>::
512      xsgetn(_CharT* __s, streamsize __n)
513      {
514        // Clear out pback buffer before going on to the real deal...
515        streamsize __ret = 0;
516        if (_M_pback_init)
517          {
518            if (__n > 0 && this->gptr() == this->eback())
519              {
520                *__s++ = *this->gptr();
521                this->gbump(1);
522                __ret = 1;
523                --__n;
524              }
525            _M_destroy_pback();
526          }
527        
528        // Optimization in the always_noconv() case, to be generalized in the
529        // future: when __n > __buflen we read directly instead of using the
530        // buffer repeatedly.
531        const bool __testin = _M_mode & ios_base::in;
532        const streamsize __buflen = _M_buf_size > 1 ? _M_buf_size - 1 : 1;
534        if (__n > __buflen && __check_facet(_M_codecvt).always_noconv()
535            && __testin && !_M_writing)
536          {
537            // First, copy the chars already present in the buffer.
538            const streamsize __avail = this->egptr() - this->gptr();
539            if (__avail != 0)
540              {
541                if (__avail == 1)
542                  *__s = *this->gptr();
543                else
544                  traits_type::copy(__s, this->gptr(), __avail);
545                __s += __avail;
546                this->gbump(__avail);
547                __ret += __avail;
548                __n -= __avail;
549              }
551            // Need to loop in case of short reads (relatively common
552            // with pipes).
553            streamsize __len;
554            for (;;)
555              {
556                __len = _M_file.xsgetn(reinterpret_cast<char*>(__s),
557                                       __n);
558                if (__len == -1)
559                  __throw_ios_failure(__N("basic_filebuf::xsgetn "
560                                          "error reading the file"));
561                if (__len == 0)
562                  break;
564                __n -= __len;
565                __ret += __len;
566                if (__n == 0)
567                  break;
569                __s += __len;
570              }
572            if (__n == 0)
573              {
574                _M_set_buffer(0);
575                _M_reading = true;
576              }
577            else if (__len == 0)
578              {
579                // If end of file is reached, set 'uncommitted'
580                // mode, thus allowing an immediate write without
581                // an intervening seek.
582                _M_set_buffer(-1);
583                _M_reading = false;
584              }
585          }
586        else
587          __ret += __streambuf_type::xsgetn(__s, __n);
589        return __ret;
590      }
592    template<typename _CharT, typename _Traits>
593      streamsize
594      basic_filebuf<_CharT, _Traits>::
595      xsputn(const _CharT* __s, streamsize __n)
596      {
597        // Optimization in the always_noconv() case, to be generalized in the
598        // future: when __n is sufficiently large we write directly instead of
599        // using the buffer.
600        streamsize __ret = 0;
601        const bool __testout = _M_mode & ios_base::out;
602        if (__check_facet(_M_codecvt).always_noconv()
603            && __testout && !_M_reading)
604         {
605           // Measurement would reveal the best choice.
606           const streamsize __chunk = 1ul << 10;
607           streamsize __bufavail = this->epptr() - this->pptr();
609           // Don't mistake 'uncommitted' mode buffered with unbuffered.
610           if (!_M_writing && _M_buf_size > 1)
611             __bufavail = _M_buf_size - 1;
613           const streamsize __limit = std::min(__chunk, __bufavail);
614           if (__n >= __limit)
615             {
616               const streamsize __buffill = this->pptr() - this->pbase();
617               const char* __buf = reinterpret_cast<const char*>(this->pbase());
618               __ret = _M_file.xsputn_2(__buf, __buffill,
619                                        reinterpret_cast<const char*>(__s),
620                                        __n);
621               if (__ret == __buffill + __n)
622                 {
623                   _M_set_buffer(0);
624                   _M_writing = true;
625                 }
626               if (__ret > __buffill)
627                 __ret -= __buffill;
628               else
629                 __ret = 0;
630             }
631           else
632             __ret = __streambuf_type::xsputn(__s, __n);
633         }
634        else
635          __ret = __streambuf_type::xsputn(__s, __n);
636        return __ret;
637     }
639   template<typename _CharT, typename _Traits>
640     typename basic_filebuf<_CharT, _Traits>::__streambuf_type*
641     basic_filebuf<_CharT, _Traits>::
642     setbuf(char_type* __s, streamsize __n)
643     {
644       if (!this->is_open())
645         if (__s == 0 && __n == 0)
646           _M_buf_size = 1;
647         else if (__s && __n > 0)
648           {
649             // This is implementation-defined behavior, and assumes that
650             // an external char_type array of length __n exists and has
651             // been pre-allocated. If this is not the case, things will
652             // quickly blow up. When __n > 1, __n - 1 positions will be
653             // used for the get area, __n - 1 for the put area and 1
654             // position to host the overflow char of a full put area.
655             // When __n == 1, 1 position will be used for the get area
656             // and 0 for the put area, as in the unbuffered case above.
657             _M_buf = __s;
658             _M_buf_size = __n;
659           }
660       return this;
661     }
664   // According to 27.8.1.4 p11 - 13, seekoff should ignore the last
665   // argument (of type openmode).
666   template<typename _CharT, typename _Traits>
667     typename basic_filebuf<_CharT, _Traits>::pos_type
668     basic_filebuf<_CharT, _Traits>::
669     seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode)
670     {
671       int __width = 0;
672       if (_M_codecvt)
673         __width = _M_codecvt->encoding();
674       if (__width < 0)
675         __width = 0;
677       pos_type __ret =  pos_type(off_type(-1));
678       const bool __testfail = __off != 0 && __width <= 0;
679       if (this->is_open() && !__testfail)
680         {
681           // Ditch any pback buffers to avoid confusion.
682           _M_destroy_pback();
684           // Correct state at destination. Note that this is the correct
685           // state for the current position during output, because
686           // codecvt::unshift() returns the state to the initial state.
687           // This is also the correct state at the end of the file because
688           // an unshift sequence should have been written at the end.
689           __state_type __state = _M_state_beg;
690           off_type __computed_off = __off * __width;
691           if (_M_reading && __way == ios_base::cur)
692             {
693               if (_M_codecvt->always_noconv())
694                 __computed_off += this->gptr() - this->egptr();
695               else
696                 {
697                   // Calculate offset from _M_ext_buf that corresponds
698                   // to gptr(). Note: uses _M_state_last, which
699                   // corresponds to eback().
700                   const int __gptr_off =
701                     _M_codecvt->length(_M_state_last, _M_ext_buf, _M_ext_next,
702                                        this->gptr() - this->eback());
703                   __computed_off += _M_ext_buf + __gptr_off - _M_ext_end;
705                   // _M_state_last is modified by codecvt::length() so
706                   // it now corresponds to gptr().
707                   __state = _M_state_last;
708                 }
709             }
710           __ret = _M_seek(__computed_off, __way, __state);
711         }
712       return __ret;
713     }
715   // _GLIBCXX_RESOLVE_LIB_DEFECTS
716   // 171. Strange seekpos() semantics due to joint position
717   // According to the resolution of DR 171, seekpos should ignore the last
718   // argument (of type openmode).
719   template<typename _CharT, typename _Traits>
720     typename basic_filebuf<_CharT, _Traits>::pos_type
721     basic_filebuf<_CharT, _Traits>::
722     seekpos(pos_type __pos, ios_base::openmode)
723     {
724       pos_type __ret =  pos_type(off_type(-1));
725       if (this->is_open())
726         {
727           // Ditch any pback buffers to avoid confusion.
728           _M_destroy_pback();
729           __ret = _M_seek(off_type(__pos), ios_base::beg, __pos.state());
730         }
731       return __ret;
732     }
734   template<typename _CharT, typename _Traits>
735     typename basic_filebuf<_CharT, _Traits>::pos_type
736     basic_filebuf<_CharT, _Traits>::
737     _M_seek(off_type __off, ios_base::seekdir __way, __state_type __state)
738     {
739       pos_type __ret = pos_type(off_type(-1));
740       if (_M_terminate_output())
741         {
742           // Returns pos_type(off_type(-1)) in case of failure.
743           __ret = pos_type(_M_file.seekoff(__off, __way));
744           _M_reading = false;
745           _M_writing = false;
746           _M_ext_next = _M_ext_end = _M_ext_buf;
747           _M_set_buffer(-1);
748           _M_state_cur = __state;
749           __ret.state(_M_state_cur);
750         }
751       return __ret;
752     }
754   template<typename _CharT, typename _Traits>
755     bool
756     basic_filebuf<_CharT, _Traits>::
757     _M_terminate_output()
758     {
759       // Part one: update the output sequence.
760       bool __testvalid = true;
761       if (this->pbase() < this->pptr())
762         {
763           const int_type __tmp = this->overflow();
764           if (traits_type::eq_int_type(__tmp, traits_type::eof()))
765             __testvalid = false;
766         }
768       // Part two: output unshift sequence.
769       if (_M_writing && !__check_facet(_M_codecvt).always_noconv()
770           && __testvalid)
771         {
772           // Note: this value is arbitrary, since there is no way to
773           // get the length of the unshift sequence from codecvt,
774           // without calling unshift.
775           const size_t __blen = 128;
776           char __buf[__blen];
777           codecvt_base::result __r;
778           streamsize __ilen = 0;
780           do
781             {
782               char* __next;
783               __r = _M_codecvt->unshift(_M_state_cur, __buf,
784                                         __buf + __blen, __next);
785               if (__r == codecvt_base::error)
786                 __testvalid = false;
787               else if (__r == codecvt_base::ok ||
788                        __r == codecvt_base::partial)
789                 {
790                   __ilen = __next - __buf;
791                   if (__ilen > 0)
792                     {
793                       const streamsize __elen = _M_file.xsputn(__buf, __ilen);
794                       if (__elen != __ilen)
795                         __testvalid = false;
796                     }
797                 }
798             }
799           while (__r == codecvt_base::partial && __ilen > 0 && __testvalid);
801           if (__testvalid)
802             {
803               // This second call to overflow() is required by the standard,
804               // but it's not clear why it's needed, since the output buffer
805               // should be empty by this point (it should have been emptied
806               // in the first call to overflow()).
807               const int_type __tmp = this->overflow();
808               if (traits_type::eq_int_type(__tmp, traits_type::eof()))
809                 __testvalid = false;
810             }
811         }
812       return __testvalid;
813     }
815   template<typename _CharT, typename _Traits>
816     int
817     basic_filebuf<_CharT, _Traits>::
818     sync()
819     {
820       // Make sure that the internal buffer resyncs its idea of
821       // the file position with the external file.
822       int __ret = 0;
823       if (this->pbase() < this->pptr())
824         {
825           const int_type __tmp = this->overflow();
826           if (traits_type::eq_int_type(__tmp, traits_type::eof()))
827             __ret = -1;
828         }
829       return __ret;
830     }
832   template<typename _CharT, typename _Traits>
833     void
834     basic_filebuf<_CharT, _Traits>::
835     imbue(const locale& __loc)
836     {
837       bool __testvalid = true;
839       const __codecvt_type* _M_codecvt_tmp = 0;
840       if (__builtin_expect(has_facet<__codecvt_type>(__loc), true))
841         _M_codecvt_tmp = &use_facet<__codecvt_type>(__loc);
843       if (this->is_open())
844         {
845           // encoding() == -1 is ok only at the beginning.
846           if ((_M_reading || _M_writing)
847               && __check_facet(_M_codecvt).encoding() == -1)
848             __testvalid = false;
849           else
850             {
851               if (_M_reading)
852                 {
853                   if (__check_facet(_M_codecvt).always_noconv())
854                     {
855                       if (_M_codecvt_tmp
856                           && !__check_facet(_M_codecvt_tmp).always_noconv())
857                         __testvalid = this->seekoff(0, ios_base::cur, _M_mode)
858                                       != pos_type(off_type(-1));
859                     }
860                   else
861                     {
862                       // External position corresponding to gptr().
863                       _M_ext_next = _M_ext_buf
864                         + _M_codecvt->length(_M_state_last, _M_ext_buf, _M_ext_next,
865                                              this->gptr() - this->eback());
866                       const streamsize __remainder = _M_ext_end - _M_ext_next;
867                       if (__remainder)
868                         std::memmove(_M_ext_buf, _M_ext_next, __remainder);
870                       _M_ext_next = _M_ext_buf;
871                       _M_ext_end = _M_ext_buf + __remainder;
872                       _M_set_buffer(-1);
873                       _M_state_last = _M_state_cur = _M_state_beg;
874                     }
875                 }
876               else if (_M_writing && (__testvalid = _M_terminate_output()))
877                 _M_set_buffer(-1);
878             }
879         }
881       if (__testvalid)
882         _M_codecvt = _M_codecvt_tmp;
883       else
884         _M_codecvt = 0;
885     }
887   // Inhibit implicit instantiations for required instantiations,
888   // which are defined via explicit instantiations elsewhere.
889   // NB:  This syntax is a GNU extension.
890 #if _GLIBCXX_EXTERN_TEMPLATE
891   extern template class basic_filebuf<char>;
892   extern template class basic_ifstream<char>;
893   extern template class basic_ofstream<char>;
894   extern template class basic_fstream<char>;
896 #ifdef _GLIBCXX_USE_WCHAR_T
897   extern template class basic_filebuf<wchar_t>;
898   extern template class basic_ifstream<wchar_t>;
899   extern template class basic_ofstream<wchar_t>;
900   extern template class basic_fstream<wchar_t>;
901 #endif
902 #endif
903 } // namespace std
905 #endif