summaryrefslogtreecommitdiffstats
path: root/src/parsers.c
blob: 85757846a5c38715681ee78c259aa3b138739017 (plain)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <errno.h>

uint64_t *parse_number64(const char *argv)
{
	uint64_t *n = malloc(sizeof(*n));
	char *endptr;

	if (!argv)
		return NULL;

	errno = 0;
	*n = strtoull(argv, &endptr, 0);
	if (errno || *endptr != '\0')
		return NULL;

	return n;
}

uint32_t *parse_number32(const char *argv)
{
	unsigned long long tmp;
	uint32_t *n = malloc(sizeof(*n));
	char *endptr;

	if (!argv)
		return NULL;

	errno = 0;
	tmp = strtoul(argv, &endptr, 0);
	if (errno || *endptr != '\0' || tmp > UINT32_MAX)
		return NULL;

	*n = tmp;
	return n;
}

uint16_t *parse_number16(const char *argv)
{
	unsigned long long tmp;
	uint16_t *n = malloc(sizeof(*n));
	char *endptr;

	if (!argv)
		return NULL;

	errno = 0;
	tmp = strtoul(argv, &endptr, 0);
	if (errno || *endptr != '\0' || tmp > UINT16_MAX)
		return NULL;

	*n = tmp;
	return n;
}

/* Parse an 8-bit number that is a power of 2 */
uint8_t *parse_number8_pow2(const char *argv)
{
	uint8_t *n;
	unsigned long int tmp, i;
	char *endptr;

	if (!argv)
		return NULL;

	errno = 0;
	tmp = strtoul(argv, &endptr, 0);
	if (tmp >= 256)
		return NULL;

	for (i = tmp; i; i >>= 1)
		if ((i & 1) && (i >> 1))
			return NULL;

	n = malloc(sizeof(*n));
	*n = tmp;

	return n;
}

/* Parse a GPR number, returning an error if it's greater than 32 */
int *parse_gpr(const char *argv)
{
	int *gpr = malloc(sizeof(*gpr));
	char *endptr;

	if (!argv)
		return NULL;

	errno = 0;
	*gpr = strtoul(argv, &endptr, 0);
	if (errno || *endptr != '\0' || *gpr > 32)
		return NULL;

	return gpr;
}

/* Parse an SPR. Currently only supports SPR by numbers but could be extended to
 * support names (eg. lr) */
int *parse_spr(const char *argv)
{
	int *spr = malloc(sizeof(*spr));
	char *endptr;

	if (!argv)
		return NULL;

	errno = 0;
	*spr = strtoul(argv, &endptr, 0);
	if (errno || *endptr != '\0' || *spr > 0x3ff)
		return NULL;

	return spr;
}


/* A special parser that always returns true. Allows for boolean flags which
 * don't take arguments. Sets the associated field to true if specified,
 * otherwise sets it to the default value (usually false). */
bool *parse_flag_noarg(const char *argv)
{
	bool *result = malloc(sizeof(*result));

	*result = true;
	return result;
}
OpenPOWER on IntegriCloud