changeset 477:96d137a6b392

Improve ioctx API. This breaks backwards compatibility of th_io_fopen().
author Matti Hamalainen <ccr@tnsp.org>
date Mon, 09 Jul 2018 08:06:45 +0300
parents 61fed1286780
children b1e80180818a
files th_ioctx.c th_ioctx.h
diffstat 2 files changed, 24 insertions(+), 15 deletions(-) [+]
line wrap: on
line diff
--- a/th_ioctx.c	Mon Jul 09 07:29:33 2018 +0300
+++ b/th_ioctx.c	Mon Jul 09 08:06:45 2018 +0300
@@ -17,7 +17,7 @@
 }
 
 
-th_ioctx *th_io_new(const th_ioctx_ops *fops, const char *filename)
+th_ioctx * th_io_new(const th_ioctx_ops *fops, const char *filename)
 {
     th_ioctx *ctx = th_malloc0(sizeof(th_ioctx));
     if (ctx == NULL)
@@ -25,8 +25,14 @@
 
     ctx->fops = fops;
     ctx->filename = th_strdup(filename);
+    if (filename != NULL && ctx->filename == NULL)
+        goto err;
 
     return ctx;
+
+err:
+    th_io_free(ctx);
+    return NULL;
 }
 
 
@@ -44,19 +50,23 @@
 }
 
 
-th_ioctx * th_io_fopen(const th_ioctx_ops *fops, const char *filename, const char *mode)
+int th_io_fopen(th_ioctx **pctx, const th_ioctx_ops *fops, const char *filename, const char *mode)
 {
-    th_ioctx *ctx = th_io_new(fops, filename);
-    if (ctx == NULL)
-        return NULL;
+    th_ioctx *ctx;
+    int res;
+
+    if ((*pctx = ctx = th_io_new(fops, filename)) == NULL)
+        return THERR_MALLOC;
 
-    if (th_io_open(ctx, mode) != THERR_OK)
-    {
-        th_io_free(ctx);
-        return NULL;
-    }
+    if ((res = th_io_open(ctx, mode)) != THERR_OK)
+        goto err;
+
+    return THERR_OK;
 
-    return ctx;
+err:
+    th_io_free(ctx);
+    *pctx = NULL;
+    return res;
 }
 
 
@@ -495,4 +505,3 @@
     th_stdio_fputs,
     th_stdio_vfprintf,
 };
-
--- a/th_ioctx.h	Mon Jul 09 07:29:33 2018 +0300
+++ b/th_ioctx.h	Mon Jul 09 08:06:45 2018 +0300
@@ -35,8 +35,8 @@
     int status;         ///< Status
     size_t line;        ///< Line number
 
-    void (*error)(struct th_ioctx *, const int err, const char *msg);
-    void (*msg)(struct th_ioctx *, const int level, const char *msg);
+    void (*error)(struct th_ioctx *ctx, const int err, const char *msg);
+    void (*msg)(struct th_ioctx *ctx, const int level, const char *msg);
 
     const struct th_ioctx_ops *fops; ///< Pointer to I/O ops struct to be used with this context
 } th_ioctx;
@@ -79,7 +79,7 @@
 //
 th_ioctx *   th_io_new(const th_ioctx_ops *fops, const char *filename);
 int          th_io_open(th_ioctx *ctx, const char *mode);
-th_ioctx *   th_io_fopen(const th_ioctx_ops *fops, const char *filename, const char *mode);
+int          th_io_fopen(th_ioctx **pctx, const th_ioctx_ops *fops, const char *filename, const char *mode);
 void         th_io_close(th_ioctx *ctx);
 void         th_io_free(th_ioctx *ctx);