-
Notifications
You must be signed in to change notification settings - Fork 0
/
hfcz.c
135 lines (121 loc) · 2.11 KB
/
hfcz.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "hfc.h"
#include "queue.h"
#include "bytes.h"
static void usage() {
printf("hfcz [-u] <file>\n");
exit(1);
}
static int compress(const char *filename) {
int fd;
struct stat stat;
int r;
fd = open(filename, O_RDONLY);
if (fd == -1) {
return -1;
}
r = fstat(fd, &stat);
if (r == -1) {
return -1;
}
size_t size = stat.st_size;
uint8_t *buff = malloc(size + 1);
if (buff == NULL) {
return -1;
}
r = read(fd, buff, size);
if (r == -1) {
return -1;
}
buff[size] = '\0'; // handle missing final newline
int lines = 0;
for (int i = 0; i < size; ++i) {
if (buff[i] == '\n') {
lines++;
}
}
char **strs = malloc(sizeof(char *) * lines);
if (strs == NULL) {
return -1;
}
uint8_t *c = buff;
char **s = strs;
for (int i = 0; i < size; ++i) {
if (buff[i] == '\n') {
*s = c;
++s;
buff[i] = '\0';
c = buff + i + 1;
}
}
struct bytes *cmp = hfc_compress(lines, strs);
r = write(1, cmp->bytes, cmp->len);
if (r == -1) {
return -1;
}
free(strs);
free(buff);
bytes_free(cmp);
return 0;
}
// XXX error handling
static int decompress(char *filename) {
struct stat filestats;
int r;
r = stat(filename, &filestats);
if (r == -1) {
return -1;
}
off_t size = filestats.st_size;
char *buff = malloc(size);
if (buff == NULL) {
return -1;
}
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
return -1;
}
r = fread(buff, 1, size, fp);
if (r < size) {
return -1;
}
fclose(fp);
struct hfc *hfc = hfc_new(buff, size);
struct hfc_iter *iter = hfc_iter_init(hfc);
char *s = hfc_iter_next(iter);
while (s) {
printf("%s\n", s);
s = hfc_iter_next(iter);
}
hfc_iter_free(iter);
hfc_free(hfc);
return 0;
}
int main(int argc, char *argv[]) {
int d = 0;
int r;
char *filename;
if (argc < 2) {
usage();
}
if (!strcmp(argv[1], "-u")) {
if (argc < 3) {
usage();
}
r = decompress(argv[2]);
} else {
r = compress(argv[1]);
}
if (r != 0) {
perror("Failed with error");
exit(-1);
}
exit(0);
}