xref: /minix/external/bsd/bind/dist/lib/isc/parseint.c (revision bb9622b5)
1 /*	$NetBSD: parseint.c,v 1.5 2014/12/10 04:37:59 christos Exp $	*/
2 
3 /*
4  * Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc. ("ISC")
5  * Copyright (C) 2001-2003  Internet Software Consortium.
6  *
7  * Permission to use, copy, modify, and/or distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
12  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
14  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
16  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17  * PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /* Id: parseint.c,v 1.8 2007/06/19 23:47:17 tbox Exp  */
21 
22 /*! \file */
23 
24 #include <config.h>
25 
26 #include <ctype.h>
27 #include <errno.h>
28 #include <limits.h>
29 
30 #include <isc/parseint.h>
31 #include <isc/result.h>
32 #include <isc/stdlib.h>
33 
34 isc_result_t
35 isc_parse_uint32(isc_uint32_t *uip, const char *string, int base) {
36 	unsigned long n;
37 	isc_uint32_t r;
38 	char *e;
39 	if (! isalnum((unsigned char)(string[0])))
40 		return (ISC_R_BADNUMBER);
41 	errno = 0;
42 	n = strtoul(string, &e, base);
43 	if (*e != '\0')
44 		return (ISC_R_BADNUMBER);
45 	/*
46 	 * Where long is 64 bits we need to convert to 32 bits then test for
47 	 * equality.  This is a no-op on 32 bit machines and a good compiler
48 	 * will optimise it away.
49 	 */
50 	r = (isc_uint32_t)n;
51 	if ((n == ULONG_MAX && errno == ERANGE) || (n != (unsigned long)r))
52 		return (ISC_R_RANGE);
53 	*uip = r;
54 	return (ISC_R_SUCCESS);
55 }
56 
57 isc_result_t
58 isc_parse_uint16(isc_uint16_t *uip, const char *string, int base) {
59 	isc_uint32_t val;
60 	isc_result_t result;
61 	result = isc_parse_uint32(&val, string, base);
62 	if (result != ISC_R_SUCCESS)
63 		return (result);
64 	if (val > 0xFFFF)
65 		return (ISC_R_RANGE);
66 	*uip = (isc_uint16_t) val;
67 	return (ISC_R_SUCCESS);
68 }
69 
70 isc_result_t
71 isc_parse_uint8(isc_uint8_t *uip, const char *string, int base) {
72 	isc_uint32_t val;
73 	isc_result_t result;
74 	result = isc_parse_uint32(&val, string, base);
75 	if (result != ISC_R_SUCCESS)
76 		return (result);
77 	if (val > 0xFF)
78 		return (ISC_R_RANGE);
79 	*uip = (isc_uint8_t) val;
80 	return (ISC_R_SUCCESS);
81 }
82