3 ms·
A concrete example that I've been working on recently: a parser/lexer backed by an input buffer. Its state looks like this: struct parser { struct {
by matheusmoreira 4y ago
A concrete example that I've been working on recently: a parser/lexer backed by an input buffer. Its state looks like this:
struct parser {
struct {
unsigned char *buffer;
size_t capacity;
} buffer;
struct {
size_t read;
size_t write;
} position;
};
The lexer makes progress by consuming bytes from the buffer, incremeting the read position. The buffer is reallocated whenever such a read would overrun the write position: I/O functions are called to fill up the buffer and push the write position further ahead.
Had they been pointers within the [buffer, capacity[ range, they would have become invalid whenever buffer is reallocated for expansion since its location in memory would change. So I chose to implement the read and write heads as offsets to the buffer's base address and calculating those pointers only when they're needed.