stream: stream_line_col: get the line/column of stream currently
Best part is that this should only use cached data, so no chunking required.
This commit is contained in:
@@ -82,6 +82,9 @@ sv_t stream_till(stream_t *, const char *);
|
|||||||
// present.
|
// present.
|
||||||
sv_t stream_while(stream_t *, const char *);
|
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
|
#endif
|
||||||
|
|
||||||
/* Copyright (C) 2026 Aryadev Chavali
|
/* Copyright (C) 2026 Aryadev Chavali
|
||||||
|
|||||||
36
src/stream.c
36
src/stream.c
@@ -8,6 +8,7 @@
|
|||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
|
|
||||||
|
#include <alisp/base.h>
|
||||||
#include <alisp/stream.h>
|
#include <alisp/stream.h>
|
||||||
|
|
||||||
const char *stream_err_to_cstr(stream_err_t err)
|
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);
|
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
|
/* Copyright (C) 2025, 2026 Aryadev Chavali
|
||||||
|
|
||||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
|||||||
Reference in New Issue
Block a user