repos / gbc

GBC - Go B Compiler
git clone https://github.com/xplshn/gbc.git

gbc / examples
xplshn  ·  2025-08-16

txtfmt.bx

Bx
 1extrn putchar, getchar;
 2
 3MAX_WIDTH 70;
 4
 5byte line_buf[100];
 6byte word_buf[50];
 7int line_len;
 8int word_len;
 9
10void print_string(s byte*, len int) {
11    auto i;
12    i = 0;
13    while (i < len) {
14        putchar(s[i]);
15        i++;
16    }
17}
18
19void flush_line() {
20    if (line_len > 0) {
21        print_string(line_buf, line_len);
22        putchar('\n');
23    }
24    line_len = 0;
25}
26
27void append_word_to_line() {
28    auto i;
29
30    if (line_len > 0) {
31        line_buf[line_len] = ' ';
32        line_len++;
33    }
34
35    i = 0;
36    while (i < word_len) {
37        line_buf[line_len] = word_buf[i];
38        line_len++;
39        i++;
40    }
41    word_len = 0;
42}
43
44main() {
45    auto c;
46
47    line_len = 0;
48    word_len = 0;
49
50    while ((c = getchar()) != -1) { // -1 == EOF
51        if (c == ' ' || c == '\t' || c == '\n') {
52            // Whitespace detected, process the completed word
53            if (word_len > 0) {
54                if (line_len + word_len + 1 > MAX_WIDTH) {
55                    // Word doesn't fit, flush the current line first
56                    flush_line();
57                }
58                append_word_to_line();
59            }
60
61            if (c == '\n') {
62                // An explicit newline in the input flushes the current line
63                flush_line();
64            }
65        } else {
66            // It's a character for the current word
67            if (word_len < 49) {
68                word_buf[word_len] = c;
69                word_len++;
70            }
71        }
72    }
73
74    // End of input, process any remaining word and flush the last line
75    if (word_len > 0) {
76        if (line_len + word_len + 1 > MAX_WIDTH) {
77            flush_line();
78        }
79        append_word_to_line();
80    }
81    flush_line();
82
83    return (0);
84}