-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.c
110 lines (101 loc) · 1.7 KB
/
tools.c
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
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#ifndef __EMSCRIPTEN__
#include <zlib.h>
#endif /* __EMSCRIPTEN */
#include "platform.h"
#include "tools.h"
uint8_t *load_file(const char *filename, size_t *size_out) {
FILE *f = fopen(filename, "rb");
if(!f) {
fprintf(
stderr,
"Could not open %s: %s (%d)\n",
filename,
strerror(errno),
errno
);
return NULL;
}
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
uint8_t *data = malloc(size);
if(!data) {
fprintf(
stderr,
"Could not allocate %"PRIuSIZET" bytes for %s: %s (%d)\n",
size, filename, strerror(errno), errno
);
fclose(f);
return NULL;
}
rewind(f);
fread(data, 1, size, f);
fclose(f);
if(size_out) *size_out = size;
return data;
}
int gcd(int a, int b) {
int c = a % b;
while(c > 0) {
a = b;
b = c;
c = a % b;
}
return b;
}
void csv_quote(char *str, size_t len) {
if(len == 0) len = strlen(str);
if(str == 0) {
putchar('\\');
putchar('N');
return;
}
putchar('"');
for(int i = 0; i < len; i++) {
switch(str[i]) {
case 0:
putchar('\\');
putchar(0);
break;
case '\\':
putchar('\\');
putchar('\\');
break;
case '\b':
putchar('\\');
putchar('b');
break;
case '\n':
putchar('\\');
putchar('n');
break;
case '\r':
putchar('\\');
putchar('r');
break;
case '\t':
putchar('\\');
putchar('t');
break;
case 26:
putchar('\\');
putchar('Z');
break;
case '"':
putchar('"');
putchar('"');
break;
default: putchar(str[i]);
}
}
putchar('"');
}