summaryrefslogtreecommitdiff
path: root/ot_scan.c
blob: c4b951a6632d5b9fb0f07a6d22ee047f35bec707 (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* 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_uint(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_uint_bencode(const char *src, uint64_t *dest, uint64_t max) {
  uint64_t value;
  size_t   consumed = scan_uint(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;
}

int scan_int(const char *src, size_t len, int64_t *dest) {
  int64_t value  = 0;
  int     negate = 0;

  if (len && *src == '-')
    --len, ++src, negate = 1;
  if (!len)
    return -1;

  while (len--) {
    if (*src < '0' || *src > '9')
      return -1;
    /* A twenty character field of nines does not fit, and silently wrapping
       would magically heal a nonsense announce */
    if (value > (INT64_MAX - (*src - '0')) / 10)
      return -1;
    value = 10 * value + (*src++ - '0');
  }

  *dest = negate ? -value : value;
  return 0;
}