From 514b9f1c5f39a49c8944df4ad36c7707df96633d Mon Sep 17 00:00:00 2001 From: Max Wash Date: Wed, 30 Jul 2025 17:49:56 +0100 Subject: [PATCH] core: stream: add function to open a b_stream from a FILE pointer --- core/include/blue/core/stream.h | 3 +++ core/stream.c | 45 +++++++++++++++++---------------- 2 files changed, 26 insertions(+), 22 deletions(-) diff --git a/core/include/blue/core/stream.h b/core/include/blue/core/stream.h index a6881c3..cb59a0e 100644 --- a/core/include/blue/core/stream.h +++ b/core/include/blue/core/stream.h @@ -4,6 +4,7 @@ #include #include #include +#include #define b_stdin (z__b_stream_get_stdin()) #define b_stdout (z__b_stream_get_stdout()) @@ -64,6 +65,8 @@ BLUE_API b_status b_stream_pipeline_init( void *p, size_t len, b_stream_pipeline *out); BLUE_API b_status b_stream_pipeline_destroy(b_stream_pipeline *pipeline); +BLUE_API b_stream *b_stream_open_fp(FILE *fp); + BLUE_API b_status b_stream_close(b_stream *stream); BLUE_API b_status b_stream_reserve(b_stream *stream, size_t len); BLUE_API b_status b_stream_seek( diff --git a/core/stream.c b/core/stream.c index ba9f610..80df120 100644 --- a/core/stream.c +++ b/core/stream.c @@ -13,21 +13,12 @@ static b_status stdio_read( struct b_stream *stream, unsigned char *out, size_t max, size_t *nr_read) { FILE *fp = stream->s_ptr; - size_t count = 0; enum b_status status = B_SUCCESS; - for (size_t i = 0; i < max; i++) { - int c = fgetc(fp); - if (ferror(fp)) { - status = B_ERR_IO_FAILURE; - break; - } + size_t count = fread(out, 1, max, fp); - if (c == -1) { - break; - } - - out[count++] = c; + if (ferror(fp)) { + status = B_ERR_IO_FAILURE; } *nr_read = count; @@ -40,17 +31,10 @@ static b_status stdio_write( { FILE *fp = stream->s_ptr; enum b_status status = B_SUCCESS; - size_t w = 0; + size_t w = fwrite(data, 1, count, fp); - for (size_t i = 0; i < count; i++) { - fputc(data[i], fp); - - if (ferror(fp)) { - status = B_ERR_IO_FAILURE; - break; - } - - w++; + if (ferror(fp)) { + status = B_ERR_IO_FAILURE; } *nr_written = w; @@ -141,6 +125,23 @@ enum b_status b_stream_pipeline_destroy(struct b_stream_pipeline *pipeline) return B_SUCCESS; } +struct b_stream *b_stream_open_fp(FILE *fp) +{ + struct b_stream *stream = malloc(sizeof *stream); + if (!stream) { + return NULL; + } + + memset(stream, 0x0, sizeof *stream); + + stream->s_mode = B_STREAM_READ | B_STREAM_WRITE; + stream->s_ptr = fp; + stream->s_read = stdio_read; + stream->s_write = stdio_write; + + return stream; +} + enum b_status b_stream_close(b_stream *stream) { if (stream->s_istack) {