Spans: give a parser a range of a stream it cannot read past.
Spans: give a parser a range of a stream it cannot read past.File formats hold tables at offsets: a font file holds its glyph table here, its metrics there. A span turns one range of a stream into a stream of its own, checked once when it is created. From then on, a parser that trusts a corrupt length still cannot read a byte of the next table: the span stops at its end, and bj_stream_peek answers 0 rather than a pointer past it.
What you'll learn
- bj_create_stream_span, and why its bounds are checked once.
- That a span has its own cursor, and never moves its parent's.
- bj_stream_peek on a span, and the 0 it gives out of range.
int main(
int argc,
char* argv[]) {
(void)argc; (void)argv;
static const char file_bytes[] = "HEADname1234";
bj_info(
"Span of NAME: %s; span of 8 bytes at 10: %s",
name != 0 ? "created" : "refused", broken != 0 ? "created" : "refused");
if (name == 0) {
return 1;
}
char buffer[9] = {0};
bj_info(
"Asked 8 bytes, got %zu: \"%s\", %s", got, buffer,
bj_info(
"Peek of 2 bytes at 1: \"%.2s\"; at 3: %s", inside, outside == 0 ?
"0" :
"a pointer");
return 0;
}
struct bj_stream bj_stream
#define bj_info(...)
Log a message using the BJ_LOG_INFO level.
const void * bj_stream_peek(struct bj_stream *stream, size_t offset, size_t length)
Points at bytes of the stream without moving the cursor.
void bj_destroy_stream(struct bj_stream *stream)
Destroy a stream and release its memory.
size_t bj_stream_position(struct bj_stream *stream)
Return the current cursor position within the stream.
struct bj_stream * bj_create_stream_span(struct bj_stream *parent, size_t offset, size_t length)
Create a span over the range [offset, offset + length) of another stream.
struct bj_stream * bj_create_stream_from_read_memory(const void *data, size_t length)
Create a read-only stream that reads from an in-memory buffer.
bj_stream_status
Why the last read or write of a stream fell short.
size_t bj_read_stream(struct bj_stream *stream, void *dest, size_t count)
Reads data from the stream into a destination buffer.
@ BJ_STREAM_STATUS_END
The data ran out, or a fixed-size stream is full.
Logging utility functions.
Portable main() replacement with platform-aware entry shim.
Header file for struct bj_stream struct and related functions.