From 37c25a56195ebbe422358fcf537d631ef6445450 Mon Sep 17 00:00:00 2001 From: Markus Mittendrein Date: Tue, 2 Oct 2018 16:03:48 +0200 Subject: Add a more flexible enum to choose the memory management mode for setEntryData instead of the freeData boolean --- src/cc4group.c | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) (limited to 'src/cc4group.c') diff --git a/src/cc4group.c b/src/cc4group.c index 8fd57d5..98e9af0 100644 --- a/src/cc4group.c +++ b/src/cc4group.c @@ -90,6 +90,13 @@ struct CC4Group_t { } error; }; +typedef enum { + Take, + Copy, + Reference +} CC4Group_MemoryManagement; + + static const C4GroupEntryData* cc4group_getEntryByPath(const CC4Group* const this, const char* const entryPath); static const C4GroupEntryData* cc4group_getDirectoryByPath(CC4Group* const this, const char* const entryPath); static const C4GroupEntryData* cc4group_getFileByPath(CC4Group* const this, const char* const entryPath); @@ -1553,7 +1560,7 @@ static bool cc4group_createFile(CC4Group* const this, const char* const path) return true; } -static bool cc4group_setEntryData(CC4Group* const this, const char* const entryPath, const void* const data, size_t const size, bool const freeData) +static bool cc4group_setEntryData(CC4Group* const this, const char* const entryPath, const void* const data, size_t const size, int const memoryManagement) { assert(this); assert(entryPath); @@ -1569,11 +1576,24 @@ static bool cc4group_setEntryData(CC4Group* const this, const char* const entryP free(entry->data); } - if(data != NULL) + if(data != NULL && size != 0) { - entry->data = (void*)data; + if(memoryManagement == Copy) + { + entry->data = malloc(size); + if(entry->data == NULL) + { + SET_ERRNO_ERROR("malloc: allocating memory for copying the file data"); + return false; + } + memcpy(entry->data, data, size); + } + else + { + entry->data = (void*)data; + } entry->core.Size = size; - entry->freeData = freeData; + entry->freeData = memoryManagement != Reference; } else { @@ -1626,6 +1646,12 @@ CC4Group_API cc4group = { .Auto = cc4group_createTmpMemoryAuto }, + .MemoryManagement = { + .Take = Take, + .Copy = Copy, + .Reference = Reference + }, + .getErrorMessage = cc4group_getErrorMessage, .getErrorCode = cc4group_getErrorCode, .getErrorMethod = cc4group_getErrorMethod, -- cgit v1.2.3-54-g00ecf