aboutsummaryrefslogtreecommitdiff
path: root/src/brle-enc.c
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-07 02:33:00 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-07 02:38:20 +0000
commit795a8ecaf5656d299139e2c41fab19573bdac0c6 (patch)
tree9d0529ad1abd7959256b139b2c9c6b7fa3e72e07 /src/brle-enc.c
downloadlab-00-master.tar.gz
publishHEADmaster
Diffstat (limited to 'src/brle-enc.c')
-rw-r--r--src/brle-enc.c94
1 files changed, 94 insertions, 0 deletions
diff --git a/src/brle-enc.c b/src/brle-enc.c
new file mode 100644
index 0000000..d14c462
--- /dev/null
+++ b/src/brle-enc.c
@@ -0,0 +1,94 @@
1#include <stdlib.h>
2#include <stdio.h>
3#include <stdint.h>
4#include <wchar.h>
5#include <locale.h>
6#include <stdbool.h>
7#include <libgen.h>
8
9#include "config.h"
10
11FILE *istream;
12FILE *ostream;
13
14char
15getbit (void)
16{
17 static int byte;
18 static int i = 8;
19 if (i > 7) {
20 byte = fgetc (istream);
21 if (byte == EOF)
22 return -1;
23 i = 0;
24 }
25 char bit = byte >> i & 1;
26 i += 1;
27 return bit;
28}
29
30bool
31put4bit (uint8_t data)
32{
33 static uint8_t byte;
34 static bool nonempty = false;
35 if (nonempty) {
36 byte |= data << 4;
37 fputc (byte, ostream);
38 nonempty = false;
39 } else {
40 byte = data & (1 << 4) - 1;
41 nonempty = true;
42 }
43 return nonempty;
44}
45
46int
47main (int argc, char *argv[])
48{
49 setlocale (LC_ALL, "");
50
51 if (argc != 3) {
52 fprintf (stderr, "Usage: %s {infile} {outfile}\n", basename (argv[0]));
53 return EXIT_FAILURE;
54 }
55
56 istream = fopen (argv[1], "rb");
57 if (istream == NULL) {
58 perror (NULL);
59 return EXIT_FAILURE;
60 }
61
62 ostream = fopen (argv[2], "wb");
63 if (ostream == NULL) {
64 perror (NULL);
65 return EXIT_FAILURE;
66 }
67
68 char current = getbit ();
69 bool nonempty;
70 while (current != -1) {
71 uint8_t count = 1;
72 char next;
73 while ((next = getbit ()) == current && count < (1 << 3) - 1)
74 ++count;
75
76 nonempty = put4bit (current << 3 | count);
77
78 current = next;
79 }
80 if (nonempty)
81 put4bit (0);
82
83 if (fclose (ostream) == EOF) {
84 perror (NULL);
85 return EXIT_FAILURE;
86 }
87
88 if (fclose (istream) == EOF) {
89 perror (NULL);
90 return EXIT_FAILURE;
91 }
92
93 return EXIT_SUCCESS;
94}