From a0c01b8ab019039094f036a287db6cfdbe9cdca6 Mon Sep 17 00:00:00 2001 From: sanine Date: Sun, 2 Jan 2022 01:25:07 -0600 Subject: implement markdown() function --- src/bindings.c | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/bindings.c (limited to 'src/bindings.c') diff --git a/src/bindings.c b/src/bindings.c new file mode 100644 index 0000000..235e2df --- /dev/null +++ b/src/bindings.c @@ -0,0 +1,66 @@ +#include +#include +#include + +#include "honeysuckle.h" +#include "md4c-html.h" +#include "bindings.h" + +struct concat_buffer { + char *buf; + size_t size; + int index; + bool ok; +}; + +static void md_callback(const MD_CHAR *html, MD_SIZE size, void *data) +{ + struct concat_buffer *d = data; + + if (!d->ok) + return; + + if (d->index + size >= d->size) { + char *new_buf = realloc(d->buf, d->size * 2); + if (new_buf == NULL) { + // failed to allocate memory, abort! + d->ok = false; + return; + } + + d->buf = new_buf; + d->size *= 2; + } + + memcpy((d->buf) + d->index, html, size); + d->index += size; +} + +int markdown(lua_State *L) +{ + char *markdown_buffer; + hs_parse_args(L, hs_str(markdown_buffer)); + size_t len = strlen(markdown_buffer); + + unsigned int md_flags = MD_FLAG_TABLES | MD_FLAG_STRIKETHROUGH | MD_FLAG_UNDERLINE; + + struct concat_buffer data; + data.buf = malloc(128 * sizeof(char)); + data.size = 128 * sizeof(char); + data.index = 0; + data.ok = true; + + // fill out the buffer + int error = md_html(markdown_buffer, len, md_callback, &data, md_flags, 0); + if (error) + hs_throw_error(L, "markdown parsing failed!"); + + if (data.ok == false) + hs_throw_error(L, "encountered error (re)allocating html buffer memory!"); + + lua_pushstring(L, data.buf); + + free(data.buf); + + return 1; +} -- cgit v1.2.1