parseint.c revision 1.2
1/* $NetBSD: parseint.c,v 1.2 2018/08/12 13:02:37 christos Exp $ */ 2 3/* 4 * Copyright (C) Internet Systems Consortium, Inc. ("ISC") 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 http://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 15/*! \file */ 16 17#include <config.h> 18 19#include <ctype.h> 20#include <errno.h> 21#include <limits.h> 22 23#include <isc/parseint.h> 24#include <isc/result.h> 25#include <isc/stdlib.h> 26 27isc_result_t 28isc_parse_uint32(isc_uint32_t *uip, const char *string, int base) { 29 unsigned long n; 30 isc_uint32_t r; 31 char *e; 32 if (! isalnum((unsigned char)(string[0]))) 33 return (ISC_R_BADNUMBER); 34 errno = 0; 35 n = strtoul(string, &e, base); 36 if (*e != '\0') 37 return (ISC_R_BADNUMBER); 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 r = (isc_uint32_t)n; 44 if ((n == ULONG_MAX && errno == ERANGE) || (n != (unsigned long)r)) 45 return (ISC_R_RANGE); 46 *uip = r; 47 return (ISC_R_SUCCESS); 48} 49 50isc_result_t 51isc_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 63isc_result_t 64isc_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