Atom

Interactive text application

This line-oriented command application uses the C standard input stream through FFI. Save it as terminal.atom and run atom run terminal.atom. Type help, count or quit after a line break. It handles UTF-8 input by accumulating the bytes of a whole line. The defaults name common libraries on glibc Linux, Windows and macOS. Supply a different C library path as the first argument on systems using another loader name.

Read one line before decoding it

The inner loop collects bytes until it reaches a newline. Decode the whole line at once so a UTF-8 character can span several bytes.

Excerpt
        line = create(u8, 0)
        loop_byte = getchar()
        while loop_byte >= 0 and loop_byte != 10:
            add(line, loop_byte)
            loop_byte = getchar()
        if loop_byte < 0 and count(line) == 0:
            break
        command = text.trim(binary.text(line))
Show full source 40 lines
terminal.atom
use binary
use ffi
use os
use text

library_name = 'libc.so.6'
if os.platform == 'windows':
    library_name = 'msvcrt.dll'
elif os.platform == 'macos':
    library_name = '/usr/lib/libSystem.B.dylib'

lib = ffi.load(get(os.args, 0, library_name))
try:
    getchar = ffi.bind(lib, 'getchar', [], i32)
    fflush = ffi.bind(lib, 'fflush', [ptr], i32)
    commands = 0
    print('Enter help, count, or quit.')
    fflush(null)
    done = false
    while not done:
        line = create(u8, 0)
        loop_byte = getchar()
        while loop_byte >= 0 and loop_byte != 10:
            add(line, loop_byte)
            loop_byte = getchar()
        if loop_byte < 0 and count(line) == 0:
            break
        command = text.trim(binary.text(line))
        if command == 'quit':
            done = true
        elif command == 'count':
            print('Commands processed: {commands}')
        elif command == 'help':
            print('count reports how many earlier commands ran.')
        else:
            print('Unknown command: {command}')
        commands += 1
        fflush(null)
finally:
    ffi.close(lib)