diff --git a/include/alisp/stream.h b/include/alisp/stream.h index e79a11c..144c771 100644 --- a/include/alisp/stream.h +++ b/include/alisp/stream.h @@ -82,6 +82,9 @@ sv_t stream_till(stream_t *, const char *); // present. sv_t stream_while(stream_t *, const char *); +// Get the line and column of the stream at its current position. +void stream_line_col(stream_t *, u64 *line, u64 *col); + #endif /* Copyright (C) 2026 Aryadev Chavali diff --git a/src/stream.c b/src/stream.c index 787e4e1..b29b49c 100644 --- a/src/stream.c +++ b/src/stream.c @@ -8,6 +8,7 @@ #include #include +#include #include const char *stream_err_to_cstr(stream_err_t err) @@ -391,6 +392,41 @@ sv_t stream_while(stream_t *stream, const char *str) return stream_substr_abs(stream, current_position, size - 1); } +void stream_line_col(stream_t *stream, u64 *line, u64 *col) +{ + if (!stream || !line || !col) + return; + // Go through the cache, byte by byte. + char *cache = NULL; + u64 size = 0; + if (stream->type == STREAM_TYPE_STRING) + { + cache = stream->string.data; + size = stream->string.size; + } + else + { + cache = (char *)vec_data(&stream->pipe.cache); + size = stream->pipe.cache.size; + } + + *line = 1; + *col = 0; + for (u64 i = 0; i < size; ++i) + { + char c = cache[i]; + if (c == '\n') + { + *line += 1; + *col = 0; + } + else + { + *col += 1; + } + } +} + /* Copyright (C) 2025, 2026 Aryadev Chavali * This program is distributed in the hope that it will be useful, but WITHOUT