jsonfmt: Add max_size and max_depth options

This commit is contained in:
Yorhel 2025-01-29 15:05:48 +01:00
parent a85ff98914
commit 163a60b4ba
4 changed files with 101 additions and 59 deletions

View file

@ -4,24 +4,29 @@ typedef struct {
SV *sv;
char *cur;
char *end;
size_t maxlen;
} fustr;
static void fustr_init_(pTHX_ fustr *s, size_t prealloc) {
static void fustr_init_(pTHX_ fustr *s, size_t prealloc, size_t maxlen) {
if (prealloc > maxlen) prealloc = maxlen;
s->sv = sv_2mortal(newSV(prealloc));
SvPOK_only(s->sv);
s->cur = SvPVX(s->sv);
s->end = SvEND(s->sv);
s->maxlen = maxlen;
}
static void fustr_grow(pTHX_ fustr *s, size_t add) {
size_t off = s->cur - SvPVX(s->sv);
size_t newlen = 64;
add += off;
if (add > s->maxlen) croak("maximum string length exceeded");
/* Increment to next power of two; SvGROW's default strategy is slow */
while (newlen < add) newlen <<= 1;
if (newlen > s->maxlen) newlen = s->maxlen;
char *buf = SvGROW(s->sv, newlen);
s->cur = buf + off;
s->end = buf + SvLEN(s->sv);
s->end = buf + (SvLEN(s->sv) > s->maxlen ? s->maxlen : SvLEN(s->sv));
}
static inline void fustr_reserve_(pTHX_ fustr *s, size_t add) {
@ -50,7 +55,7 @@ static SV *fustr_done_(pTHX_ fustr *s) {
return s->sv;
}
#define fustr_init(a,b) fustr_init_(aTHX_ a,b)
#define fustr_init(a,b,c) fustr_init_(aTHX_ a,b,c)
#define fustr_reserve(a,b) fustr_reserve_(aTHX_ a,b)
#define fustr_write(a,b,c) fustr_write_(aTHX_ a,b,c)
#define fustr_write_buf(a,b) fustr_write_buf_(aTHX_ a,b)