/src/bind9/lib/isc/parseint.c
Line | Count | Source |
1 | | /* |
2 | | * Copyright (C) Internet Systems Consortium, Inc. ("ISC") |
3 | | * |
4 | | * SPDX-License-Identifier: MPL-2.0 |
5 | | * |
6 | | * This Source Code Form is subject to the terms of the Mozilla Public |
7 | | * License, v. 2.0. If a copy of the MPL was not distributed with this |
8 | | * file, you can obtain one at https://mozilla.org/MPL/2.0/. |
9 | | * |
10 | | * See the COPYRIGHT file distributed with this work for additional |
11 | | * information regarding copyright ownership. |
12 | | */ |
13 | | |
14 | | /*! \file */ |
15 | | |
16 | | #include <ctype.h> |
17 | | #include <errno.h> |
18 | | #include <inttypes.h> |
19 | | #include <limits.h> |
20 | | #include <stdlib.h> |
21 | | |
22 | | #include <isc/parseint.h> |
23 | | #include <isc/result.h> |
24 | | |
25 | | isc_result_t |
26 | 3.15M | isc_parse_uint32(uint32_t *uip, const char *string, int base) { |
27 | 3.15M | unsigned long n; |
28 | 3.15M | uint32_t r; |
29 | 3.15M | char *e; |
30 | 3.15M | if (!isalnum((unsigned char)(string[0]))) { |
31 | 178k | return ISC_R_BADNUMBER; |
32 | 178k | } |
33 | 3.15M | errno = 0; |
34 | 2.98M | n = strtoul(string, &e, base); |
35 | 2.98M | if (*e != '\0') { |
36 | 439 | return ISC_R_BADNUMBER; |
37 | 439 | } |
38 | | /* |
39 | | * Where long is 64 bits we need to convert to 32 bits then test for |
40 | | * equality. This is a no-op on 32 bit machines and a good compiler |
41 | | * will optimise it away. |
42 | | */ |
43 | 2.98M | r = (uint32_t)n; |
44 | 2.98M | if ((n == ULONG_MAX && errno == ERANGE) || (n != (unsigned long)r)) { |
45 | 3.01k | return ISC_R_RANGE; |
46 | 3.01k | } |
47 | 2.97M | *uip = r; |
48 | 2.97M | return ISC_R_SUCCESS; |
49 | 2.98M | } |
50 | | |
51 | | isc_result_t |
52 | 0 | isc_parse_uint16(uint16_t *uip, const char *string, int base) { |
53 | 0 | uint32_t val; |
54 | |
|
55 | 0 | RETERR(isc_parse_uint32(&val, string, base)); |
56 | 0 | if (val > 0xFFFF) { |
57 | 0 | return ISC_R_RANGE; |
58 | 0 | } |
59 | 0 | *uip = (uint16_t)val; |
60 | 0 | return ISC_R_SUCCESS; |
61 | 0 | } |
62 | | |
63 | | isc_result_t |
64 | 76.1k | isc_parse_uint8(uint8_t *uip, const char *string, int base) { |
65 | 76.1k | uint32_t val; |
66 | | |
67 | 76.1k | RETERR(isc_parse_uint32(&val, string, base)); |
68 | 76.0k | if (val > 0xFF) { |
69 | 110 | return ISC_R_RANGE; |
70 | 110 | } |
71 | 75.9k | *uip = (uint8_t)val; |
72 | 75.9k | return ISC_R_SUCCESS; |
73 | 76.0k | } |