#Best way to stream numbers parsed from a reader?

1 messages · Page 1 of 1 (latest)

storm dove
#

Hello, I'm new to Zig!

For context, I'm working on a small graphing CLI, I'd like it to read numbers from stdin, refreshing a CLI graph (using ncurses) as they come in.

For that, I'd like to, on startup, read as much data as we have, render the graph, then block for input on either stdin or the tty (via ncurses).

Here's the number-parsing code I've got, it's passing my tests and will parse floats out from among other text:

fn getNum(alloc: anytype, reader: anytype) ?f32 {
    var char_arr = std.ArrayList(u8).init(alloc);
    defer char_arr.deinit();
    outer: while (reader.readByte() catch null) |byte| {
        if ((byte < '0' or byte > '9') and byte != '.') {
            continue;
        } else {
            char_arr.append(byte) catch return null;
            while (reader.readByte() catch null) |next_byte| {
                if (((next_byte >= '0' and next_byte <= '9') or next_byte == '.')) {
                    char_arr.append(next_byte) catch return null;
                    continue;
                } else {
                    break :outer;
                }
            }
            break :outer;
        }
    }
    if (char_arr.items.len > 0) {
        const num = std.fmt.parseFloat(f32, char_arr.items) catch return null;
        return num;
    } else {
        return null;
    }
}

This passes my tests, but unfortunately it just reads till EOF, and if there's no data it will block.

  1. Is there a good way to know which IO reader methods block and which don't?
  2. Is there a better way to handle concurrent input/streaming like this without anything async?
storm dove
smoky skiff
#

Set fds to non_blocking and use i/o multiplexing