-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.cpp
60 lines (55 loc) · 1.46 KB
/
utils.cpp
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
#include "utils.h"
#include "common.h"
#include <cstdlib>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
File::~File() {
delete[] contents;
}
bool File::read_entire_file_into_memory(const char *filename, File *out_file) {
int fd = open(filename, O_RDONLY);
if (fd == -1)
return false;
struct stat info{};
fstat(fd, &info);
char *contents = new char[info.st_size];
ssize_t res = read(fd, contents, info.st_size) == info.st_size;
assert(res);
out_file->contents = contents;
out_file->size = info.st_size;
close(fd);
return true;
}
bool string_to_u64(char *string, uint64_t *out) {
char *valid;
*out = strtoul(string, &valid, 10);
return *valid == '\0';
}
size_t read_line_from_stream(StretchyBuf<char> &buffer, int fd) {
char ch;
size_t total_read{0U};
ssize_t bytes_read;
while (true) {
bytes_read = read(fd, &ch, sizeof(char));
if (bytes_read <= 0) break;
total_read += bytes_read;
buffer.push((char) ch);
if (ch == '\n') break;
}
// This is an edge case where the file descriptor is coming from an actual file
// and we encountered the end of file but the last line hasn't a newline character
// at it so we add it explicitly for uniformity reasons
if (bytes_read <= 0) {
return -1;
} else {
if (buffer[buffer.len - 1] != '\n') {
buffer.push('\n');
++total_read;
}
}
return total_read;
}
bool file_exists(const char *filename) {
return access(filename, F_OK) != -1;
}