summaryrefslogtreecommitdiff
path: root/ot_scan.c
blob: a96f82bd6cb18275410e900084208439efb69bb3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
   It is considered beerware. Prost. Skol. Cheers or whatever.

   $id$ */

/* System */
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>

/* 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;
}