aboutsummaryrefslogtreecommitdiff
path: root/src/utils.c
blob: da48ef62e41295452664341bb9cca974927e1bde (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
#include "utils.h"
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>

int is_number(char *str)
{
	unsigned int length = strlen(str);

	for (unsigned int c = 0; c < length; c++)
		if (!isdigit(str[c]))
			return 0;

	return 1;
}


void *malloc_s(unsigned long amount)
{
	void *memory = malloc(amount);

	if (memory == NULL)
	{
		printf("Error: Memory allocation failed");
		exit(EXIT_FAILURE);
	}

	return memory;
}

unsigned int str_to_uint(char *str, char **err)
{
	if (*str == '-')
	{
		*err = "Less than 0";
		return 0;
	}

	char *str_waste;
	unsigned long num = strtoul(str, &str_waste, 10);

	if (strlen(str_waste) != 0)
	{
		*err = "Not a number";
		return 0;
	}

	if (num > (unsigned long)UINT_MAX)
	{
		*err = "Too large";
		return 0;
	}

	return (unsigned int)num;
}