#include <iostream>
#include <akaxiso/configuration.h>

#ifdef USE_XERCESC

#include "istream_inputsource.h"
#include <xercesc/util/BinInputStream.hpp>

namespace {
  using namespace xercesc;


#if 0 //def AKAXISO_ISTREAM_HAS_READSOME
  unsigned int readsome(std::istream &istm, XMLByte * toFill, const unsigned int maxToRead) {
    return istm.readsome(reinterpret_cast<char*>(toFill), maxToRead);
  }
#else
  unsigned int readsome(std::istream &istm, XMLByte * toFill, const unsigned int maxToRead) {
    unsigned int index = 0;
    for (;index < maxToRead; ++index) {
      istm.get(*reinterpret_cast<char*>(toFill));
      if (istm.fail())
	break;
      ++toFill;
    }
    return index;
  }
#endif


  class IStreamBinInputStream : public xercesc::BinInputStream {
  public:
    IStreamBinInputStream(std::istream &istm) : istm_(istm), pos_(0) { }
    
    virtual unsigned int curPos () const;
    virtual unsigned int readBytes(XMLByte *const toFill, const unsigned int maxToRead);
  private:
    std::istream &istm_;
    unsigned int pos_;
  };

  unsigned int IStreamBinInputStream::curPos () const {
    return pos_;
  }
  unsigned int IStreamBinInputStream::readBytes(XMLByte *const toFill, 
						const unsigned int maxToRead) {

    unsigned int size = readsome(istm_, toFill, maxToRead);
    pos_ += size;
    return size;
  }

}

using namespace aka2;

IStreamInputSource::IStreamInputSource(std::istream &istm) : istm_(istm){}

xercesc::BinInputStream *IStreamInputSource::makeStream() const {
  return new IStreamBinInputStream(istm_);
}

#endif
