xref: /netbsd/external/bsd/ntp/dist/lib/isc/parseint.c (revision 6550d01e)
1 /*	$NetBSD: parseint.c,v 1.1.1.1 2009/12/13 16:54:11 kardel Exp $	*/
2 
3 /*
4  * Copyright (C) 2004, 2005, 2007  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 	char *e;
38 	if (! isalnum((unsigned char)(string[0])))
39 		return (ISC_R_BADNUMBER);
40 	errno = 0;
41 	n = strtoul(string, &e, base);
42 	if (*e != '\0')
43 		return (ISC_R_BADNUMBER);
44 	if (n == ULONG_MAX && errno == ERANGE)
45 		return (ISC_R_RANGE);
46 	*uip = n;
47 	return (ISC_R_SUCCESS);
48 }
49 
50 isc_result_t
51 isc_parse_uint16(isc_uint16_t *uip, const char *string, int base) {
52 	isc_uint32_t val;
53 	isc_result_t result;
54 	result = isc_parse_uint32(&val, string, base);
55 	if (result != ISC_R_SUCCESS)
56 		return (result);
57 	if (val > 0xFFFF)
58 		return (ISC_R_RANGE);
59 	*uip = (isc_uint16_t) val;
60 	return (ISC_R_SUCCESS);
61 }
62 
63 isc_result_t
64 isc_parse_uint8(isc_uint8_t *uip, const char *string, int base) {
65 	isc_uint32_t val;
66 	isc_result_t result;
67 	result = isc_parse_uint32(&val, string, base);
68 	if (result != ISC_R_SUCCESS)
69 		return (result);
70 	if (val > 0xFF)
71 		return (ISC_R_RANGE);
72 	*uip = (isc_uint8_t) val;
73 	return (ISC_R_SUCCESS);
74 }
75