serialize.c 1.2 KB

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