Added endian aware read/writing functions.

This commit is contained in:
bkaradzic
2013-09-02 16:23:21 -07:00
parent c7732f64fb
commit 10be2a8270
2 changed files with 51 additions and 2 deletions

View File

@@ -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 <typename Ty>
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 <typename Ty>
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 <typename Ty>
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__

View File

@@ -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<typename Ty>
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<typename Ty>
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<typename Ty>
inline int32_t write(WriterI* _writer, const Ty& _value)
{
return _writer->write(&_value, sizeof(Ty) );
}
/// Write value as little endian.
template<typename Ty>
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<typename Ty>
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);