/// ReadStream.h
/**
*/

#ifndef READSTREAM_H_
#define READSTREAM_H_

#include <string>
#include <vector>
#include <istream>
#include <sstream>

// Functions for reading a specific length of bytes,
// as a specific type, returned as a vector of strings

namespace jcs {

// todo: add byte swapping
template<class T> 
struct ReadStream
{
  static std::vector<std::string>
  doit(std::istream& in, std::streamsize length) {
    T value;
    std::vector<std::string> v;
    std::streamsize bytes_read = 0;
    while (bytes_read < length) {
      if ((length - bytes_read) < sizeof(value)) {
        in.read(reinterpret_cast<char*> (&value), (length - bytes_read));
      }
      else {
        in.read(reinterpret_cast<char*> (&value), sizeof(value));
      }
      std::stringstream ss;
      ss << value;
      std::string new_value;
      ss >> new_value;
      v.push_back(new_value);
      bytes_read += in.gcount();
    }
    return v;
  }
};

template<> 
struct ReadStream<std::string>
{
  static std::vector<std::string>
  doit(std::istream& in, std::streamsize length) {
    std::vector<std::string> v;
    v.push_back(std::string());
    v.front().reserve(length);
    for (int i = 0; in.good() && i < length; ++i )
      v.front().push_back(in.get());
    return v;
  }
};

}

#endif
