From d95163270e022fe87ece0c151c2987fd62274ba8 Mon Sep 17 00:00:00 2001 From: Dirk Engling Date: Sat, 24 Oct 2026 05:25:05 +0200 Subject: Add a dedicated ranged unsigned int scanner and a bencoded variant --- ot_scan.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ ot_scan.h | 21 +++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 ot_scan.c create mode 100644 ot_scan.h diff --git a/ot_scan.c b/ot_scan.c new file mode 100644 index 0000000..a96f82b --- /dev/null +++ b/ot_scan.c @@ -0,0 +1,44 @@ +/* This software was written by Dirk Engling + It is considered beerware. Prost. Skol. Cheers or whatever. + + $id$ */ + +/* System */ +#include +#include +#include + +/* Opentracker */ +#include "ot_scan.h" + +size_t scan_udec(const char *src, uint64_t *dest, uint64_t max) { + unsigned long long value; + char *end; + + if (*src < '0' || *src > '9') + return 0; + + errno = 0; + value = strtoull(src, &end, 10); + + if (errno == ERANGE || value > (unsigned long long)max) + return 0; + + *dest = (uint64_t)value; + return (size_t)(end - src); +} + +size_t scan_udec_bencode(const char *src, uint64_t *dest, uint64_t max) { + uint64_t value; + size_t consumed = scan_udec(src, &value, max); + + /* bencode writes no leading zeros, so anything longer than a single digit + must not begin with one. */ + if (consumed > 1 && *src == '0') + return 0; + + if (consumed) + *dest = value; + + return consumed; +} diff --git a/ot_scan.h b/ot_scan.h new file mode 100644 index 0000000..860a088 --- /dev/null +++ b/ot_scan.h @@ -0,0 +1,21 @@ +/* This software was written by Dirk Engling + It is considered beerware. Prost. Skol. Cheers or whatever. + + $id$ */ + +#ifndef OT_SCAN_H__ +#define OT_SCAN_H__ + +#include +#include + +/* Read an unsigned decimal number from src into dest and return how many + characters were consumed. Returns zero and leaves dest untouched when src + does not begin with a digit, or when the value would exceed max. */ +size_t scan_udec(const char *src, uint64_t *dest, uint64_t max); + +/* As scan_udec, but following the bencode integer grammar, which permits a + leading zero on zero alone. */ +size_t scan_udec_bencode(const char *src, uint64_t *dest, uint64_t max); + +#endif -- cgit v1.3