changeset 693:a622d21833e1

Implement fopen() in mem ioctx, and simplistic read-only/write flag support.
author Matti Hamalainen <ccr@tnsp.org>
date Mon, 09 Mar 2020 18:54:37 +0200
parents ea6bcbfb9d18
children 0fc5ddaccc57
files th_ioctx.h th_ioctx_mem.c
diffstat 2 files changed, 44 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/th_ioctx.h	Mon Mar 09 17:59:06 2020 +0200
+++ b/th_ioctx.h	Mon Mar 09 18:54:37 2020 +0200
@@ -49,6 +49,7 @@
     size_t minAlloc;    ///< Minimum allocation increase (0 = default)
     off_t  memOffset;   ///< Current offset in data
     uint8_t *memData;   ///< Pointer to data
+    BOOL   memWrite;    ///< TRUE = memory can be written to / expanded etc. FALSE = no
 
     // Message functions
     void (*error)(struct th_ioctx *ctx, const int err, const char *msg);
--- a/th_ioctx_mem.c	Mon Mar 09 17:59:06 2020 +0200
+++ b/th_ioctx_mem.c	Mon Mar 09 18:54:37 2020 +0200
@@ -8,10 +8,52 @@
 #include "th_ioctx.h"
 
 
+static int th_mem_fopen(th_ioctx *ctx)
+{
+    if (ctx->mode == NULL)
+        return THERR_NULLPTR;
+
+    // Setup some things based on the mode string
+    switch (ctx->mode[0])
+    {
+        case 'a':
+            // Append
+            ctx->memWrite = TRUE;
+            ctx->memOffset = ctx->memSize;
+            break;
+
+        case 'r':
+            // Read or read-write
+            ctx->memWrite = ctx->mode[1] == '+';
+            ctx->memOffset = 0;
+            break;
+
+        case 'w':
+            // Write, so truncate size
+            ctx->memOffset = 0;
+            ctx->memSize = 0;
+            ctx->memWrite = TRUE;
+            break;
+
+        default:
+            return THERR_INVALID_ARGS;
+    }
+
+    return THERR_OK;
+}
+
+
 static BOOL th_mem_realloc(th_ioctx *ctx, const size_t newSize)
 {
     size_t grow;
 
+    // Check write flag
+    if (!ctx->memWrite)
+    {
+        ctx->status = THERR_FWRITE;
+        return FALSE;
+    }
+
     // Check against max size
     if (ctx->maxSize > 0 && newSize > ctx->maxSize)
     {
@@ -179,7 +221,7 @@
 {
     "MemIO",
 
-    NULL,
+    th_mem_fopen,
     NULL,
 
     th_mem_freset,