summary refs log tree commit diff
path: root/num.c
blob: ac7f0a4926f680d864818a3c5aa4a89fdfe9bb1c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// SPDX-License-Identifier: GPL-2.0-or-later
// SPDX-FileCopyrightText: 2020 Alyssa Ross <hi@alyssa.is>

#define _GNU_SOURCE

#include "num.h"

#include <ctype.h>
#include <stdlib.h>

int getu32(const char *s, uint32_t min, uint32_t max, uint32_t *out)
{
	unsigned long l;

	if (getul(s, min, max, &l) == -1)
		return -1;

	*out = (uint32_t)l;

	return 0;
}

int getul(const char *s, unsigned long min, unsigned long max,
	  unsigned long *out)
{
	char *endptr;

	if (!s || !isdigit(s[0]) || (s[0] == '0' && s[1]))
		return -1;

	*out = strtoul(s, &endptr, 10);

	if (*endptr || *out < min || *out > max)
		return -1;

	return 0;
}