From 2066e4911948d11cac5a234d2f7773dc5f06ba96 Mon Sep 17 00:00:00 2001 From: Aki Date: Mon, 18 Mar 2024 23:41:20 +0100 Subject: Added filesystem-only starshatter::data DataLoader replacement Step by step. The intent is to find a good spot between current data representations and the standard library and put the intermediate stage there. After it matures a bit, we can move further away. --- FoundationEx/src/reader/file.cpp | 129 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 FoundationEx/src/reader/file.cpp (limited to 'FoundationEx/src/reader/file.cpp') diff --git a/FoundationEx/src/reader/file.cpp b/FoundationEx/src/reader/file.cpp new file mode 100644 index 0000000..f9e9ae2 --- /dev/null +++ b/FoundationEx/src/reader/file.cpp @@ -0,0 +1,129 @@ +/* Starshatter: The Open Source Project + Copyright (c) 2021-2024, Starshatter: The Open Source Project Contributors + Copyright (c) 2011-2012, Starshatter OpenSource Distribution Contributors + Copyright (c) 1997-2006, Destroyer Studios LLC. +*/ + +#include "file.h" + +#include +#include +#include +#include +#include +#include + +#include + + +namespace starshatter +{ +namespace foundation +{ + + +FileReader::FileReader(std::fstream src) : + file {std::move(src)} +{ + file.seekg(0); + file.ignore(std::numeric_limits::max()); + size = file.gcount(); + file.clear(); + file.seekg(0); + position = 0; +} + + +bool +FileReader::valid() const +{ + return static_cast(file) && file.is_open(); +} + + +Count +FileReader::available() const +{ + return size - position; +} + + +Count +FileReader::seek(Count pos) +{ + position = pos; + if (position > size) + position = size; + file.seekg(position); + return position; +} + + +Count +FileReader::seek(Offset offset, Direction dir) +{ + switch (dir) { + case Direction::Start: + break; // no-op + case Direction::End: + offset = size + offset; + break; + case Direction::Current: + offset = position + offset; + break; + } + if (offset < 0) + offset = 0; + return seek(static_cast(offset)); +} + + +Count +FileReader::read(char* dest) +{ + return read(dest, available()); +} + + +Count +FileReader::read(char* dest, Count bytes) +{ + bytes = std::min(bytes, available()); + file.read(dest, bytes); + position += bytes; + return bytes; +} + + +Count +FileReader::peek(char* dest) const +{ + return peek(dest, available()); +} + + +Count +FileReader::peek(char* dest, Count bytes) const +{ + bytes = std::min(bytes, available()); + const auto before = file.tellg(); + file.read(dest, bytes); + file.seekg(before); + return bytes; +} + + +Text +FileReader::more() +{ + const auto size = available(); + if (size < 1) + return Text(); + std::vector tmp(size); + read(tmp.data(), size); + return Text(tmp.data(), size); +} + + +} // namespace foundation +} // namespace starshatter -- cgit v1.1