/* 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 #include #include #include #include #include namespace starshatter { namespace foundation { // If extension is needed, use type_traits or update to C++20 and use concepts inline bool ok(const char* data) { return data != nullptr; } inline bool ok(const std::unique_ptr& data) { return static_cast(data); } inline const char* at(const char* data) { return data; } inline const char* at(const std::unique_ptr& data) { return data.get(); } template BufferReader::BufferReader() { } template BufferReader::BufferReader(Source src) : buffer {std::move(src)}, size {std::strlen(at(buffer)) + 1} { } template BufferReader::BufferReader(Source src, Count bytes) : buffer {std::move(src)}, size {bytes} { } template bool BufferReader::valid() const { return ok(buffer); } template Count BufferReader::available() const { return size - position; } template Count BufferReader::seek(Count pos) { position = pos; if (position > size) position = size; return position; } template Count BufferReader::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; } position = static_cast(std::clamp(offset, 0, size)); return position; } template Count BufferReader::read(char* dest) { return read(dest, available()); } template Count BufferReader::read(char* dest, Count bytes) { bytes = peek(dest, bytes); position += bytes; return bytes; } template Count BufferReader::peek(char* dest) const { return peek(dest, available()); } template Count BufferReader::peek(char* dest, Count bytes) const { bytes = std::min(bytes, available()); std::copy(at(buffer) + position, at(buffer) + position + bytes, dest); return bytes; } template Text BufferReader::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