memory_arena
Loading...
Searching...
No Matches
arena_io.c
Go to the documentation of this file.
1
84#include "arena_io.h"
85#include "arena_debug.h"
86#include <stdio.h>
87#include <string.h>
88
161bool arena_save_to_file(const t_arena* arena, const char* path)
162{
163 if (!arena || !path)
164 return false;
165
166 if (!atomic_load_explicit(&arena->owns_buffer, memory_order_acquire))
167 return false;
168
169 ARENA_LOCK((t_arena*) arena);
170 size_t used = arena->offset;
171 const void* buf = arena->buffer;
172 ARENA_UNLOCK((t_arena*) arena);
173
174 t_arena_snapshot_header header = {.magic = ARENA_SNAPSHOT_MAGIC, .version = ARENA_SNAPSHOT_VERSION, .used = used};
175
176 FILE* f = fopen(path, "wb");
177 if (!f)
178 return false;
179
180 bool ok = fwrite(&header, sizeof(header), 1, f) == 1 && fwrite(buf, 1, used, f) == used;
181
182 fclose(f);
183 return ok;
184}
185
255bool arena_load_from_file(t_arena* arena, const char* path)
256{
257 if (!arena || !path)
258 return false;
259
260 if (!atomic_load_explicit(&arena->owns_buffer, memory_order_acquire))
261 return false;
262
263 FILE* f = fopen(path, "rb");
264 if (!f)
265 return false;
266
267 t_arena_snapshot_header header;
268 bool ok = fread(&header, sizeof(header), 1, f) == 1 && strncmp(header.magic, ARENA_SNAPSHOT_MAGIC, 9) == 0 &&
269 header.version == ARENA_SNAPSHOT_VERSION && header.used <= arena->size &&
270 fread(arena->buffer, 1, header.used, f) == header.used;
271
272 if (ok)
273 arena->offset = header.used;
274
275 fclose(f);
276 return ok;
277}
Debugging utilities and hooks for the arena memory allocator.
#define ARENA_UNLOCK(arena)
#define ARENA_LOCK(arena)
Acquire the mutex lock if thread safety is enabled.
bool arena_save_to_file(const t_arena *arena, const char *path)
Save the current contents of an arena to a file.
Definition arena_io.c:161
bool arena_load_from_file(t_arena *arena, const char *path)
Load arena contents from a snapshot file.
Definition arena_io.c:255
Arena snapshot input/output operations (save/load).
#define ARENA_SNAPSHOT_VERSION
Version number of the snapshot file format.
Definition arena_io.h:37
size_t used
Number of bytes used in the arena buffer.
Definition arena_io.h:2
#define ARENA_SNAPSHOT_MAGIC
Magic string identifying a valid arena snapshot file.
Definition arena_io.h:34
The main memory arena structure used for fast allocation.