diff --git a/include/bx/endian.h b/include/bx/endian.h index c9f0294..4227807 100644 --- a/include/bx/endian.h +++ b/include/bx/endian.h @@ -46,8 +46,10 @@ namespace bx return (int64_t)endianSwap( (uint64_t)_in); } + /// Input argument is encoded as little endian, convert it if neccessary + /// depending on host CPU endianess. template - inline Ty littleEndian(const Ty _in) + inline Ty toLittleEndian(const Ty _in) { #if BX_CPU_ENDIAN_BIG return endianSwap(_in); @@ -56,8 +58,10 @@ namespace bx #endif // BX_CPU_ENDIAN_BIG } + /// Input argument is encoded as big endian, convert it if neccessary + /// depending on host CPU endianess. template - inline Ty bigEndian(const Ty _in) + inline Ty toBigEndian(const Ty _in) { #if BX_CPU_ENDIAN_LITTLE return endianSwap(_in); @@ -66,6 +70,18 @@ namespace bx #endif // BX_CPU_ENDIAN_LITTLE } + /// If _littleEndian is true, converts input argument to from little endian + /// to host CPU endiness. + template + inline Ty toHostEndian(const Ty _in, bool _fromLittleEndian) + { +#if BX_CPU_ENDIAN_LITTLE + return _fromLittleEndian ? _in : endianSwap(_in); +#else + return _fromLittleEndian ? endianSwap(_in) : _in; +#endif // BX_CPU_ENDIAN_LITTLE + } + } // namespace bx #endif // __BX_ENDIAN_H__ diff --git a/include/bx/readerwriter.h b/include/bx/readerwriter.h index 416006b..128c4c7 100644 --- a/include/bx/readerwriter.h +++ b/include/bx/readerwriter.h @@ -62,28 +62,61 @@ namespace bx { } + /// Read data. inline int32_t read(ReaderI* _reader, void* _data, int32_t _size) { return _reader->read(_data, _size); } + /// Write value. template inline int32_t read(ReaderI* _reader, Ty& _value) { return _reader->read(&_value, sizeof(Ty) ); } + /// Read value and converts it to host endianess. _fromLittleEndian specifies + /// underlying stream endianess. + template + inline int32_t readHE(ReaderI* _reader, Ty& _value, bool _fromLittleEndian) + { + Ty value; + int32_t result = _reader->read(&value, sizeof(Ty) ); + _value = toHostEndian(value, _fromLittleEndian); + return result; + } + + /// Write data. inline int32_t write(WriterI* _writer, const void* _data, int32_t _size) { return _writer->write(_data, _size); } + /// Write value. template inline int32_t write(WriterI* _writer, const Ty& _value) { return _writer->write(&_value, sizeof(Ty) ); } + /// Write value as little endian. + template + inline int32_t writeLE(WriterI* _writer, const Ty& _value) + { + Ty value = toLittleEndian(_value); + int32_t result = _writer->write(&value, sizeof(Ty) ); + return result; + } + + /// Write value as big endian. + template + inline int32_t writeBE(WriterI* _writer, const Ty& _value) + { + Ty value = toBigEndian(_value); + int32_t result = _writer->write(&value, sizeof(Ty) ); + return result; + } + inline int64_t skip(SeekerI* _seeker, int64_t _offset) { return _seeker->seek(_offset, Whence::Current);