jak-project/common/util/BinaryReader.h

44 lines
966 B
C
Raw Normal View History

#pragma once
/*!
* @file BinaryReader.h
* Read raw data like a stream.
*/
2020-08-22 23:30:17 -04:00
#include <cstdint>
#include <cstring>
#include <span>
2020-08-22 23:30:17 -04:00
#include <vector>
#include "common/common_types.h"
#include "common/util/Assert.h"
2020-08-22 23:30:17 -04:00
class BinaryReader {
2020-08-26 01:21:33 -04:00
public:
explicit BinaryReader(std::span<const uint8_t> _span) : m_span(_span) {}
2020-08-22 23:30:17 -04:00
2020-08-26 01:21:33 -04:00
template <typename T>
2020-08-22 23:30:17 -04:00
T read() {
ASSERT(m_seek + sizeof(T) <= m_span.size());
T obj;
memcpy(&obj, m_span.data() + m_seek, sizeof(T));
m_seek += sizeof(T);
2020-08-22 23:30:17 -04:00
return obj;
}
void ffwd(int amount) {
m_seek += amount;
ASSERT(m_seek <= m_span.size());
2020-08-22 23:30:17 -04:00
}
uint32_t bytes_left() const { return m_span.size() - m_seek; }
const uint8_t* here() { return m_span.data() + m_seek; }
BinaryReader at(u32 pos) { return BinaryReader(m_span.subspan(pos)); }
uint32_t get_seek() const { return m_seek; }
void set_seek(u32 seek) { m_seek = seek; }
2020-08-22 23:30:17 -04:00
2020-08-26 01:21:33 -04:00
private:
std::span<const u8> m_span;
uint32_t m_seek = 0;
2020-08-22 23:30:17 -04:00
};