Mirror of :pserver:cvs@cvs.fefe.de:/cvs libowfat https://www.fefe.de/libowfat/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

40 lines
1.1 KiB

  1. #include "scan.h"
  2. size_t scan_varint(const char* in,size_t len, unsigned long long* n) {
  3. size_t i;
  4. unsigned long long l;
  5. if (len==0) return 0;
  6. for (l=0, i=0; i<len; ++i) {
  7. if (i*7+7>sizeof(l)*8) // value too large to fit in destination integer!
  8. return 0;
  9. l+=(unsigned long long)(in[i]&0x7f) << (i*7);
  10. if (!(in[i]&0x80)) {
  11. if (in[i]==0) return 0; // libowfat extension: reject non-minimal encoding
  12. *n=l;
  13. return i+1;
  14. }
  15. }
  16. return 0;
  17. }
  18. #ifdef __ELF__
  19. size_t scan_pb_type0_int(const char* dest,size_t len,unsigned long long* l) __attribute__((alias("scan_varint")));
  20. #else
  21. size_t scan_pb_type0_int(const char* dest,size_t len,unsigned long long* l) {
  22. return scan_varint(dest,len,l);
  23. }
  24. #endif
  25. #ifdef UNITTEST
  26. #include <assert.h>
  27. int main() {
  28. unsigned long long n;
  29. assert(scan_varint("\x05",1,&n)==1 && n==5);
  30. assert(scan_varint("\x80\x00",2,&n)==0); // non-minimal encoding
  31. assert(scan_varint("\x80\x80",2,&n)==0); // truncated (last byte in sequence has high bit 0)
  32. assert(scan_varint("\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01",10,&n)==0); // value too large
  33. return 0;
  34. }
  35. #endif