Skip to content

Instantly share code, notes, and snippets.

@ITotalJustice
Created July 13, 2025 20:43
Show Gist options
  • Select an option

  • Save ITotalJustice/e6a3fd4dfc1ccdefb4758274338d68a1 to your computer and use it in GitHub Desktop.

Select an option

Save ITotalJustice/e6a3fd4dfc1ccdefb4758274338d68a1 to your computer and use it in GitHub Desktop.
buffered io
struct BufferedFileData {
u8 data[1024 * 64]; // configure size here.
s64 off;
s64 size;
};
static BufferedFileData buffered;
size_t Source::ReadFile(void *_buffer, size_t read_size) {
auto dst = static_cast<u8*>(_buffer);
size_t amount = 0;
if (buffered.size && this->m_offset >= buffered.off) {
const auto off = this->m_offset - buffered.off;
const auto size = std::min<s64>(read_size, buffered.size - off);
if (size > 0) {
std::memcpy(dst, buffered.data + off, size);
read_size -= size;
m_offset += size;
amount += size;
dst += size;
}
}
if (read_size) {
u64 bytes_read = 0;
// if the dst dst is big enough, read data in place.
if (read_size >= sizeof(buffered.data)) {
if (R_SUCCEEDED(fsFileRead(&this->m_file, this->m_offset, dst, read_size, 0, &bytes_read)) && bytes_read) {
read_size -= bytes_read;
m_offset += bytes_read;
amount += bytes_read;
dst += bytes_read;
// save the last chunk of data to the buffered io.
const auto max_advance = std::min(amount, sizeof(buffered.data));
buffered.off = m_offset - max_advance;
buffered.size = max_advance;
std::memcpy(buffered.data, dst - max_advance, max_advance);
}
} else if (R_SUCCEEDED(fsFileRead(&this->m_file, this->m_offset, buffered.data, sizeof(buffered.data), 0, &bytes_read)) && bytes_read) {
const auto max_advance = std::min(read_size, bytes_read);
std::memcpy(dst, buffered.data, max_advance);
buffered.off = m_offset;
buffered.size = bytes_read;
read_size -= max_advance;
m_offset += max_advance;
amount += max_advance;
dst += max_advance;
}
}
return amount;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment