1
0

ByteWriter.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "ByteWriter.h"
  2. #include <string.h>
  3. /* generic endian-agnostic implementation. this code assumes that unaligned accesses are illegal */
  4. void bytewriter_init(bytewriter_t byte_writer, void *data, size_t byte_length)
  5. {
  6. byte_writer->data = data;
  7. byte_writer->byte_length = byte_length;
  8. byte_writer->data_ptr = (uint8_t *)data;
  9. }
  10. /* n byte functions */
  11. void bytewriter_write_n(bytewriter_t byte_writer, const void *source, size_t bytes)
  12. {
  13. memcpy(byte_writer->data_ptr, source, bytes);
  14. byte_writer->data_ptr += bytes;
  15. }
  16. void bytewriter_write_u8(bytewriter_t byte_writer, uint8_t value)
  17. {
  18. *byte_writer->data_ptr++ = value;
  19. byte_writer->byte_length--;
  20. }
  21. void bytewriter_write_u16_le(bytewriter_t byte_writer, uint16_t value)
  22. {
  23. *byte_writer->data_ptr++ = value & 0xFF;
  24. value >>= 8;
  25. *byte_writer->data_ptr++ = value & 0xFF;
  26. byte_writer->byte_length -= 2;
  27. }
  28. void bytewriter_write_u16_be(bytewriter_t byte_writer, uint16_t value)
  29. {
  30. *byte_writer->data_ptr++ = (value >> 8) & 0xFF;
  31. *byte_writer->data_ptr++ = value & 0xFF;
  32. byte_writer->byte_length -= 2;
  33. }
  34. void bytewriter_write_u32_le(bytewriter_t byte_writer, uint32_t value)
  35. {
  36. *byte_writer->data_ptr++ = value & 0xFF;
  37. value >>= 8;
  38. *byte_writer->data_ptr++ = value & 0xFF;
  39. value >>= 8;
  40. *byte_writer->data_ptr++ = value & 0xFF;
  41. value >>= 8;
  42. *byte_writer->data_ptr++ = value & 0xFF;
  43. byte_writer->byte_length -= 4;
  44. }
  45. void bytewriter_write_u32_be(bytewriter_t byte_writer, uint32_t value)
  46. {
  47. *byte_writer->data_ptr++ = (value >> 24) & 0xFF;
  48. *byte_writer->data_ptr++ = (value >> 16) & 0xFF;
  49. *byte_writer->data_ptr++ = (value >> 8) & 0xFF;
  50. *byte_writer->data_ptr++ = value & 0xFF;
  51. byte_writer->byte_length -= 4;
  52. }
  53. void bytewriter_write_zero_n(bytewriter_t byte_writer, size_t bytes)
  54. {
  55. size_t i;
  56. for (i=0;i<bytes;i++)
  57. {
  58. *byte_writer->data_ptr++ = 0;
  59. }
  60. byte_writer->byte_length -= bytes;
  61. }
  62. void bytewriter_write_uuid_be(bytewriter_t byte_writer, GUID guid_value)
  63. {
  64. bytewriter_write_u32_be(byte_writer, guid_value.Data1);
  65. bytewriter_write_u16_be(byte_writer, guid_value.Data2);
  66. bytewriter_write_u16_be(byte_writer, guid_value.Data3);
  67. bytewriter_write_n(byte_writer, guid_value.Data4, 8);
  68. }