forked from WHC/Hermit
Vendored sashidown, OpenAI-compatible env (OPENAI_*), and bootstrap scripts. Co-authored-by: Cursor <cursoragent@cursor.com>
97 lines
2.5 KiB
C
97 lines
2.5 KiB
C
#include "sashidown.h"
|
|
#include "line_index.h"
|
|
#include "fsm.h"
|
|
#include "render.h"
|
|
#include "render_ansi.h"
|
|
#include "render_json.h"
|
|
#include <string.h>
|
|
|
|
int sashidown_parse(const char *input, size_t len,
|
|
char *output, size_t cap, size_t *out_len)
|
|
{
|
|
if (!input || !output || cap == 0)
|
|
return -1;
|
|
|
|
LINE_INDEX_STACK(ix);
|
|
line_index_build(input, len, &ix);
|
|
|
|
sashidown_ctx_t ctx = {
|
|
.input = input,
|
|
.input_len = len,
|
|
.output = output,
|
|
.output_cap = cap,
|
|
.output_len = 0,
|
|
.write_ptr = NULL,
|
|
.write_end = NULL,
|
|
.line_ix = &ix,
|
|
.overflow = 0,
|
|
};
|
|
|
|
if (sashidown_render(&ctx, input, len) != 0) {
|
|
fsm_write_end(&ctx);
|
|
return -1;
|
|
}
|
|
|
|
if (ctx.overflow || ctx.output_len + 1 > cap)
|
|
return -1;
|
|
|
|
output[ctx.output_len] = '\0';
|
|
if (out_len)
|
|
*out_len = ctx.output_len;
|
|
return 0;
|
|
}
|
|
|
|
static int convert_with_render(const char *input, size_t len,
|
|
char *output, size_t cap, size_t *out_len,
|
|
int (*render_fn)(sashidown_ctx_t *, const char *, size_t))
|
|
{
|
|
if (!input || !output || cap == 0)
|
|
return -1;
|
|
|
|
LINE_INDEX_STACK(ix);
|
|
line_index_build(input, len, &ix);
|
|
|
|
sashidown_ctx_t ctx = {
|
|
.input = input,
|
|
.input_len = len,
|
|
.output = output,
|
|
.output_cap = cap,
|
|
.output_len = 0,
|
|
.write_ptr = NULL,
|
|
.write_end = NULL,
|
|
.line_ix = &ix,
|
|
.overflow = 0,
|
|
};
|
|
|
|
if (render_fn(&ctx, input, len) != 0) {
|
|
fsm_write_end(&ctx);
|
|
return -1;
|
|
}
|
|
|
|
if (ctx.overflow || ctx.output_len + 1 > cap)
|
|
return -1;
|
|
|
|
output[ctx.output_len] = '\0';
|
|
if (out_len)
|
|
*out_len = ctx.output_len;
|
|
return 0;
|
|
}
|
|
|
|
int sashidown_convert(const char *input, size_t len,
|
|
char *output, size_t cap, size_t *out_len,
|
|
sashidown_format_t format)
|
|
{
|
|
switch (format) {
|
|
case SASHIDOWN_FMT_HTML:
|
|
return sashidown_parse(input, len, output, cap, out_len);
|
|
case SASHIDOWN_FMT_ANSI:
|
|
return convert_with_render(input, len, output, cap, out_len, sashidown_render_ansi);
|
|
case SASHIDOWN_FMT_ANSI_PLAIN:
|
|
return convert_with_render(input, len, output, cap, out_len, sashidown_render_ansi_plain);
|
|
case SASHIDOWN_FMT_JSON:
|
|
return convert_with_render(input, len, output, cap, out_len, sashidown_render_json);
|
|
default:
|
|
return -1;
|
|
}
|
|
}
|