commit 0ed5d6492171c6d53401729b830405be84b42a33 parent 66f7dec877e52d4ccfd035da8ea62964ff5fd1a0 Author: Michael Savage <mikejsavage@gmail.com> Date: Sun Mar 6 21:13:44 +0000 Add stream.h Diffstat:
stream.h | | | 56 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
diff --git a/stream.h b/stream.h @@ -0,0 +1,56 @@ +#ifndef _STREAM_H_ +#define _STREAM_H_ + +#include "endian.h" + +struct Stream { + char * ptr; +}; + +#ifdef IS_LITTLE_ENDIAN +#define DEF_TYPE( type ) \ + inline Stream read_##type( Stream stream, type * v ) { \ + *v = *( type * ) stream.ptr; \ + stream.ptr += sizeof( type ); \ + return stream; \ + } \ + inline Stream write_##type( Stream stream, const type * v ) { \ + *( type * ) stream.ptr = *v; \ + stream.ptr += sizeof( type ); \ + return stream; \ + } +#else +#define DEF_TYPE( type ) \ + inline Stream read_##type( Stream stream, type * v ) { \ + char swapped[ sizeof( type ) ]; \ + for( int i = 0; i < sizeof( type ); i++ ) { \ + swapped[ i ] = stream.ptr[ sizeof( swapped ) - 1 - i ]; \ + } \ + *v = *( type * ) swapped; \ + stream.ptr += sizeof( type ); \ + return stream; \ + } \ + inline Stream write_##type( Stream stream, const type * v ) { \ + char * v_as_string = ( char * ) v; \ + for( int i = 0; i < sizeof( type ); i++ ) { \ + stream.ptr[ i ] = v_as_string[ sizeof( type ) - 1 - i ]; \ + } \ + stream.ptr += sizeof( type ); \ + return stream; \ + } +#endif + +DEF_TYPE( u8 ) +DEF_TYPE( u16 ) +DEF_TYPE( u32 ) +DEF_TYPE( u64 ) +DEF_TYPE( s8 ) +DEF_TYPE( s16 ) +DEF_TYPE( s32 ) +DEF_TYPE( s64 ) +DEF_TYPE( f32 ) +DEF_TYPE( f64 ) + +#undef DEF_TYPE + +#endif // _STREAM_H_