aboutsummaryrefslogtreecommitdiff
path: root/src/utils.c
diff options
context:
space:
mode:
authorHampus <hampus@hampusmat.com>2022-01-04 18:55:51 +0100
committerHampus <hampus@hampusmat.com>2022-01-05 20:09:27 +0100
commite3690eb85a9456cc1f3ccda751ae7d9fdf2d3b03 (patch)
tree2fdd32726d753495bf562102a0531101eaa1ddfd /src/utils.c
parent1bed3ac57906b26ef05b25c2bc5c1dca424dba4a (diff)
refactor: improve even more
Diffstat (limited to 'src/utils.c')
-rw-r--r--src/utils.c54
1 files changed, 47 insertions, 7 deletions
diff --git a/src/utils.c b/src/utils.c
index 93f7c53..69ce55d 100644
--- a/src/utils.c
+++ b/src/utils.c
@@ -1,17 +1,57 @@
#include "utils.h"
#include <ctype.h>
#include <string.h>
+#include <stdlib.h>
+#include <limits.h>
-/**
- * Returns whether or not a string is a number.
- */
int is_number(char *str)
{
- size_t len = strlen(str);
- for (int c = 0; c < len; c++)
- {
+ 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 = "Not greater 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;
+}
+