Created
March 8, 2024 10:49
-
-
Save adujardin/aab56749919055dfe8512710abae58b8 to your computer and use it in GitHub Desktop.
fstream like interface for vector of uint8_t
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <vector> | |
#include <cstdint> | |
class BinaryVectorStream { | |
private: | |
std::vector<uint8_t>& data; | |
size_t position; | |
public: | |
BinaryVectorStream(std::vector<uint8_t>& vec) : data(vec), position(0) { | |
} | |
bool eof() const { | |
return position >= data.size(); | |
} | |
void write(const void* ptr, size_t size) { | |
const uint8_t* bytes = static_cast<const uint8_t*> (ptr); | |
data.insert(data.end(), bytes, bytes + size); | |
} | |
void read(void* ptr, size_t size) { | |
if (position + size > data.size()) { | |
throw std::runtime_error("End of file reached"); | |
} | |
std::copy(data.begin() + position, data.begin() + position + size, static_cast<uint8_t*> (ptr)); | |
position += size; | |
} | |
void seekg(size_t pos) { | |
if (pos > data.size()) { | |
throw std::runtime_error("Invalid seek position"); | |
} | |
position = pos; | |
} | |
size_t tellg() const { | |
return position; | |
} | |
void close() { | |
data.clear(); | |
position = 0; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment