Skip to content
Snippets Groups Projects
binary_stream.cpp 1.61 KiB
Newer Older
  • Learn to ignore specific revisions
  • theazgra's avatar
    theazgra committed
    #include "binary_stream.h"
    #include <iterator>
    
    BinaryStream::BinaryStream(const std::string &file)
    {
        this->fileStream = std::ifstream(file, std::ios::binary);
        this->fileStream.unsetf(std::ios::skipws);
    
        assert(this->fileStream.is_open());
    
        this->currentPosition = 0;
        this->fileStream.seekg(std::ios::end);
        this->fileSize = fileStream.tellg();
        this->fileStream.seekg(std::ios::beg);
    }
    
    BinaryStream::~BinaryStream()
    {
        this->fileStream.close();
    }
    
    size_t BinaryStream::get_size() const
    {
        return this->fileSize;
    }
    
    void BinaryStream::move_to(const long position)
    {
        this->fileStream.seekg(position);
        this->currentPosition = position;
    }
    
    void BinaryStream::move_to_beginning()
    {
        this->fileStream.seekg(std::ios::beg);
        this->currentPosition = 0;
    }
    
    void BinaryStream::move_to_end()
    {
        this->fileStream.seekg(std::ios::end);
        this->currentPosition = this->fileSize;
    }
    
    bool BinaryStream::can_read()
    {
        return (this->currentPosition < this->fileSize);
    }
    
    std::vector<byte> BinaryStream::consume_bytes(const long byteCount)
    {
        //TODO: Maybe this should be replace with faster reading.
    
        // Check if iterator is set at current stream position, or
        // we have to move iterator manually to match this->currentPosition
        auto readIterator = std::istream_iterator<byte>(fileStream);
    
        std::vector<byte> result;
        result.resize(byteCount);
        for (size_t i = 0; i < byteCount; i++)
        {
            result[i] = *readIterator++;
        }
        this->currentPosition += byteCount;
    
        return result;
    }
    
    std::vector<byte> BinaryStream::consume_bytes_at(const long position, const long byteCount)
    {
    }