From 477abc9aa1d376618080bb1b836c9ef853e31e87 Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Fri, 6 Feb 2026 07:05:10 +0000 Subject: [PATCH] stream: stream_sv and stream_sv_abs Just straight string views into the current stream content - obviously may not be stable. Helpful when analysing a non-moving stream. --- include/alisp/stream.h | 6 ++++++ src/stream.c | 43 +++++++++++++++++++++++++++--------------- 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/include/alisp/stream.h b/include/alisp/stream.h index 36fa09c..c8f0a94 100644 --- a/include/alisp/stream.h +++ b/include/alisp/stream.h @@ -70,6 +70,12 @@ u64 stream_seek(stream_t *, i64); u64 stream_seek_forward(stream_t *, u64); u64 stream_seek_backward(stream_t *, u64); +// Return a string view to stream data relative to the current position of the +// stream +sv_t stream_sv(stream_t *); +// Return a string view to data from the start of the stream +sv_t stream_sv_abs(stream_t *); + // Return a relative substring of a given size sv_t stream_substr(stream_t *, u64); // Return an absolute substring at given index and of given size. diff --git a/src/stream.c b/src/stream.c index b332275..6c7124b 100644 --- a/src/stream.c +++ b/src/stream.c @@ -11,6 +11,8 @@ #include #include +#include +#include const char *stream_err_to_cstr(stream_err_t err) { @@ -310,6 +312,32 @@ u64 stream_seek_backward(stream_t *stream, u64 offset) return offset; } +sv_t stream_sv(stream_t *stream) +{ + return sv_chop_left(stream_sv_abs(stream), stream->position); +} + +sv_t stream_sv_abs(stream_t *stream) +{ + if (!stream) + return SV(NULL, 0); + sv_t sv = {0}; + switch (stream->type) + { + case STREAM_TYPE_STRING: + sv = stream->string; + break; + case STREAM_TYPE_PIPE: + case STREAM_TYPE_FILE: + sv = SV((char *)vec_data(&stream->pipe.cache), stream_size(stream)); + break; + default: + FAIL("Unreachable"); + return SV(NULL, 0); + } + return sv; +} + sv_t stream_substr(stream_t *stream, u64 size) { if (stream_eoc(stream)) @@ -324,21 +352,6 @@ sv_t stream_substr(stream_t *stream, u64 size) if (successful != size) return SV(NULL, 0); - char *ptr = NULL; - switch (stream->type) - { - case STREAM_TYPE_STRING: - ptr = stream->string.data; - break; - case STREAM_TYPE_PIPE: - case STREAM_TYPE_FILE: - ptr = (char *)vec_data(&stream->pipe.cache); - break; - default: - FAIL("Unreachable"); - return SV(NULL, 0); - } - return SV(ptr + stream->position, size); }