From a24e8116cca13337153f217bf595dd3ff63cffcb Mon Sep 17 00:00:00 2001 From: DeaDDooMER Date: Wed, 7 Apr 2021 16:41:52 +0300 Subject: [PATCH] streams: new method: getlen --- src/common/files.c | 17 +++++++++++++++++ src/common/streams.c | 4 ++++ src/common/streams.h | 7 +++++-- 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/common/files.c b/src/common/files.c index 792df2d..8961c03 100644 --- a/src/common/files.c +++ b/src/common/files.c @@ -22,6 +22,21 @@ static void FILE_Stream_SetPos (Stream *r, long pos) { assert(res == 0); // fail } +static long FILE_Stream_GetLen (Stream *r) { + FILE_Stream *rd = (FILE_Stream*)r; + assert(rd != NULL); + assert(rd->fp != NULL); + long pos = ftell(rd->fp); + assert(pos != -1); // fail get cur pos + int res = fseek(rd->fp, 0, SEEK_END); + assert(res == 0); // fail jump to end + long len = ftell(rd->fp); + res = fseek(rd->fp, pos, SEEK_SET); + assert(res == 0); // fail return + assert(len != -1); // fail get length + return len; +} + static void FILE_Stream_Read (Stream *r, void *data, size_t size, size_t n) { FILE_Stream *rd = (FILE_Stream*)r; assert(rd != NULL); @@ -43,6 +58,7 @@ void FILE_Assign (FILE_Stream *r, FILE *fp) { assert(fp != NULL); r->base.getpos = FILE_Stream_GetPos; r->base.setpos = FILE_Stream_SetPos; + r->base.getlen = FILE_Stream_GetLen; r->base.read = FILE_Stream_Read; r->base.write = FILE_Stream_Write; r->fp = fp; @@ -65,6 +81,7 @@ void FILE_Close (FILE_Stream *r) { } r->base.getpos = NULL; r->base.setpos = NULL; + r->base.getlen = NULL; r->base.read = NULL; r->base.write = NULL; r->fp = NULL; diff --git a/src/common/streams.c b/src/common/streams.c index 76edaab..685ace1 100644 --- a/src/common/streams.c +++ b/src/common/streams.c @@ -12,6 +12,10 @@ void stream_setpos (Stream *s, long pos) { s->setpos(s, pos); } +long stream_getlen (Stream *s) { + return s->getlen(s); +} + void stream_read (void *data, size_t size, size_t n, Stream *r) { r->read(r, data, size, n); } diff --git a/src/common/streams.h b/src/common/streams.h index e40427f..e0a9dd8 100644 --- a/src/common/streams.h +++ b/src/common/streams.h @@ -7,8 +7,9 @@ typedef struct Stream Stream; struct Stream { - long (*getpos)(Stream *r); - void (*setpos)(Stream *r, long pos); + long (*getpos)(Stream *rw); + void (*setpos)(Stream *rw, long pos); + long (*getlen)(Stream *rw); void (*read)(Stream *r, void *data, size_t size, size_t n); void (*write)(Stream *w, const void *data, size_t size, size_t n); }; @@ -16,6 +17,8 @@ struct Stream { long stream_getpos (Stream *s); void stream_setpos (Stream *s, long pos); +long stream_getlen (Stream *s); + void stream_read (void *data, size_t size, size_t n, Stream *r); int8_t stream_read8 (Stream *r); int16_t stream_read16 (Stream *r); -- 2.29.2