serialize.c 1.2 KB

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