/*
 * Copyright (c) 1998
 * Silicon Graphics Computer Systems, Inc.
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Silicon Graphics makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 */ 

// This header defines classes basic_stringbuf, basic_istringstream,
// basic_ostringstream, and basic_stringstream.  These classes 
// represent streamsbufs and streams whose sources or destinations are
// C++ strings.

#ifndef __SGI_STL_SSTREAM
#define __SGI_STL_SSTREAM

#if defined(__sgi) && !defined(__GNUC__) && !defined(_STANDARD_C_PLUS_PLUS)
#error This header file requires the -LANG:std option
#endif

#include <istream>              // Includes <ostream>, <ios>, <iosfwd>
#include <string>

__STL_BEGIN_NAMESPACE

//----------------------------------------------------------------------
// This version of basic_stringbuf relies on the internal details of
// basic_string.  It relies on the fact that, in this implementation,
// basic_string's iterators are pointers.  It also assumes (as allowed
// by the standard) that _CharT is a POD type.

// We have a very small buffer for the put area, just so that we don't
// have to use append() for every sputc.  Conceptually, the buffer
// immediately follows the end of the underlying string.  We use this
// buffer when appending to write-only streambufs, but we don't use it
// for read-write streambufs.

template <class _CharT, class _Traits, class _Alloc>
class basic_stringbuf : public basic_streambuf<_CharT, _Traits>
{
public:                         // Typedefs.
  typedef _CharT                     char_type;
  typedef typename _Traits::int_type int_type;
  typedef typename _Traits::pos_type pos_type;
  typedef typename _Traits::off_type off_type;
  typedef _Traits                    traits_type;

  typedef basic_streambuf<_CharT, _Traits>          _Base;
  typedef basic_string<_CharT, _Traits, _Alloc>     _String;

public:                         // Constructors, destructor.
  explicit basic_stringbuf(ios_base::openmode __mode
                                      = ios_base::in | ios_base::out);
  explicit basic_stringbuf(const _String& __s, ios_base::openmode __mode
                                      = ios_base::in | ios_base::out);
  virtual ~basic_stringbuf();

public:                         // Get or set the string.
  _String str() const { _M_append_buffer(); return _M_str; }
  void str(const _String& __s);

protected:                      // Overridden virtual member functions.
  virtual int_type underflow();
  virtual int_type uflow();
  virtual int_type pbackfail(int_type __c = _Traits::eof());
  virtual int_type overflow(int_type __c = _Traits::eof());

  virtual streamsize xsputn(const char_type* __s, streamsize __n);
  virtual streamsize _M_xsputnc(char_type __c, streamsize __n);

  virtual _Base* setbuf(_CharT* __buf, streamsize __n);
  virtual pos_type seekoff(off_type __off, ios_base::seekdir __dir,
                           ios_base::openmode __mode 
                                      = ios_base::in | ios_base::out);
  virtual pos_type seekpos(pos_type __pos, ios_base::openmode __mode 
                                      = ios_base::in | ios_base::out);

private:                        // Helper functions.
  // Append the internal buffer to the string if necessary.
  void _M_append_buffer() const;

private:
  ios_base::openmode _M_mode;
  mutable _String _M_str;

  enum { _S_BufSiz = 8 };
  _CharT _M_Buf[_S_BufSiz];
};

//----------------------------------------------------------------------
// Non-inline member functions.

// Constructors.  Note that the base class constructor sets all of the
// get and area pointers to null.

template <class _CharT, class _Traits, class _Alloc>
basic_stringbuf<_CharT, _Traits, _Alloc>
  ::basic_stringbuf(ios_base::openmode __mode)
    : _Base(), _M_mode(__mode), _M_str()
{}

template <class _CharT, class _Traits, class _Alloc>
basic_stringbuf<_CharT, _Traits, _Alloc>
  ::basic_stringbuf(const _String& __s, ios_base::openmode __mode)
    : _Base(), _M_mode(__mode), _M_str(__s)
{
  // The initial read position is the beginning of the string.
  if (_M_mode & ios_base::in)
    this->setg(_M_str.begin(), _M_str.begin(), _M_str.end());

  // The initial write position is the beginning of the string.
  if (_M_mode & ios_base::out)
    this->setp(_M_str.begin(), _M_str.end());
}

template <class _CharT, class _Traits, class _Alloc>
basic_stringbuf<_CharT, _Traits, _Alloc>::~basic_stringbuf()
{}

// Set the underlying string to a new value.
template <class _CharT, class _Traits, class _Alloc>
void 
basic_stringbuf<_CharT, _Traits, _Alloc>::str(const _String& __s)
{
  _M_str = __s;
  // The initial read position is the beginning of the string.
  if (_M_mode & ios_base::in)
    this->setg(_M_str.begin(), _M_str.begin(), _M_str.end());

  // The initial write position is the beginning of the string.
  if (_M_mode & ios_base::out)
    this->setp(_M_str.begin(), _M_str.end());
}

// Precondition: gptr() >= egptr().  Returns a character, if one is available.
template <class _CharT, class _Traits, class _Alloc>
typename basic_stringbuf<_CharT, _Traits, _Alloc>::int_type
basic_stringbuf<_CharT, _Traits, _Alloc>::underflow()
{
  return this->gptr() != this->egptr()
    ? _Traits::to_int_type(*this->gptr())
    : _Traits::eof();
}

// Precondition: gptr() >= egptr().
template <class _CharT, class _Traits, class _Alloc>
typename basic_stringbuf<_CharT, _Traits, _Alloc>::int_type
basic_stringbuf<_CharT, _Traits, _Alloc>::uflow()
{
  if (this->gptr() != this->egptr()) {
    int_type __c = _Traits::to_int_type(*this->gptr());
    this->gbump(1);
    return __c;
  }
  else
    return _Traits::eof();
}

template <class _CharT, class _Traits, class _Alloc>
typename basic_stringbuf<_CharT, _Traits, _Alloc>::int_type
basic_stringbuf<_CharT, _Traits, _Alloc>::pbackfail(int_type __c)
{
  if (this->gptr() != this->eback()) {
    if (!_Traits::eq_int_type(__c, _Traits::eof())) {
      if (_Traits::eq(_Traits::to_char_type(__c), this->gptr()[-1])) {
        this->gbump(-1);
        return __c;
      }
      else if (_M_mode & ios_base::out) {
        this->gbump(-1);
        *this->gptr() = __c;
        return __c;
      }
      else
        return _Traits::eof();
    }
    else {
      this->gbump(-1);
      return _Traits::not_eof(__c);
    }
  }
  else
    return _Traits::eof();
}

template <class _CharT, class _Traits, class _Alloc>
typename basic_stringbuf<_CharT, _Traits, _Alloc>::int_type
basic_stringbuf<_CharT, _Traits, _Alloc>::overflow(int_type __c)
{
  if (_M_mode & ios_base::out) {
    if (!_Traits::eq_int_type(__c, _Traits::eof())) {
      if (!(_M_mode & ios_base::in)) {
        // It's a write-only streambuf, so we can use special append buffer.
        if (this->pptr() == this->epptr())
          this->_M_append_buffer();
      
        if (this->pptr() != this->epptr()) {
          *this->pptr() = _Traits::to_char_type(__c);
          this->pbump(1);
          return __c;
        }
        else
          return _Traits::eof();
      }

      else {
        // We're not using a special append buffer, just the string itself.
        if (this->pptr() == this->epptr()) {
          ptrdiff_t __offset = this->gptr() - this->eback();
          _M_str.push_back(_Traits::to_char_type(__c));
          this->setg(_M_str.begin(), _M_str.begin() + __offset, _M_str.end());
          this->setp(_M_str.begin(), _M_str.end());
          this->pbump(_M_str.size());
          return __c;
        }
        else {
          *this->pptr() = _Traits::to_char_type(__c);
          this->pbump(1);
          return __c;
        }
      }
    }
    else                        // __c is EOF, so we don't have to do anything
      return _Traits::not_eof(__c);
  }
  else                          // Overflow always fails if it's read-only.
    return _Traits::eof();
}

template <class _CharT, class _Traits, class _Alloc>
streamsize 
basic_stringbuf<_CharT, _Traits, _Alloc>::xsputn(const char_type* __s,
                                                 streamsize __n)
{
  streamsize __nwritten = 0;

  if ((_M_mode & ios_base::out) && __n > 0) {
    // If the put pointer is somewhere in the middle of the string,
    // then overwrite instead of append.
    if (this->pbase() == _M_str.begin()) {
      ptrdiff_t __avail = _M_str.end() - this->pptr();
      if (__avail > __n) {
        _Traits::copy(this->pptr(), __s, __n);
        this->pbump(__n);
        return __n;
      }
      else {
        _Traits::copy(this->pptr(), __s, __avail);
        __nwritten += __avail;
        __n -= __avail;
        __s += __avail;
        this->setp(_M_Buf, _M_Buf + static_cast<int>(_S_BufSiz));
      }
    }

    // At this point we know we're appending.
    if (_M_mode & ios_base::in) {
      ptrdiff_t __get_offset = this->gptr() - this->eback();
      _M_str.append(__s, __s + __n);
      this->setg(_M_str.begin(), _M_str.begin() + __get_offset, _M_str.end());
      this->setp(_M_str.begin(), _M_str.end());
      this->pbump(_M_str.size());
    }
    else {
      _M_append_buffer();
      _M_str.append(__s, __s + __n);
    }

    __nwritten += __n;
  }

  return __nwritten;
}

template <class _CharT, class _Traits, class _Alloc>
streamsize 
basic_stringbuf<_CharT, _Traits, _Alloc>::_M_xsputnc(char_type __c,
                                                     streamsize __n)
{
  streamsize __nwritten = 0;

  if ((_M_mode & ios_base::out) && __n > 0) {
    // If the put pointer is somewhere in the middle of the string,
    // then overwrite instead of append.
    if (this->pbase() == _M_str.begin()) {
      ptrdiff_t __avail = _M_str.end() - this->pptr();
      if (__avail > __n) {
        _Traits::assign(this->pptr(), __n, __c);
        this->pbump(__n);
        return __n;
      }
      else {
        _Traits::assign(this->pptr(), __avail, __c);
        __nwritten += __avail;
        __n -= __avail;
        this->setp(_M_Buf, _M_Buf + static_cast<int>(_S_BufSiz));
      }
    }

    // At this point we know we're appending.
    if (this->_M_mode & ios_base::in) {
      ptrdiff_t __get_offset = this->gptr() - this->eback();
      _M_str.append(__n, __c);
      this->setg(_M_str.begin(), _M_str.begin() + __get_offset, _M_str.end());
      this->setp(_M_str.begin(), _M_str.end());
      this->pbump(_M_str.size());
    }
    else {
      _M_append_buffer();
      _M_str.append(__n, __c);      
    }

    __nwritten += __n;
  }

  return __nwritten;
}

// According to the C++ standard the effects of setbuf are implementation
// defined, except that setbuf(0, 0) has no effect.  In this implementation,
// setbuf(<anything>, n), for n > 0, calls reserve(n) on the underlying
// string.
template <class _CharT, class _Traits, class _Alloc>
basic_streambuf<_CharT, _Traits>*
basic_stringbuf<_CharT, _Traits, _Alloc>::setbuf(_CharT*, streamsize __n)
{
  if (__n > 0) {
    bool __do_get_area = false;
    bool __do_put_area = false;
    ptrdiff_t __offg = 0;
    ptrdiff_t __offp = 0;

    if (this->pbase() == _M_str.begin()) {
      __do_put_area = true;
      __offp = this->pptr() - this->pbase();
    }

    if (this->eback() == _M_str.begin()) {
      __do_get_area = true;
      __offg = this->gptr() - this->eback();
    }

    if ((_M_mode & ios_base::out) && !(_M_mode & ios_base::in))
      _M_append_buffer();

    _M_str.reserve(__n);

    if (__do_get_area) {
      this->setg(_M_str.begin(), _M_str.begin() + __offg, _M_str.end());
    }

    if (__do_put_area) {
      this->setp(_M_str.begin(), _M_str.end());
      this->pbump(__offp);
    }
  }

  return this;
}

template <class _CharT, class _Traits, class _Alloc>
typename basic_stringbuf<_CharT, _Traits, _Alloc>::pos_type
basic_stringbuf<_CharT, _Traits, _Alloc>
  ::seekoff(off_type __off, ios_base::seekdir __dir,
            ios_base::openmode __mode)
{
  bool __in  = false;
  bool __out = false;
  
  const ios_base::fmtflags __inout = ios_base::in | ios_base::out;

  if ((__mode & __inout) == __inout) {
    if (__dir == ios_base::beg || __dir == ios_base::end)
      __in = __out = true;
  }
  else if (__mode & ios_base::in)
    __in = true;
  else if (__mode & ios_base::out)
    __out = true;

  if (!__in && !__out)
    return pos_type(off_type(-1));
  else if ((__in  && (!(_M_mode & ios_base::in) || this->gptr() == 0)) ||
           (__out && (!(_M_mode & ios_base::out) || this->pptr() == 0)))
    return pos_type(off_type(-1));

  if ((_M_mode & ios_base::out) && !(_M_mode & ios_base::in))
    _M_append_buffer();

  streamoff __newoff;
  switch(__dir) {
  case ios_base::beg:
    __newoff = 0;
    break;
  case ios_base::end:
    __newoff = _M_str.size();
    break;
  case ios_base::cur:
    __newoff = __in ? this->gptr() - this->eback() 
                    : this->pptr() - this->pbase();
    break;
  default:
    return pos_type(off_type(-1));
  }

  __off += __newoff;

  if (__in) {
    ptrdiff_t __n = this->egptr() - this->eback();

    if (__off < 0 || __off > __n)
      return pos_type(off_type(-1));
    else
      this->setg(this->eback(), this->eback() + __off, this->eback() + __n);
  }

  if (__out) {
    ptrdiff_t __n = this->epptr() - this->pbase();

    if (__off < 0 || __off > __n)
      return pos_type(off_type(-1));
    else {
      this->setp(this->pbase(), this->pbase() + __n);
      this->pbump(__off);
    }
  }

  return pos_type(__off);
}

template <class _CharT, class _Traits, class _Alloc>
typename basic_stringbuf<_CharT, _Traits, _Alloc>::pos_type
basic_stringbuf<_CharT, _Traits, _Alloc>
  ::seekpos(pos_type __pos, ios_base::openmode __mode)
{
  bool __in  = (__mode & ios_base::in) != 0;
  bool __out = (__mode & ios_base::out) != 0;

  if ((__in  && (!(_M_mode & ios_base::in) || this->gptr() == 0)) ||
      (__out && (!(_M_mode & ios_base::out) || this->pptr() == 0)))
    return pos_type(off_type(-1));

  const off_type __n = __pos - pos_type(off_type(0));
  if ((_M_mode & ios_base::out) && !(_M_mode & ios_base::in))
    _M_append_buffer();

  if (__in) {
    if (__n < 0 || __n > this->egptr() - this->eback())
      return pos_type(off_type(-1));
    this->setg(this->eback(), this->eback() + __n, this->egptr());
  }

  if (__out) {
    if (__n < 0 || __n > off_type(_M_str.size()))
      return pos_type(off_type(-1));
    this->setp(_M_str.begin(), _M_str.end());
    this->pbump(__n);
  }

  return __pos;
}

// This is declared as a const member function because it is 
// called by basic_stringbuf<>::str().  Precondition: this is a
// write-only stringbuf.  We can't use an output buffer for read-
// write stringbufs.  Postcondition: pptr is reset to the beginning
// of the buffer.
template <class _CharT, class _Traits, class _Alloc>
void basic_stringbuf<_CharT, _Traits, _Alloc>::_M_append_buffer() const

{
  // Do we have a buffer to append?
  if (this->pbase() == this->_M_Buf && this->pptr() != this->_M_Buf) {
    _M_str.append(this->pbase(), this->pptr());
    basic_stringbuf* __this = const_cast<basic_stringbuf*>(this);
    __this->setp(const_cast<_CharT*>(_M_Buf),
                 const_cast<_CharT*>(_M_Buf + static_cast<int>(_S_BufSiz)));
  }

  // Have we run off the end of the string?
  else if (this->pptr() == this->epptr()) {
    basic_stringbuf* __this = const_cast<basic_stringbuf*>(this);
    __this->setp(const_cast<_CharT*>(_M_Buf),
                 const_cast<_CharT*>(_M_Buf + static_cast<int>(_S_BufSiz)));
  }
}

//----------------------------------------------------------------------
// Class basic_istringstream, an input stream that uses a stringbuf.

template <class _CharT, class _Traits, class _Alloc>
class basic_istringstream : public basic_istream<_CharT, _Traits>
{
public:                         // Typedefs
  typedef typename basic_ios<_CharT, _Traits>::char_type   char_type;
  typedef typename basic_ios<_CharT, _Traits>::int_type    int_type;
  typedef typename basic_ios<_CharT, _Traits>::pos_type    pos_type;
  typedef typename basic_ios<_CharT, _Traits>::off_type    off_type;
  typedef typename basic_ios<_CharT, _Traits>::traits_type traits_type;

  typedef basic_ios<_CharT, _Traits>                _Basic_ios;
  typedef basic_istream<_CharT, _Traits>            _Base;
  typedef basic_string<_CharT, _Traits, _Alloc>     _String;

public:                         // Constructors, destructor.
  basic_istringstream(ios_base::openmode __mode = ios_base::in);
  basic_istringstream(const _String& __str,
                      ios_base::openmode __mode = ios_base::in);
  ~basic_istringstream();

public:                         // Member functions.
  basic_stringbuf<_CharT, _Traits, _Alloc>* rdbuf() const
    { return const_cast<basic_stringbuf<_CharT, _Traits, _Alloc>*>(&_M_buf); }

  _String str() const { return _M_buf.str(); }
  void str(const _String& __s) { _M_buf.str(__s); }

private:
  basic_stringbuf<_CharT, _Traits, _Alloc> _M_buf;
};

template <class _CharT, class _Traits, class _Alloc>
basic_istringstream<_CharT, _Traits, _Alloc>
  ::basic_istringstream(ios_base::openmode __mode)
    : _Basic_ios(), _Base(0),
      _M_buf(__mode | ios_base::in)
{
  _Basic_ios::init(&_M_buf);
}

template <class _CharT, class _Traits, class _Alloc>
basic_istringstream<_CharT, _Traits, _Alloc>
  ::basic_istringstream(const _String& __str, ios_base::openmode __mode)
    : _Basic_ios(), _Base(0),
      _M_buf(__str, __mode | ios_base::in)
{
  _Basic_ios::init(&_M_buf);
}

template <class _CharT, class _Traits, class _Alloc>
basic_istringstream<_CharT, _Traits, _Alloc>::~basic_istringstream()
{}


//----------------------------------------------------------------------
// Class basic_ostringstream, an output stream that uses a stringbuf.

template <class _CharT, class _Traits, class _Alloc>
class basic_ostringstream : public basic_ostream<_CharT, _Traits>
{
public:                         // Typedefs
#ifdef __STL_NO_USING_CLAUSE_IN_CLASS
  typedef typename basic_ios<_CharT, _Traits>::char_type char_type;
  typedef typename basic_ios<_CharT, _Traits>::int_type int_type;
  typedef typename basic_ios<_CharT, _Traits>::pos_type pos_type;
  typedef typename basic_ios<_CharT, _Traits>::off_type off_type;
  typedef typename basic_ios<_CharT, _Traits>::traits_type traits_type;
#else
  using basic_ios<_CharT, _Traits>::char_type;
  using basic_ios<_CharT, _Traits>::int_type;
  using basic_ios<_CharT, _Traits>::pos_type;
  using basic_ios<_CharT, _Traits>::off_type;
  using basic_ios<_CharT, _Traits>::traits_type;
#endif

  typedef basic_ios<_CharT, _Traits>                _Basic_ios;
  typedef basic_ostream<_CharT, _Traits>            _Base;
  typedef basic_string<_CharT, _Traits, _Alloc>     _String;

public:                         // Constructors, destructor.
  basic_ostringstream(ios_base::openmode __mode = ios_base::out);
  basic_ostringstream(const _String& __str,
                      ios_base::openmode __mode = ios_base::out);
  ~basic_ostringstream();

public:                         // Member functions.
  basic_stringbuf<_CharT, _Traits, _Alloc>* rdbuf() const
    { return const_cast<basic_stringbuf<_CharT, _Traits, _Alloc>*>(&_M_buf); }

  _String str() const { return _M_buf.str(); }
  void str(const _String& __s) { _M_buf.str(__s); }

private:
  basic_stringbuf<_CharT, _Traits, _Alloc> _M_buf;
};

template <class _CharT, class _Traits, class _Alloc>
basic_ostringstream<_CharT, _Traits, _Alloc>
  ::basic_ostringstream(ios_base::openmode __mode)
    : _Basic_ios(), _Base(0),
      _M_buf(__mode | ios_base::out)
{
  _Basic_ios::init(&_M_buf);
}
  
template <class _CharT, class _Traits, class _Alloc>
basic_ostringstream<_CharT, _Traits, _Alloc>
  ::basic_ostringstream(const _String& __str, ios_base::openmode __mode)
    : _Basic_ios(), _Base(0),
      _M_buf(__str, __mode | ios_base::out)
{
  _Basic_ios::init(&_M_buf);
}

template <class _CharT, class _Traits, class _Alloc>
basic_ostringstream<_CharT, _Traits, _Alloc>::~basic_ostringstream()
{}


//----------------------------------------------------------------------
// Class basic_stringstream, a bidirectional stream that uses a stringbuf.

template <class _CharT, class _Traits, class _Alloc>
class basic_stringstream : public basic_iostream<_CharT, _Traits>
{
public:                         // Typedefs
#ifdef __STL_NO_USING_CLAUSE_IN_CLASS
  typedef typename basic_ios<_CharT, _Traits>::char_type char_type;
  typedef typename basic_ios<_CharT, _Traits>::int_type int_type;
  typedef typename basic_ios<_CharT, _Traits>::pos_type pos_type;
  typedef typename basic_ios<_CharT, _Traits>::off_type off_type;
  typedef typename basic_ios<_CharT, _Traits>::traits_type traits_type;
#else
  using basic_ios<_CharT, _Traits>::char_type;
  using basic_ios<_CharT, _Traits>::int_type;
  using basic_ios<_CharT, _Traits>::pos_type;
  using basic_ios<_CharT, _Traits>::off_type;
  using basic_ios<_CharT, _Traits>::traits_type;
#endif

  typedef basic_ios<_CharT, _Traits>                 _Basic_ios;
  typedef basic_iostream<_CharT, _Traits>            _Base;
  typedef basic_string<_CharT, _Traits, _Alloc>      _String;

public:                         // Constructors, destructor.
  basic_stringstream(ios_base::openmode = ios_base::in | ios_base::out);
  basic_stringstream(const _String& __str,
                     ios_base::openmode = ios_base::in | ios_base::out);
  ~basic_stringstream();

public:                         // Member functions.
  basic_stringbuf<_CharT, _Traits, _Alloc>* rdbuf() const
    { return const_cast<basic_stringbuf<_CharT, _Traits, _Alloc>*>(&_M_buf); }

  _String str() const { return _M_buf.str(); }
  void str(const _String& __s) { _M_buf.str(__s); }

private:
  basic_stringbuf<_CharT, _Traits, _Alloc> _M_buf;
};

template <class _CharT, class _Traits, class _Alloc>
basic_stringstream<_CharT, _Traits, _Alloc>
  ::basic_stringstream(ios_base::openmode __mode)
    : _Basic_ios(), _Base(0), _M_buf(__mode)
{
  _Basic_ios::init(&_M_buf);
}

template <class _CharT, class _Traits, class _Alloc>
basic_stringstream<_CharT, _Traits, _Alloc>
  ::basic_stringstream(const _String& __str, ios_base::openmode __mode)
    : _Basic_ios(), _Base(0), _M_buf(__str, __mode)
{
  _Basic_ios::init(&_M_buf);
}

template <class _CharT, class _Traits, class _Alloc>
basic_stringstream<_CharT, _Traits, _Alloc>::~basic_stringstream()
{}


__STL_END_NAMESPACE

#endif /* __SGI_STL_SSTREAM */

// Local Variables:
// mode:C++
// End:
// End:
// End:
