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.
 
 
 
 

43 lines
1.1 KiB

  1. #include "scan.h"
  2. /* parse a netstring, input buffer is in (len bytes).
  3. * if parsing is successful:
  4. * *dest points to string and *slen is size of string
  5. * return number of bytes parsed
  6. * else
  7. * return 0
  8. * Note: *dest will point inside the input buffer!
  9. */
  10. size_t scan_netstring(const char* in,size_t len,char** dest,size_t* slen) {
  11. // [len]":"[string]","
  12. // 3:foo,3:bar,4:fini,
  13. unsigned long l;
  14. size_t n=scan_ulongn(in,len,&l);
  15. if (!n || /* did not start with a number */
  16. n+2+l<l || /* overflow */
  17. n+2+l>len || /* longer than we have input data */
  18. in[n]!=':' || /* syntax error */
  19. in[n+l+1]!=',')
  20. return 0;
  21. *dest=(char*)in+n+1;
  22. *slen=l;
  23. return n+2+l;
  24. }
  25. #ifdef UNITTEST
  26. #include <assert.h>
  27. #include "scan_ulongn.c"
  28. int main() {
  29. char buf[]="12:hello world!,";
  30. char* s;
  31. size_t l;
  32. const char* orig;
  33. assert(scan_netstring(buf,16,&s,&l)==16 && s==buf+3 && l==12);
  34. orig="3:foo,"; assert(scan_netstring(orig,6,&s,&l)==6 && s==orig+2 && l==3);
  35. orig="4294967295:foo,"; assert(scan_netstring(orig,15,&s,&l)==0);
  36. orig="18446744073709551615:foo,"; assert(scan_netstring(orig,25,&s,&l)==0);
  37. }
  38. #endif