]> git.cameronkatri.com Git - pw-darwin.git/blob - pw/strtounum.c
Actually add the new code
[pw-darwin.git] / pw / strtounum.c
1 /*-
2 * Copyright (C) Baptiste Daroussin <bapt@FreeBSD.org>
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 * SUCH DAMAGE.
24 */
25
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28
29 #include <errno.h>
30 #include <inttypes.h>
31 #include <limits.h>
32 #include <stdlib.h>
33
34 #include "pw.h"
35
36 #define INVALID "invalid"
37 #define TOOSMALL "too small"
38 #define TOOLARGE "too large"
39
40 uintmax_t
41 strtounum(const char *numstr, uintmax_t minval, uintmax_t maxval,
42 const char **errstrp)
43 {
44 uintmax_t ret = 0;
45 char *ep;
46
47 if (minval > maxval) {
48 errno = EINVAL;
49 if (errstrp != NULL)
50 *errstrp = INVALID;
51 return (0);
52 }
53
54 ret = strtoumax(numstr, &ep, 10);
55 if (errno == EINVAL || numstr == ep || *ep != '\0') {
56 errno = EINVAL;
57 if (errstrp != NULL)
58 *errstrp = INVALID;
59 return (0);
60 } else if ((ret == 0 && errno == ERANGE) || ret < minval) {
61 errno = ERANGE;
62 if (errstrp != NULL)
63 *errstrp = TOOSMALL;
64 return (0);
65 } else if ((ret == UINTMAX_MAX && errno == ERANGE) || ret > maxval) {
66 errno = ERANGE;
67 if (errstrp != NULL)
68 *errstrp = TOOLARGE;
69 return (0);
70 }
71
72 return (ret);
73 }