-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.c
More file actions
65 lines (59 loc) · 1.45 KB
/
common.c
File metadata and controls
65 lines (59 loc) · 1.45 KB
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
#include "common.h"
#include <stdlib.h>
#include <string.h>
string_t create_string(char *data) {
if (data == NULL) {
string_t string = {.data = malloc(sizeof(char)), .length = 0};
string.data[0] = '\0';
return string;
}
size_t len = strlen(data);
string_t string = {.data = malloc((len + 1) * sizeof(char)), .length = len};
memcpy(string.data, data, len + 1);
return string;
}
void append_char_to_str(string_t *string, char c) {
string->length++;
string->data = realloc(string->data, (string->length + 1) * sizeof(char));
string->data[string->length - 1] = c;
string->data[string->length] = '\0';
}
void append_str_to_str(string_t *string, char *other) {
size_t old_len = string->length;
size_t other_len = strlen(other);
string->length += other_len;
string->data = realloc(string->data, (string->length + 1) * sizeof(char));
memcpy(&string->data[old_len], other, other_len + 1);
}
char *print_char(int c) {
char *result = NULL;
switch (c) {
case EOF:
return "EOF";
case 0:
return "\\0";
case 9:
return "\\t";
case 10:
return "\\n";
case 13:
return "\\r";
case 32:
return "\\s";
case 33 ... 126:
asprintf(&result, "%c", c);
break;
default:
if (c >= 0 && c < 256) {
asprintf(&result, "\\x%hhx", c);
} else {
asprintf(&result, "\\?%x", c);
}
}
return result;
}
void fprint_indent(int indent, FILE *fout) {
while (indent-- > 0) {
fprintf(fout, " ");
}
}