1
#include "ArrayWriter.h"
4
struct ArrayWriter_context {
11
static int write(void* toWrite, size_t length, struct Writer* writer);
12
static uint64_t bytesWritten(struct Writer* writer);
14
/** @see ArrayWriter.h */
15
struct Writer* ArrayWriter_new(void* writeToBuffer,
17
struct MemAllocator* allocator)
19
struct Writer* writer =
20
allocator->calloc(sizeof(struct Writer), 1, allocator);
21
struct ArrayWriter_context* context =
22
allocator->calloc(sizeof(struct ArrayWriter_context), 1, allocator);
24
if (context == NULL || writer == NULL) {
28
context->beginPointer = (char*) writeToBuffer;
29
context->pointer = (char*) writeToBuffer;
30
context->endPointer = (char*) writeToBuffer + length;
32
struct Writer localWriter = {
35
.bytesWritten = bytesWritten
37
memcpy(writer, &localWriter, sizeof(struct Writer));
42
/** @see Writer->write() */
43
static int write(void* toWrite, size_t length, struct Writer* writer)
45
struct ArrayWriter_context* context =
46
(struct ArrayWriter_context*) writer->context;
48
/* If there was a previous failure then don't allow any more writing. */
49
if (context->returnCode != 0) {
50
return context->returnCode;
53
/* Prove that it doesn't run off the end of the buffer or roll over. */
54
if (context->pointer + length >= context->endPointer
55
|| context->pointer + length < context->pointer)
57
context->returnCode = -1;
61
memcpy(context->pointer, toWrite, length);
62
context->pointer += length;
67
static uint64_t bytesWritten(struct Writer* writer)
69
struct ArrayWriter_context* context =
70
(struct ArrayWriter_context*) writer->context;
72
return context->pointer - context->beginPointer;