serialize.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //
  2. // Created by Dusan Klinec on 02/05/2018.
  3. //
  4. #include "serialize.h"
  5. int xmr_size_varint(uint64_t num) {
  6. int ctr = 1;
  7. while (num >= 0x80) {
  8. ++ctr;
  9. num >>= 7;
  10. }
  11. return ctr;
  12. }
  13. int xmr_write_varint(uint8_t *buff, size_t buff_size, uint64_t num) {
  14. unsigned ctr = 0;
  15. while (num >= 0x80 && ctr < buff_size) {
  16. *buff = (uint8_t)(((num)&0x7f) | 0x80);
  17. ++buff;
  18. ++ctr;
  19. num >>= 7;
  20. }
  21. /* writes the last one to dest */
  22. if (ctr < buff_size) {
  23. *buff = (uint8_t)num;
  24. ++ctr;
  25. }
  26. return ctr <= buff_size ? (int)ctr : -1;
  27. }
  28. int xmr_read_varint(uint8_t *buff, size_t buff_size, uint64_t *val) {
  29. unsigned read = 0;
  30. int finished_ok = 0;
  31. *val = 0;
  32. for (int shift = 0; read < buff_size; shift += 7, ++read) {
  33. uint8_t byte = buff[read];
  34. if ((byte == 0 && shift != 0) || (shift >= 63 && byte > 1)) {
  35. return -1;
  36. }
  37. *val |= (uint64_t)(byte & 0x7f) << shift;
  38. /* If there is no next */
  39. if ((byte & 0x80) == 0) {
  40. finished_ok = 1;
  41. break;
  42. }
  43. }
  44. return finished_ok ? (int)read + 1 : -2;
  45. }