From 795a8ecaf5656d299139e2c41fab19573bdac0c6 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sat, 7 Nov 2026 05:33:00 +0300 Subject: publish --- src/brle-enc.c | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 src/brle-enc.c (limited to 'src/brle-enc.c') 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 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" + +FILE *istream; +FILE *ostream; + +char +getbit (void) +{ + static int byte; + static int i = 8; + if (i > 7) { + byte = fgetc (istream); + if (byte == EOF) + return -1; + i = 0; + } + char bit = byte >> i & 1; + i += 1; + return bit; +} + +bool +put4bit (uint8_t data) +{ + static uint8_t byte; + static bool nonempty = false; + if (nonempty) { + byte |= data << 4; + fputc (byte, ostream); + nonempty = false; + } else { + byte = data & (1 << 4) - 1; + nonempty = true; + } + return nonempty; +} + +int +main (int argc, char *argv[]) +{ + setlocale (LC_ALL, ""); + + if (argc != 3) { + fprintf (stderr, "Usage: %s {infile} {outfile}\n", basename (argv[0])); + return EXIT_FAILURE; + } + + istream = fopen (argv[1], "rb"); + if (istream == NULL) { + perror (NULL); + return EXIT_FAILURE; + } + + ostream = fopen (argv[2], "wb"); + if (ostream == NULL) { + perror (NULL); + return EXIT_FAILURE; + } + + char current = getbit (); + bool nonempty; + while (current != -1) { + uint8_t count = 1; + char next; + while ((next = getbit ()) == current && count < (1 << 3) - 1) + ++count; + + nonempty = put4bit (current << 3 | count); + + current = next; + } + if (nonempty) + put4bit (0); + + if (fclose (ostream) == EOF) { + perror (NULL); + return EXIT_FAILURE; + } + + if (fclose (istream) == EOF) { + perror (NULL); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} -- cgit v1.3.1