apfl/src/source_readers.c
Laria Carolin Chabowski 025fd61abd Add apfl_string_source_reader
A useful source reader implementation to pass in a source saved as an
in-memory string into the tokenizer.

This replaces the string_src_reader in the tokenizer_test and is even a bit
more flexible, by allowing any aplf_string_view as the source.
2021-12-16 22:49:41 +01:00

47 lines
892 B
C

#include <assert.h>
#include <string.h>
#include "apfl.h"
#include "internal.h"
struct string_source_reader {
struct apfl_string_view sv;
size_t off;
};
bool
apfl_string_source_reader(void *opaque, char *buf, size_t *len, bool need)
{
(void)need;
struct string_source_reader *ctx = opaque;
size_t maxlen = *len;
size_t remain_len = ctx->sv.len - ctx->off;
*len = maxlen < remain_len ? maxlen : remain_len;
memcpy(buf, ctx->sv.bytes + ctx->off, *len);
ctx->off += *len;
assert(ctx->off <= ctx->sv.len);
return true;
}
void *
apfl_string_source_reader_new(struct apfl_string_view sv)
{
struct string_source_reader *ctx = ALLOC(struct string_source_reader);
if (ctx == NULL) {
return NULL;
}
ctx->sv = sv;
ctx->off = 0;
return ctx;
}
void
apfl_string_source_reader_destroy(void *opaque)
{
free(opaque);
}