From 67392d12e6545a3d9537449e91f268e598a62f12 Mon Sep 17 00:00:00 2001 From: Max Wash Date: Thu, 31 Jul 2025 11:13:40 +0100 Subject: [PATCH] core: stream: replaced cached cursor counter with a tell() function callback --- core/include/blue/core/stream.h | 1 + core/stream.c | 28 +++++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/core/include/blue/core/stream.h b/core/include/blue/core/stream.h index e7c5d5c..9393a54 100644 --- a/core/include/blue/core/stream.h +++ b/core/include/blue/core/stream.h @@ -45,6 +45,7 @@ typedef struct b_stream { b_status (*s_close)(struct b_stream *); b_status (*s_seek)(struct b_stream *, long long, b_stream_seek_origin); + b_status (*s_tell)(const struct b_stream *, size_t *); b_status (*s_getc)(struct b_stream *, int *); b_status (*s_read)(struct b_stream *, unsigned char *, size_t, size_t *); b_status (*s_write)( diff --git a/core/stream.c b/core/stream.c index 536642e..dee1ba3 100644 --- a/core/stream.c +++ b/core/stream.c @@ -68,23 +68,38 @@ static enum b_status stdio_seek( return B_SUCCESS; } +static enum b_status stdio_tell(const struct b_stream *stream, size_t *cursor) +{ + FILE *fp = stream->s_ptr; + long pos = ftell(fp); + if (pos == -1L) { + return B_ERR_NOT_SUPPORTED; + } + + *cursor = (size_t)pos; + return B_SUCCESS; +} + static struct b_stream stdio[] = { [IDX_STDIN] = { .s_mode = B_STREAM_READ, .s_read = stdio_read, .s_seek = stdio_seek, + .s_tell = stdio_tell, .s_ptr = NULL, /* set to stdin (stdio.h) at runtime */ }, [IDX_STDOUT] = { .s_mode = B_STREAM_WRITE, .s_write = stdio_write, .s_seek = stdio_seek, + .s_tell = stdio_tell, .s_ptr = NULL, /* set to stdout (stdio.h) at runtime */ }, [IDX_STDERR] = { .s_mode = B_STREAM_WRITE, .s_write = stdio_write, .s_seek = stdio_seek, + .s_tell = stdio_tell, .s_ptr = NULL, /* set to stderr (stdio.h) at runtime */ }, }; @@ -169,6 +184,7 @@ struct b_stream *b_stream_open_fp(FILE *fp) stream->s_read = stdio_read; stream->s_write = stdio_write; stream->s_seek = stdio_seek; + stream->s_tell = stdio_tell; return stream; } @@ -211,7 +227,17 @@ enum b_status b_stream_seek( size_t b_stream_cursor(const b_stream *stream) { - return stream->s_cursor; + if (!stream->s_tell) { + return 0; + } + + size_t cursor = 0; + enum b_status status = stream->s_tell(stream, &cursor); + if (!B_OK(status)) { + return 0; + } + + return cursor; } enum b_status b_stream_push_indent(b_stream *stream, int indent)