stream: Refactor stream_substr and stream_substr_abs using stream_sv

Bit more elegant, and allows the caller code to focus on the task
rather than string management.
This commit is contained in:
2026-02-06 07:06:03 +00:00
committed by oreodave
parent 477abc9aa1
commit 9ee8955908

View File

@@ -352,7 +352,9 @@ sv_t stream_substr(stream_t *stream, u64 size)
if (successful != size) if (successful != size)
return SV(NULL, 0); return SV(NULL, 0);
return SV(ptr + stream->position, size); sv_t sv = stream_sv(stream);
sv = sv_truncate(sv, size);
return sv;
} }
sv_t stream_substr_abs(stream_t *stream, u64 index, u64 size) sv_t stream_substr_abs(stream_t *stream, u64 index, u64 size)
@@ -360,23 +362,21 @@ sv_t stream_substr_abs(stream_t *stream, u64 index, u64 size)
switch (stream->type) switch (stream->type)
{ {
case STREAM_TYPE_STRING: case STREAM_TYPE_STRING:
if (index + size <= stream_size(stream)) return sv_truncate(sv_chop_left(stream_sv_abs(stream), index), size);
return SV(stream->string.data + index, size);
return SV(NULL, 0);
case STREAM_TYPE_PIPE: case STREAM_TYPE_PIPE:
case STREAM_TYPE_FILE: case STREAM_TYPE_FILE:
{ {
if (index + size <= stream_size(stream)) if (index + size > stream_size(stream))
return SV((char *)vec_data(&stream->pipe.cache) + index, size); // => try reading chunks till either we drop or we have enough space
// (index + size > stream_size(stream)) => try reading chunks
for (bool read_chunk = stream_chunk(stream); for (bool read_chunk = stream_chunk(stream);
read_chunk && index + size >= stream->pipe.cache.size; read_chunk && index + size >= stream->pipe.cache.size;
read_chunk = stream_chunk(stream)) read_chunk = stream_chunk(stream))
continue; continue;
if (index + size > stream_size(stream)) sv_t sv = stream_sv_abs(stream);
return SV(NULL, 0); sv = sv_chop_left(sv, index);
return SV((char *)vec_data(&stream->pipe.cache) + index, size); sv = sv_truncate(sv, size);
return sv;
} }
default: default:
assert("Unreachable"); assert("Unreachable");