ByteWriter.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #pragma once
  2. #include "foundation/types.h"
  3. /* A simple byte-oriented writer.
  4. use this instead of manually writing data as this deals with memory alignment issues
  5. for you.
  6. memory alignment can be critical and annoying on some architectures (e.g. PowerPC)
  7. it also handles little-endian/big-endian issues
  8. Usually you just make one of these things on the stack, passing in your buffer and length
  9. */
  10. #ifdef __cplusplus
  11. extern "C" {
  12. #endif
  13. typedef struct bytewriter_struct_t
  14. {
  15. size_t byte_length;
  16. uint8_t *data_ptr;
  17. void *data;
  18. } bytewriter_s, *bytewriter_t;
  19. void bytewriter_init(bytewriter_t byte_writer, void *data, size_t byte_length);
  20. static size_t bytewriter_size(bytewriter_t byte_writer) /* returns remaining bytes in stream */
  21. {
  22. return byte_writer->byte_length;
  23. }
  24. static void *bytewriter_pointer(bytewriter_t byte_writer) /* returns a pointer to the current bitstream position */
  25. {
  26. return byte_writer->data_ptr;
  27. }
  28. static void bytewriter_advance(bytewriter_t byte_writer, size_t bytes) /* advances the byte stream */
  29. {
  30. byte_writer->byte_length-=bytes;
  31. byte_writer->data_ptr+=bytes;
  32. }
  33. void bytewriter_write_n(bytewriter_t byte_writer, const void *source, size_t bytes);
  34. void bytewriter_write_zero_n(bytewriter_t byte_writer, size_t bytes);
  35. void bytewriter_write_u8(bytewriter_t byte_writer, uint8_t value);
  36. void bytewriter_write_u16_le(bytewriter_t byte_writer, uint16_t value);
  37. void bytewriter_write_u16_be(bytewriter_t byte_writer, uint16_t value);
  38. void bytewriter_write_u32_le(bytewriter_t byte_writer, uint32_t value);
  39. void bytewriter_write_u32_be(bytewriter_t byte_writer, uint32_t value);
  40. void bytewriter_write_uuid_be(bytewriter_t byte_writer, GUID guid_value);
  41. #ifdef __cplusplus
  42. }
  43. #endif