#include "xdr.hpp" namespace retronfs { void XdrWriter::pad(unsigned len) { unsigned p = (4 - (len & 3)) & 3; while (p--) out_.push_back(0); } void XdrWriter::u32(uint32_t v) { out_.push_back((byte)((v >> 24) & 0xff)); out_.push_back((byte)((v >> 16) & 0xff)); out_.push_back((byte)((v >> 8) & 0xff)); out_.push_back((byte)(v & 0xff)); } void XdrWriter::u64(uint64_t v) { u32((uint32_t)(v >> 32)); u32((uint32_t)(v & 0xffffffffU)); } void XdrWriter::opaque(const Bytes& data) { u32((uint32_t)data.size()); fixed_opaque(data.empty() ? 0 : &data[0], (unsigned)data.size()); } void XdrWriter::fixed_opaque(const byte* data, unsigned len) { for (unsigned i = 0; i < len; ++i) out_.push_back(data[i]); pad(len); } void XdrWriter::str(const std::string& value) { u32((uint32_t)value.size()); for (unsigned i = 0; i < value.size(); ++i) out_.push_back((byte)value[i]); pad((unsigned)value.size()); } const Bytes& XdrWriter::data() const { return out_; } XdrReader::XdrReader(const Bytes& data) : in_(data), pos_(0) {} void XdrReader::require(unsigned n) { if (pos_ + n > in_.size()) { throw Error("truncated XDR stream"); } } void XdrReader::skip_pad(unsigned len) { unsigned p = (4 - (len & 3)) & 3; require(p); pos_ += p; } uint32_t XdrReader::u32() { require(4); uint32_t v = ((uint32_t)in_[pos_] << 24) | ((uint32_t)in_[pos_ + 1] << 16) | ((uint32_t)in_[pos_ + 2] << 8) | ((uint32_t)in_[pos_ + 3]); pos_ += 4; return v; } uint64_t XdrReader::u64() { uint64_t hi = u32(); uint64_t lo = u32(); return (hi << 32) | lo; } Bytes XdrReader::opaque() { unsigned len = u32(); return fixed_opaque(len); } Bytes XdrReader::fixed_opaque(unsigned len) { require(len); Bytes out; out.insert(out.end(), in_.begin() + pos_, in_.begin() + pos_ + len); pos_ += len; skip_pad(len); return out; } std::string XdrReader::str() { Bytes data = opaque(); return std::string(data.begin(), data.end()); } bool XdrReader::eof() const { return pos_ >= in_.size(); } unsigned XdrReader::remaining() const { return (unsigned)(in_.size() - pos_); } }