file_raw_json.c

filter: Statementstmt 82.9% 393 / 474 Branchbran 57.7% 245 / 424 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 71.0% 638 / 898 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« yyjson.c ↑ Summary include/yyjson.h »
1 /*
2 * file_raw_json.c - File::Raw::JSON value-mapping + JSONL brace-balancer
3 */
4  
5 #include "file_raw_json.h"
6  
7 #include <string.h>
8 #include <stdio.h>
9 #include <math.h>
10 #include <limits.h>
11 #include "tie_orderedhash.h"
12  
13 /* ============================================================
14 * Defaults
15 * ============================================================ */
16  
17 void
18 357 json_options_defaults(json_options_t *o)
19 {
20 357 o->mode = JSON_MODE_DOCUMENT;
21 357 o->pretty = 0;
22 357 o->indent = 2;
23 357 o->sort_keys = 0;
24 357 o->canonical = 0;
25 357 o->utf8 = 1;
26 357 o->relaxed = 0;
27 357 o->allow_nonref = 1;
28 357 o->allow_nan_inf = 0;
29 357 o->ordered = 0;
30 357 o->max_depth = 512;
31 357 o->eol[0] = '\n';
32 357 o->eol[1] = '\0';
33 357 o->eol_len = 1;
34 357 }
35  
36 /* ============================================================
37 * JSONL brace-balancer
38 *
39 * Walk a buffer, find the byte range of the next balanced top-level
40 * JSON value (object or array). Skip leading whitespace; track string
41 * state and escape state; bail on truncation with NEED_MORE; bail on
42 * a non-opener with NO_OPENER.
43 *
44 * Equivalent to JSON::Lines's recursive Perl regex but:
45 * - O(n) byte scan with no backtracking
46 * - no PCRE2 dep
47 * - resumable: caller can retry with a longer buffer after NEED_MORE
48 * ============================================================ */
49  
50 jsonl_scan_t
51 6137 json_jsonl_next(const char *buf, STRLEN len,
52 STRLEN *out_start, STRLEN *out_end, STRLEN *next_pos)
53 {
54 6137 STRLEN i = 0;
55 6137 int depth = 0;
56 6137 int in_string = 0;
57 6137 int prev_backslash = 0;
58 char c;
59  
60 /* Skip ASCII whitespace before the value. */
61 6143 ▶ while (i < len) {
Branch: 1 branch
BranchTrueFalseTotal
while (i < len) { 6142 1 6143
62 6142 c = buf[i];
63 6142 ▶ if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break;
Branch: 4 branches
BranchTrueFalseTotal
if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break; 6139 3 6142
if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break; 6139 0 6139
if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break; 6136 3 6139
if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break; 6136 0 6136
64 6 i++;
65 }
66 6137 ▶ if (i >= len) {
Branch: 1 branch
BranchTrueFalseTotal
if (i >= len) { 1 6136 6137
67 1 *out_start = i;
68 1 *out_end = i;
69 1 *next_pos = i;
70 1 return JSONL_NO_OPENER; /* only whitespace */
71 }
72  
73 6136 c = buf[i];
74 6136 ▶ if (c != '[' && c != '{') {
Branch: 2 branches
BranchTrueFalseTotal
if (c != '[' && c != '{') { 6120 16 6136
if (c != '[' && c != '{') { 0 6120 6120
75 /* Non-opener: caller decides whether to skip or croak. */
76 0 *out_start = i;
77 0 *out_end = i;
78 0 *next_pos = i;
79 0 return JSONL_NO_OPENER;
80 }
81  
82 6136 *out_start = i;
83 6136 depth = 1;
84 6136 i++;
85  
86 265539 ▶ while (i < len) {
Branch: 1 branch
BranchTrueFalseTotal
while (i < len) { 265534 5 265539
87 265534 c = buf[i];
88 265534 ▶ if (in_string) {
Branch: 1 branch
BranchTrueFalseTotal
if (in_string) { 166139 99395 265534
89 166139 ▶ if (prev_backslash) {
Branch: 1 branch
BranchTrueFalseTotal
if (prev_backslash) { 8 166131 166139
90 8 prev_backslash = 0;
91 166131 ▶ } else if (c == '\\') {
Branch: 1 branch
BranchTrueFalseTotal
} else if (c == '\\') { 8 166123 166131
92 8 prev_backslash = 1;
93 166123 ▶ } else if (c == '"') {
Branch: 1 branch
BranchTrueFalseTotal
} else if (c == '"') { 26276 139847 166123
94 26276 in_string = 0;
95 }
96 166139 i++;
97 166139 continue;
98 }
99 99395 switch (c) {
100 2034 case '[': case '{':
101 2034 depth++;
102 2034 break;
103 8163 case ']': case '}':
104 8163 depth--;
105 8163 ▶ if (depth == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (depth == 0) { 6131 2032 8163
106 6131 *out_end = i + 1;
107 /* Skip trailing whitespace so next_pos points at the
108 * next value (or end of buffer). */
109 6131 i++;
110 12235 ▶ while (i < len) {
Branch: 1 branch
BranchTrueFalseTotal
while (i < len) { 12186 49 12235
111 12186 char w = buf[i];
112 12186 ▶ if (w != ' ' && w != '\t' && w != '\n' && w != '\r')
Branch: 4 branches
BranchTrueFalseTotal
if (w != ' ' && w != '\t' && w != '\n' && w != '\r') 12180 6 12186
if (w != ' ' && w != '\t' && w != '\n' && w != '\r') 12180 0 12180
if (w != ' ' && w != '\t' && w != '\n' && w != '\r') 6082 6098 12180
if (w != ' ' && w != '\t' && w != '\n' && w != '\r') 6082 0 6082
113 6082 break;
114 6104 i++;
115 }
116 6131 *next_pos = i;
117 6131 return JSONL_FOUND;
118 }
119 2032 break;
120 26279 case '"':
121 26279 in_string = 1;
122 26279 break;
123 62919 default:
124 /* literal data */
125 62919 break;
126 }
127 93264 i++;
128 }
129  
130 /* Hit EOF mid-value: caller must buffer the tail and retry. */
131 5 return JSONL_NEED_MORE;
132 }
133  
134 /* ============================================================
135 * Value mapping: yyjson_val -> Perl SV
136 *
137 * Recursive walker. Caller owns the returned SV (refcount 1).
138 * boolean_stash, if non-NULL, is the HV* of the class to bless
139 * true/false sentinels into.
140 * ============================================================ */
141  
142 static SV *make_bool_sv(pTHX_ int truth, HV *stash);
143 static HV *make_ordered_hv(pTHX);
144 static void ordered_hv_set(pTHX_ HV *hv, const char *key, STRLEN klen, SV *val);
145  
146 /* Internal recursive walker. Threads `depth` so we can enforce
147 * `max_depth` (the public option) without yyjson cooperation. */
148 static SV *
149 50205 sv_from_yyjson_d(pTHX_ yyjson_val *val, HV *boolean_stash,
150 int ordered, int depth, int max_depth)
151 {
152 yyjson_type t;
153 yyjson_subtype st;
154  
155 50205 ▶ if (!val) return newSV(0);
Branch: 1 branch
BranchTrueFalseTotal
if (!val) return newSV(0); 0 50205 50205
156  
157 50205 ▶ t = yyjson_get_type(val);
Branch: 1 branch
BranchTrueFalseTotal
t = yyjson_get_type(val); 50205 0 50205
158 50205 st = yyjson_get_subtype(val);
159  
160 /* Depth check fires when we *enter* a container, so primitives
161 * one level past the cap still parse - matches what callers
162 * intuitively expect from "max_depth = N nested levels". */
163 50205 ▶ if ((t == YYJSON_TYPE_ARR || t == YYJSON_TYPE_OBJ) && depth >= max_depth) {
Branch: 3 branches
BranchTrueFalseTotal
if ((t == YYJSON_TYPE_ARR || t == YYJSON_TYPE_OBJ) && depth >= max_depth) { 46720 3485 50205
if ((t == YYJSON_TYPE_ARR || t == YYJSON_TYPE_OBJ) && depth >= max_depth) { 9511 37209 46720
if ((t == YYJSON_TYPE_ARR || t == YYJSON_TYPE_OBJ) && depth >= max_depth) { 1 12995 12996
164 1 croak("File::Raw::JSON: max_depth (%d) exceeded during decode",
165 max_depth);
166 }
167  
168 50204 switch (t) {
169 21 case YYJSON_TYPE_NULL:
170 21 return newSV(0);
171  
172 24 ▶ case YYJSON_TYPE_BOOL: {
Branch: 1 branch
BranchTrueFalseTotal
case YYJSON_TYPE_BOOL: { 24 0 24
173 /* Inline fast path for the default boolean class (~99% of
174 * decodes): pointer-compare the stash and bump the pre-
175 * built singleton's refcount. Saves a function call to
176 * make_bool_sv per boolean. */
177 24 int truth = yyjson_get_bool(val);
178 24 ▶ if (boolean_stash == g_frj_default_stash) {
Branch: 1 branch
BranchTrueFalseTotal
if (boolean_stash == g_frj_default_stash) { 22 2 24
179 22 ▶ SV *s = truth ? g_frj_true_sv : g_frj_false_sv;
Branch: 1 branch
BranchTrueFalseTotal
SV *s = truth ? g_frj_true_sv : g_frj_false_sv; 13 9 22
180 22 ▶ if (s) {
Branch: 1 branch
BranchTrueFalseTotal
if (s) { 22 0 22
181 22 SvREFCNT_inc_simple_void_NN(s);
182 22 return s;
183 }
184 }
185 2 return make_bool_sv(aTHX_ truth, boolean_stash);
186 }
187  
188 13849 case YYJSON_TYPE_NUM:
189 13849 switch (st) {
190 /* yyjson parses integers as 64-bit whatever the perl is, so a
191 * value wider than this perl's IV/UV must fall back to an NV
192 * rather than be cast down: on a 32-bit-IV perl the cast
193 * silently truncates (9007199254740992 lands as 0). NV keeps
194 * the magnitude, and loses precision only past 2**53. */
195 7815 ▶ case YYJSON_SUBTYPE_UINT: {
Branch: 1 branch
BranchTrueFalseTotal
case YYJSON_SUBTYPE_UINT: { 7815 0 7815
196 7815 uint64_t u = yyjson_get_uint(val);
197 7815 ▶ if (u <= (uint64_t)IV_MAX) return newSViv((IV)u);
Branch: 1 branch
BranchTrueFalseTotal
if (u <= (uint64_t)IV_MAX) return newSViv((IV)u); 7813 2 7815
198 2 if (u <= (uint64_t)UV_MAX) return newSVuv((UV)u);
199 return newSVnv((NV)u);
200 }
201 4 ▶ case YYJSON_SUBTYPE_SINT: {
Branch: 1 branch
BranchTrueFalseTotal
case YYJSON_SUBTYPE_SINT: { 4 0 4
202 4 int64_t i = yyjson_get_sint(val);
203 if (i >= (int64_t)IV_MIN && i <= (int64_t)IV_MAX)
204 4 return newSViv((IV)i);
205 return newSVnv((NV)i);
206 }
207 6030 ▶ case YYJSON_SUBTYPE_REAL:
Branch: 1 branch
BranchTrueFalseTotal
case YYJSON_SUBTYPE_REAL: 6030 0 6030
208 6030 return newSVnv(yyjson_get_real(val));
209 0 default:
210 0 return newSV(0);
211 }
212  
213 23315 ▶ case YYJSON_TYPE_STR: {
Branch: 1 branch
BranchTrueFalseTotal
case YYJSON_TYPE_STR: { 23315 0 23315
214 23315 ▶ const char *s = yyjson_get_str(val);
Branch: 1 branch
BranchTrueFalseTotal
const char *s = yyjson_get_str(val); 23315 0 23315
215 23315 size_t n = yyjson_get_len(val);
216 23315 SV *out = newSVpvn(s, n);
217 23315 sv_utf8_decode(out);
218 23315 return out;
219 }
220  
221 3484 ▶ case YYJSON_TYPE_ARR: {
Branch: 1 branch
BranchTrueFalseTotal
case YYJSON_TYPE_ARR: { 3484 0 3484
222 3484 size_t n = yyjson_arr_size(val);
223 3484 AV *av = newAV();
224 /* Empty-array fast path: skip iter setup. */
225 3484 ▶ if (n == 0) return newRV_noinc((SV *)av);
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) return newRV_noinc((SV *)av); 26 3458 3484
226 {
227 yyjson_val *elem;
228 yyjson_arr_iter it;
229 3458 av_extend(av, (SSize_t)n);
230 yyjson_arr_iter_init(val, &it);
231 23049 ▶ while ((elem = yyjson_arr_iter_next(&it))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((elem = yyjson_arr_iter_next(&it))) { 16645 2946 19591
232 16645 av_push(av, sv_from_yyjson_d(aTHX_ elem, boolean_stash,
233 ordered, depth + 1,
234 max_depth));
235 }
236 }
237 2946 return newRV_noinc((SV *)av);
238 }
239  
240 9511 ▶ case YYJSON_TYPE_OBJ: {
Branch: 1 branch
BranchTrueFalseTotal
case YYJSON_TYPE_OBJ: { 9511 0 9511
241 /* Tied OrderedHash when ordered=>1 (each insert dispatches
242 * tie_oh_store so insertion order is preserved); plain HV
243 * with hv_store otherwise. */
244 9511 size_t n = yyjson_obj_size(val);
245 9511 ▶ HV *hv = ordered ? make_ordered_hv(aTHX) : newHV();
Branch: 1 branch
BranchTrueFalseTotal
HV *hv = ordered ? make_ordered_hv(aTHX) : newHV(); 85 9426 9511
246 /* Empty-object fast path. */
247 9511 ▶ if (n == 0) return newRV_noinc((SV *)hv);
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) return newRV_noinc((SV *)hv); 11 9500 9511
248 /* Pre-size the bucket table for the non-ordered case so
249 * hv_store doesn't trigger 2-3 splits + rehashes for any
250 * object with more than 8 keys. */
251 9500 ▶ if (!ordered && n > 8) hv_ksplit(hv, (IV)n);
Branch: 2 branches
BranchTrueFalseTotal
if (!ordered && n > 8) hv_ksplit(hv, (IV)n); 9416 84 9500
if (!ordered && n > 8) hv_ksplit(hv, (IV)n); 2 9414 9416
252 {
253 yyjson_val *key, *vv;
254 yyjson_obj_iter it;
255 yyjson_obj_iter_init(val, &it);
256 46290 ▶ while ((key = yyjson_obj_iter_next(&it))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((key = yyjson_obj_iter_next(&it))) { 27290 9500 36790
257 27290 ▶ vv = yyjson_obj_iter_get_val(key);
Branch: 1 branch
BranchTrueFalseTotal
vv = yyjson_obj_iter_get_val(key); 27290 0 27290
258 27290 ▶ const char *kp = yyjson_get_str(key);
Branch: 1 branch
BranchTrueFalseTotal
const char *kp = yyjson_get_str(key); 27290 0 27290
259 27290 size_t kl = yyjson_get_len(key);
260 27290 SV *child = sv_from_yyjson_d(aTHX_ vv, boolean_stash,
261 ordered, depth + 1,
262 max_depth);
263 27290 ▶ if (ordered) {
Branch: 1 branch
BranchTrueFalseTotal
if (ordered) { 414 26876 27290
264 414 ordered_hv_set(aTHX_ hv, kp, kl, child);
265 } else {
266 /* Negative klen tells hv_store the bytes are
267 * UTF-8 - so wide-char Perl literals (eg
268 * "\x{00e9}") match keys decoded from yyjson's
269 * native UTF-8 byte stream. */
270 26876 ▶ if (!hv_store(hv, kp, -(I32)kl, child, 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hv_store(hv, kp, -(I32)kl, child, 0)) { 0 26876 26876
271 0 SvREFCNT_dec(child);
272 }
273 }
274 }
275 }
276 9500 return newRV_noinc((SV *)hv);
277 }
278  
279 0 default:
280 0 return newSV(0);
281 }
282 }
283  
284 SV *
285 6270 json_sv_from_yyjson(pTHX_ yyjson_val *val, HV *boolean_stash,
286 int ordered, int max_depth)
287 {
288 6270 return sv_from_yyjson_d(aTHX_ val, boolean_stash, ordered, 0, max_depth);
289 }
290  
291 static HV *
292 85 make_ordered_hv(pTHX)
293 {
294 85 HV *hv = newHV();
295 85 SV *tied = tie_oh_new(aTHX); /* refcount=1, owned */
296 85 sv_magic((SV *)hv, tied, PERL_MAGIC_tied, NULL, 0);
297 85 SvREFCNT_dec(tied); /* sv_magic took its own */
298 85 return hv;
299 }
300  
301 /* Insert (key, val) into the tied HV. Detects our impl object and
302 * calls tie_oh_store directly (no method dispatch). For foreign tie
303 * classes - if a caller hands us an HV tied to something we don't
304 * recognise - fall back to call_method("STORE") so the contract still
305 * holds. */
306 static void
307 414 ordered_hv_set(pTHX_ HV *hv, const char *key, STRLEN klen, SV *val)
308 {
309 414 MAGIC *mg = mg_find((SV *)hv, PERL_MAGIC_tied);
310 SV *tied_obj;
311 414 dSP;
312  
313 414 ▶ if (!mg || !mg->mg_obj) {
Branch: 2 branches
BranchTrueFalseTotal
if (!mg || !mg->mg_obj) { 414 0 414
if (!mg || !mg->mg_obj) { 0 414 414
314 /* No tie magic. Plain hv_store is fine. */
315 0 ▶ if (!hv_store(hv, key, (I32)klen, val, 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hv_store(hv, key, (I32)klen, val, 0)) { 0 0 0
316 0 SvREFCNT_dec(val);
317 }
318 0 return;
319 }
320 414 tied_obj = mg->mg_obj;
321  
322 /* Fast path: our own class. tie_oh_store takes ownership of val,
323 * so no SvREFCNT bookkeeping needed. */
324 414 ▶ if (tie_oh_is_instance(aTHX_ tied_obj)) {
Branch: 1 branch
BranchTrueFalseTotal
if (tie_oh_is_instance(aTHX_ tied_obj)) { 414 0 414
325 414 tie_oh_store(aTHX_ tied_obj, key, klen, val);
326 414 return;
327 }
328  
329 /* Slow path: foreign tie class. Dispatch STORE via call_method,
330 * mortalising the value so it gets cleaned up after the call. */
331 0 ENTER; SAVETMPS;
332 0 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 0 0
333 0 ▶ XPUSHs(tied_obj);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(tied_obj); 0 0 0
334 0 ▶ XPUSHs(sv_2mortal(newSVpvn(key, klen)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSVpvn(key, klen))); 0 0 0
335 0 ▶ XPUSHs(sv_2mortal(val));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(val)); 0 0 0
336 0 PUTBACK;
337 0 call_method("STORE", G_DISCARD);
338 0 SPAGAIN;
339 0 PUTBACK;
340 0 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 0 0
341 }
342  
343 static SV *
344 2 make_bool_sv(pTHX_ int truth, HV *stash)
345 {
346 2 ▶ if (!stash) {
Branch: 1 branch
BranchTrueFalseTotal
if (!stash) { 0 2 2
347 0 ▶ return newSVsv(truth ? &PL_sv_yes : &PL_sv_no);
Branch: 1 branch
BranchTrueFalseTotal
return newSVsv(truth ? &PL_sv_yes : &PL_sv_no); 0 0 0
348 }
349 /* Hot path: default class returns the pre-built read-only
350 * singleton. Caller's SvREFCNT_dec balances our SvREFCNT_inc. */
351 2 ▶ if (g_frj_default_stash && stash == g_frj_default_stash) {
Branch: 2 branches
BranchTrueFalseTotal
if (g_frj_default_stash && stash == g_frj_default_stash) { 2 0 2
if (g_frj_default_stash && stash == g_frj_default_stash) { 0 2 2
352 0 ▶ SV *s = truth ? g_frj_true_sv : g_frj_false_sv;
Branch: 1 branch
BranchTrueFalseTotal
SV *s = truth ? g_frj_true_sv : g_frj_false_sv; 0 0 0
353 0 ▶ if (s) {
Branch: 1 branch
BranchTrueFalseTotal
if (s) { 0 0 0
354 0 ▶ SvREFCNT_inc_simple_void(s);
Branch: 1 branch
BranchTrueFalseTotal
SvREFCNT_inc_simple_void(s); 0 0 0
355 0 return s;
356 }
357 /* Singletons not initialised yet (eg called from BOOT order
358 * race). Fall through to per-call allocation. */
359 }
360 {
361 2 SV *inner = newSViv(truth ? 1 : 0);
362 2 SV *rv = newRV_noinc(inner);
363 2 sv_bless(rv, stash);
364 2 return rv;
365 }
366 }
367  
368 /* ============================================================
369 * Value mapping: Perl SV -> yyjson_mut_val (for encode)
370 * ============================================================ */
371  
372 static int sv_is_known_boolean_class(pTHX_ SV *sv);
373  
374 /* Cycle detection.
375 *
376 * Cycles can only form when a value points back to one of its
377 * ancestors on the current descent path. Sibling subtrees can
378 * never form cycles with each other - they're disjoint by the time
379 * we visit them. So we only need to track the *active path*, not
380 * everything ever visited. For real-world JSON-shaped data the
381 * path is typically 3-10 deep; a linear scan of a small SV* array
382 * is dramatically cheaper than HV insert / lookup / delete.
383 *
384 * If a structure exceeds VISITED_STACK_MAX (rare; we'd croak under
385 * default max_depth=512 long before then), we fall back to an HV
386 * for the overflow. Combined with the inline stack the worst case
387 * stays correct without slowing the common case. */
388 #define VISITED_STACK_MAX 64
389  
390 typedef struct {
391 SV *stack[VISITED_STACK_MAX];
392 int depth;
393 HV *overflow; /* lazy; created only when stack is full */
394 } visited_t;
395  
396 PERL_STATIC_INLINE int
397 6637 visited_seen(pTHX_ visited_t *v, SV *target)
398 {
399 int i;
400 /* Linear scan from top of stack (most recently entered first -
401 * cycles tend to point near where we just were). */
402 17825 ▶ for (i = v->depth - 1; i >= 0; i--) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = v->depth - 1; i >= 0; i--) { 11190 6635 17825
403 11190 ▶ if (v->stack[i] == target) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (v->stack[i] == target) return 1; 2 11188 11190
404 }
405 6635 ▶ if (v->overflow) {
Branch: 1 branch
BranchTrueFalseTotal
if (v->overflow) { 0 6635 6635
406 0 return hv_exists(v->overflow, (const char *)&target, sizeof(SV *));
407 }
408 6635 return 0;
409 }
410  
411 PERL_STATIC_INLINE void
412 6635 visited_enter(pTHX_ visited_t *v, SV *target)
413 {
414 6635 ▶ if (v->depth < VISITED_STACK_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (v->depth < VISITED_STACK_MAX) { 6635 0 6635
415 6635 v->stack[v->depth++] = target;
416 6635 return;
417 }
418 /* Stack full - spill to HV. */
419 0 ▶ if (!v->overflow) v->overflow = newHV();
Branch: 1 branch
BranchTrueFalseTotal
if (!v->overflow) v->overflow = newHV(); 0 0 0
420 0 SvREFCNT_inc_simple_void_NN(&PL_sv_undef);
421 0 ▶ if (!hv_store(v->overflow, (const char *)&target, sizeof(SV *),
Branch: 1 branch
BranchTrueFalseTotal
if (!hv_store(v->overflow, (const char *)&target, sizeof(SV *), 0 0 0
422 &PL_sv_undef, 0))
423 0 SvREFCNT_dec(&PL_sv_undef);
424 }
425  
426 PERL_STATIC_INLINE void
427 6633 visited_leave(pTHX_ visited_t *v, SV *target)
428 {
429 /* Stack is LIFO - the last visited_enter must match this leave.
430 * Defensive: walk back if not at top (shouldn't happen). */
431 6633 ▶ if (v->depth > 0 && v->stack[v->depth - 1] == target) {
Branch: 2 branches
BranchTrueFalseTotal
if (v->depth > 0 && v->stack[v->depth - 1] == target) { 6633 0 6633
if (v->depth > 0 && v->stack[v->depth - 1] == target) { 6633 0 6633
432 6633 v->depth--;
433 6633 return;
434 }
435 0 ▶ if (v->overflow) {
Branch: 1 branch
BranchTrueFalseTotal
if (v->overflow) { 0 0 0
436 0 hv_delete(v->overflow, (const char *)&target, sizeof(SV *),
437 G_DISCARD);
438 }
439 }
440  
441 static yyjson_mut_val *sv_to_yyjson_v(pTHX_ SV *sv, yyjson_mut_doc *doc,
442 const json_options_t *opts,
443 visited_t *visited);
444  
445 yyjson_mut_val *
446 1156 json_sv_to_yyjson(pTHX_ SV *sv, yyjson_mut_doc *doc,
447 const json_options_t *opts)
448 {
449 visited_t visited;
450 yyjson_mut_val *r;
451 1156 visited.depth = 0;
452 1156 visited.overflow = NULL;
453 1156 r = sv_to_yyjson_v(aTHX_ sv, doc, opts, &visited);
454 1151 ▶ if (visited.overflow) SvREFCNT_dec((SV *)visited.overflow);
Branch: 1 branch
BranchTrueFalseTotal
if (visited.overflow) SvREFCNT_dec((SV *)visited.overflow); 0 1151 1151
455 1151 return r;
456 }
457  
458 static yyjson_mut_val *
459 32631 sv_to_yyjson_v(pTHX_ SV *sv, yyjson_mut_doc *doc,
460 const json_options_t *opts, visited_t *visited)
461 {
462 PERL_UNUSED_ARG(opts);
463  
464 32646 ▶ if (!sv || !SvOK(sv)) return yyjson_mut_null(doc);
Branch: 2 branches
BranchTrueFalseTotal
if (!sv || !SvOK(sv)) return yyjson_mut_null(doc); 32631 0 32631
if (!sv || !SvOK(sv)) return yyjson_mut_null(doc); 15 32616 32631
465  
466 32616 ▶ if (SvROK(sv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvROK(sv)) { 6656 25960 32616
467 6656 SV *target = SvRV(sv);
468 6656 ▶ if (SvOBJECT(target) && sv_is_known_boolean_class(aTHX_ sv)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvOBJECT(target) && sv_is_known_boolean_class(aTHX_ sv)) { 16 6640 6656
if (SvOBJECT(target) && sv_is_known_boolean_class(aTHX_ sv)) { 14 2 16
469 14 int truth = SvTRUE(target) ? 1 : 0;
470 28 ▶ return yyjson_mut_bool(doc, truth);
Branch: 1 branch
BranchTrueFalseTotal
return yyjson_mut_bool(doc, truth); 14 0 14
471 }
472 6642 ▶ if (SvTYPE(target) == SVt_PVAV) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvTYPE(target) == SVt_PVAV) { 2229 4413 6642
473 2229 AV *av = (AV *)target;
474 yyjson_mut_val *arr;
475 SV **arr_ptr;
476 SSize_t i, n;
477 2229 ▶ if (visited_seen(aTHX_ visited, target)) {
Branch: 1 branch
BranchTrueFalseTotal
if (visited_seen(aTHX_ visited, target)) { 1 2228 2229
478 1 croak("File::Raw::JSON: circular reference detected "
479 "(array references itself)");
480 }
481 2228 visited_enter(aTHX_ visited, target);
482 2228 arr = yyjson_mut_arr(doc);
483 2228 n = av_len(av) + 1;
484 /* Direct AvARRAY access skips av_fetch's bounds + magic
485 * check per element. Holes (sparse arrays) come back as
486 * NULL pointers; we substitute &PL_sv_undef. */
487 2228 arr_ptr = AvARRAY(av);
488 17560 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 15333 2227 17560
489 15333 SV *ep = arr_ptr[i];
490 yyjson_mut_val *child =
491 15333 ▶ sv_to_yyjson_v(aTHX_ ep ? ep : &PL_sv_undef,
Branch: 1 branch
BranchTrueFalseTotal
sv_to_yyjson_v(aTHX_ ep ? ep : &PL_sv_undef, 15331 2 15333
492 doc, opts, visited);
493 yyjson_mut_arr_append(arr, child);
494 }
495 2227 visited_leave(aTHX_ visited, target);
496 2227 return arr;
497 }
498 4413 ▶ if (SvTYPE(target) == SVt_PVHV) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvTYPE(target) == SVt_PVHV) { 4408 5 4413
499 /* Three dispatches:
500 * - Tie::OrderedHash: walk via the public C ABI
501 * tie_oh_iter_* (no method dispatch).
502 * - Other tied HVs: walk via hv_iternext (which goes
503 * through tied FIRSTKEY/NEXTKEY) and dispatch FETCH
504 * per key via call_method.
505 * - Untied HVs: walk via hv_iternext + hv_iterval.
506 *
507 * sort_keys / canonical: collect (key, val) pairs first,
508 * sort, emit. Default: walk and emit in one pass - no
509 * collection buffer alloc. HvUSEDKEYS returns 0 for tied
510 * HVs (their bucket storage is empty), so we can't use it
511 * to pre-size or short-circuit; the live walks above
512 * handle tied HVs correctly. */
513 4408 HV *hv = (HV *)target;
514 yyjson_mut_val *obj;
515 HE *he;
516 MAGIC *tied_mg;
517 4408 ▶ int do_sort = opts->sort_keys || opts->canonical;
Branch: 2 branches
BranchTrueFalseTotal
int do_sort = opts->sort_keys || opts->canonical; 260 4148 4408
int do_sort = opts->sort_keys || opts->canonical; 19 241 260
518  
519 4408 ▶ if (visited_seen(aTHX_ visited, target)) {
Branch: 1 branch
BranchTrueFalseTotal
if (visited_seen(aTHX_ visited, target)) { 1 4407 4408
520 1 croak("File::Raw::JSON: circular reference detected "
521 "(hash references itself)");
522 }
523 4407 visited_enter(aTHX_ visited, target);
524 4407 obj = yyjson_mut_obj(doc);
525 4407 tied_mg = mg_find((SV *)hv, PERL_MAGIC_tied);
526  
527 4407 ▶ if (do_sort) {
Branch: 1 branch
BranchTrueFalseTotal
if (do_sort) { 4167 240 4407
528 /* Collect-sort-emit. Most JSON objects have <32
529 * keys; stack-allocate the buffers for that case to
530 * skip the malloc/free pair (significant when
531 * sort_keys is set on a large array of small
532 * objects - was the dominant cost on the
533 * sort_keys+pretty bench at medium size). */
534 #define FRJ_SORT_STACK_SIZE 32
535 SV *stack_keys[FRJ_SORT_STACK_SIZE];
536 SV *stack_vals[FRJ_SORT_STACK_SIZE];
537 4167 SV **keys_buf = stack_keys;
538 4167 SV **vals_buf = stack_vals;
539 4167 SSize_t count = 0;
540 4167 SSize_t cap = FRJ_SORT_STACK_SIZE;
541 4167 int on_heap = 0;
542 SSize_t i;
543  
544 #define FRJ_PUSH_PAIR(KSV, VSV) STMT_START { \
545 if (count >= cap) { \
546 SSize_t new_cap = cap * 2; \
547 if (on_heap) { \
548 Renew(keys_buf, new_cap, SV *); \
549 Renew(vals_buf, new_cap, SV *); \
550 } else { \
551 SV **nk, **nv; \
552 Newx(nk, new_cap, SV *); \
553 Newx(nv, new_cap, SV *); \
554 memcpy(nk, keys_buf, sizeof(SV *) * (size_t)count); \
555 memcpy(nv, vals_buf, sizeof(SV *) * (size_t)count); \
556 keys_buf = nk; \
557 vals_buf = nv; \
558 on_heap = 1; \
559 } \
560 cap = new_cap; \
561 } \
562 keys_buf[count] = (KSV); \
563 vals_buf[count] = (VSV); \
564 count++; \
565 } STMT_END
566  
567 4167 ▶ if (tied_mg && tied_mg->mg_obj
Branch: 2 branches
BranchTrueFalseTotal
if (tied_mg && tied_mg->mg_obj 5 4162 4167
if (tied_mg && tied_mg->mg_obj 5 0 5
568 5 ▶ && tie_oh_is_instance(aTHX_ tied_mg->mg_obj))
Branch: 1 branch
BranchTrueFalseTotal
&& tie_oh_is_instance(aTHX_ tied_mg->mg_obj)) 5 0 5
569 5 {
570 5 SV *self = tied_mg->mg_obj;
571 tie_oh_iter_t it;
572 const char *key;
573 STRLEN klen;
574 SV *vsv;
575 5 tie_oh_iter_init(aTHX_ self, &it);
576 18 ▶ while (tie_oh_iter_next(aTHX_ self, &it,
Branch: 1 branch
BranchTrueFalseTotal
while (tie_oh_iter_next(aTHX_ self, &it, 13 5 18
577 &key, &klen, &vsv)) {
578 13 SV *ksv = sv_2mortal(newSVpvn(key, klen));
579 13 ▶ FRJ_PUSH_PAIR(ksv, vsv);
Branch: 6 branches
BranchTrueFalseTotal
FRJ_PUSH_PAIR(ksv, vsv); 0 13 13
FRJ_PUSH_PAIR(ksv, vsv); 0 0 0
FRJ_PUSH_PAIR(ksv, vsv); 0 0 0
FRJ_PUSH_PAIR(ksv, vsv); 0 0 0
FRJ_PUSH_PAIR(ksv, vsv); 0 0 0
FRJ_PUSH_PAIR(ksv, vsv); 0 0 0
580 }
581 4162 ▶ } else if (tied_mg && tied_mg->mg_obj) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (tied_mg && tied_mg->mg_obj) { 0 4162 4162
} else if (tied_mg && tied_mg->mg_obj) { 0 0 0
582 0 hv_iterinit(hv);
583 0 ▶ while ((he = hv_iternext(hv))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(hv))) { 0 0 0
584 I32 klen;
585 0 const char *key = hv_iterkey(he, &klen);
586 SV *fetched, *copy, *ksv;
587 int rc;
588 0 dSP;
589 0 ENTER; SAVETMPS;
590 0 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 0 0
591 0 ▶ XPUSHs(tied_mg->mg_obj);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(tied_mg->mg_obj); 0 0 0
592 0 ▶ XPUSHs(sv_2mortal(newSVpvn(key, klen)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSVpvn(key, klen))); 0 0 0
593 0 PUTBACK;
594 0 rc = call_method("FETCH", G_SCALAR);
595 0 SPAGAIN;
596 0 ▶ fetched = rc > 0 ? POPs : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
fetched = rc > 0 ? POPs : &PL_sv_undef; 0 0 0
597 0 copy = newSVsv(fetched);
598 0 PUTBACK;
599 0 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 0 0
600 0 ksv = sv_2mortal(newSVpvn(key, klen));
601 0 ▶ FRJ_PUSH_PAIR(ksv, sv_2mortal(copy));
Branch: 6 branches
BranchTrueFalseTotal
FRJ_PUSH_PAIR(ksv, sv_2mortal(copy)); 0 0 0
FRJ_PUSH_PAIR(ksv, sv_2mortal(copy)); 0 0 0
FRJ_PUSH_PAIR(ksv, sv_2mortal(copy)); 0 0 0
FRJ_PUSH_PAIR(ksv, sv_2mortal(copy)); 0 0 0
FRJ_PUSH_PAIR(ksv, sv_2mortal(copy)); 0 0 0
FRJ_PUSH_PAIR(ksv, sv_2mortal(copy)); 0 0 0
602 }
603 } else {
604 /* Untied HV: HeVAL(he) is direct, no tie-magic
605 * re-check (hv_iterval would do that since it's
606 * the polymorphic accessor). */
607 4162 hv_iterinit(hv);
608 18563 ▶ while ((he = hv_iternext(hv))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(hv))) { 14401 4162 18563
609 14401 ▶ FRJ_PUSH_PAIR(hv_iterkeysv(he), HeVAL(he));
Branch: 6 branches
BranchTrueFalseTotal
FRJ_PUSH_PAIR(hv_iterkeysv(he), HeVAL(he)); 0 14401 14401
FRJ_PUSH_PAIR(hv_iterkeysv(he), HeVAL(he)); 0 0 0
FRJ_PUSH_PAIR(hv_iterkeysv(he), HeVAL(he)); 0 0 0
FRJ_PUSH_PAIR(hv_iterkeysv(he), HeVAL(he)); 0 0 0
FRJ_PUSH_PAIR(hv_iterkeysv(he), HeVAL(he)); 0 0 0
FRJ_PUSH_PAIR(hv_iterkeysv(he), HeVAL(he)); 0 0 0
610 }
611 }
612  
613 #undef FRJ_PUSH_PAIR
614  
615 /* Insertion sort: small n typical, no comparator
616 * indirection. */
617 {
618 SSize_t a, b;
619 14419 ▶ for (a = 1; a < count; a++) {
Branch: 1 branch
BranchTrueFalseTotal
for (a = 1; a < count; a++) { 10252 4167 14419
620 10252 SV *kcur = keys_buf[a];
621 10252 SV *vcur = vals_buf[a];
622 STRLEN clen;
623 10252 const char *cpv = SvPV(kcur, clen);
624 10252 b = a - 1;
625 21601 ▶ while (b >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
while (b >= 0) { 18190 3411 21601
626 STRLEN plen;
627 18190 const char *ppv = SvPV(keys_buf[b], plen);
628 18190 STRLEN cmplen = clen < plen ? clen : plen;
629 18190 int rc = memcmp(cpv, ppv, cmplen);
630 18190 ▶ if (rc < 0 || (rc == 0 && clen < plen)) {
Branch: 3 branches
BranchTrueFalseTotal
if (rc < 0 || (rc == 0 && clen < plen)) { 6841 11349 18190
if (rc < 0 || (rc == 0 && clen < plen)) { 2 6839 6841
if (rc < 0 || (rc == 0 && clen < plen)) { 0 2 2
631 11349 keys_buf[b + 1] = keys_buf[b];
632 11349 vals_buf[b + 1] = vals_buf[b];
633 11349 b--;
634 } else break;
635 }
636 10252 keys_buf[b + 1] = kcur;
637 10252 vals_buf[b + 1] = vcur;
638 }
639 }
640  
641 18581 ▶ for (i = 0; i < count; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < count; i++) { 14414 4167 18581
642 STRLEN klen;
643 14414 const char *kp = SvPV(keys_buf[i], klen);
644 14414 ▶ yyjson_mut_val *kval = yyjson_mut_strn(doc, kp, (size_t)klen);
Branch: 1 branch
BranchTrueFalseTotal
yyjson_mut_val *kval = yyjson_mut_strn(doc, kp, (size_t)klen); 14414 0 14414
645 14414 yyjson_mut_val *vval = sv_to_yyjson_v(aTHX_ vals_buf[i],
646 doc, opts, visited);
647 yyjson_mut_obj_add(obj, kval, vval);
648 }
649  
650 4167 ▶ if (on_heap) {
Branch: 1 branch
BranchTrueFalseTotal
if (on_heap) { 0 4167 4167
651 0 Safefree(keys_buf);
652 0 Safefree(vals_buf);
653 }
654 #undef FRJ_SORT_STACK_SIZE
655 }
656 240 ▶ else if (tied_mg && tied_mg->mg_obj
Branch: 2 branches
BranchTrueFalseTotal
else if (tied_mg && tied_mg->mg_obj 54 186 240
else if (tied_mg && tied_mg->mg_obj 54 0 54
657 54 ▶ && tie_oh_is_instance(aTHX_ tied_mg->mg_obj))
Branch: 1 branch
BranchTrueFalseTotal
&& tie_oh_is_instance(aTHX_ tied_mg->mg_obj)) 54 0 54
658 54 {
659 /* Single-pass: tie_oh_iter_* + emit. */
660 54 SV *self = tied_mg->mg_obj;
661 tie_oh_iter_t it;
662 const char *key;
663 STRLEN klen;
664 SV *vsv;
665 54 tie_oh_iter_init(aTHX_ self, &it);
666 387 ▶ while (tie_oh_iter_next(aTHX_ self, &it,
Branch: 1 branch
BranchTrueFalseTotal
while (tie_oh_iter_next(aTHX_ self, &it, 333 54 387
667 &key, &klen, &vsv)) {
668 333 ▶ yyjson_mut_val *kval = yyjson_mut_strn(
Branch: 1 branch
BranchTrueFalseTotal
yyjson_mut_val *kval = yyjson_mut_strn( 333 0 333
669 doc, key, (size_t)klen);
670 333 yyjson_mut_val *vval = sv_to_yyjson_v(
671 aTHX_ vsv, doc, opts, visited);
672 yyjson_mut_obj_add(obj, kval, vval);
673 }
674 }
675 186 ▶ else if (tied_mg && tied_mg->mg_obj) {
Branch: 2 branches
BranchTrueFalseTotal
else if (tied_mg && tied_mg->mg_obj) { 0 186 186
else if (tied_mg && tied_mg->mg_obj) { 0 0 0
676 /* Single-pass: hv_iternext + per-key call_method FETCH. */
677 0 hv_iterinit(hv);
678 0 ▶ while ((he = hv_iternext(hv))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(hv))) { 0 0 0
679 I32 klen;
680 0 const char *key = hv_iterkey(he, &klen);
681 SV *fetched, *copy, *vsv;
682 yyjson_mut_val *kval, *vval;
683 int rc;
684 0 dSP;
685 0 ENTER; SAVETMPS;
686 0 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 0 0
687 0 ▶ XPUSHs(tied_mg->mg_obj);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(tied_mg->mg_obj); 0 0 0
688 0 ▶ XPUSHs(sv_2mortal(newSVpvn(key, klen)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSVpvn(key, klen))); 0 0 0
689 0 PUTBACK;
690 0 rc = call_method("FETCH", G_SCALAR);
691 0 SPAGAIN;
692 0 ▶ fetched = rc > 0 ? POPs : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
fetched = rc > 0 ? POPs : &PL_sv_undef; 0 0 0
693 0 copy = newSVsv(fetched);
694 0 PUTBACK;
695 0 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 0 0
696 0 vsv = sv_2mortal(copy);
697  
698 0 ▶ kval = yyjson_mut_strn(doc, key, (size_t)klen);
Branch: 1 branch
BranchTrueFalseTotal
kval = yyjson_mut_strn(doc, key, (size_t)klen); 0 0 0
699 0 vval = sv_to_yyjson_v(aTHX_ vsv, doc, opts, visited);
700 yyjson_mut_obj_add(obj, kval, vval);
701 }
702 }
703 else {
704 /* Untied HV: HeVAL(he) is direct. hv_iterval is the
705 * tie-aware polymorphic accessor and would re-check
706 * magic per key; we already know we're not tied here. */
707 186 hv_iterinit(hv);
708 1580 ▶ while ((he = hv_iternext(hv))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(hv))) { 1395 185 1580
709 I32 klen;
710 1395 const char *key = hv_iterkey(he, &klen);
711 1395 ▶ yyjson_mut_val *kval = yyjson_mut_strn(
Branch: 1 branch
BranchTrueFalseTotal
yyjson_mut_val *kval = yyjson_mut_strn( 1395 0 1395
712 doc, key, (size_t)klen);
713 1395 yyjson_mut_val *vval = sv_to_yyjson_v(
714 aTHX_ HeVAL(he), doc, opts, visited);
715 yyjson_mut_obj_add(obj, kval, vval);
716 }
717 }
718  
719 4406 visited_leave(aTHX_ visited, target);
720 4406 return obj;
721 }
722 /* Reject things that have no sane JSON encoding. */
723 {
724 5 svtype tt = SvTYPE(target);
725 5 ▶ if (tt == SVt_PVCV) {
Branch: 1 branch
BranchTrueFalseTotal
if (tt == SVt_PVCV) { 1 4 5
726 1 croak("File::Raw::JSON: cannot encode CODE reference as JSON");
727 }
728 4 ▶ if (tt == SVt_PVGV) {
Branch: 1 branch
BranchTrueFalseTotal
if (tt == SVt_PVGV) { 1 3 4
729 1 croak("File::Raw::JSON: cannot encode GLOB reference as JSON");
730 }
731 /* SvRXOK is the portable regex check - handles SVt_REGEXP
732 * and the older magic-attached form. */
733 3 ▶ if (SvRXOK(sv) || SvRXOK(target)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvRXOK(sv) || SvRXOK(target)) { 2 1 3
if (SvRXOK(sv) || SvRXOK(target)) { 0 2 2
734 1 croak("File::Raw::JSON: cannot encode Regexp reference as JSON");
735 }
736 }
737 /* Non-blessed scalar refs are treated as JSON booleans by
738 * truthiness, matching JSON::XS / Cpanel::JSON::XS / JSON::PP:
739 * \1 -> true
740 * \0 -> false
741 * \"" -> false
742 * \"x" -> true
743 * Lets callers express booleans without loading a sentinel
744 * class. */
745 2 ▶ if (!SvOBJECT(target)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOBJECT(target)) { 2 0 2
746 4 ▶ return yyjson_mut_bool(doc, SvTRUE(target) ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
return yyjson_mut_bool(doc, SvTRUE(target) ? 1 : 0); 2 0 2
747 }
748 /* Blessed non-recognised refs (eg bless \1, 'My::Class' that
749 * isn't a known boolean class) fall through to SvPV which
750 * emits the stringified form ("My::Class=SCALAR(0x...)"). */
751 {
752 STRLEN len;
753 0 const char *s = SvPV(sv, len);
754 0 ▶ return yyjson_mut_strn(doc, s, (size_t)len);
Branch: 1 branch
BranchTrueFalseTotal
return yyjson_mut_strn(doc, s, (size_t)len); 0 0 0
755 }
756 }
757  
758 25960 ▶ if (SvIOK(sv) && !SvNOK(sv)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvIOK(sv) && !SvNOK(sv)) { 5690 20270 25960
if (SvIOK(sv) && !SvNOK(sv)) { 1690 4000 5690
759 1692 ▶ if (SvIsUV(sv)) return yyjson_mut_uint(doc, (uint64_t)SvUV(sv));
Branch: 1 branch
BranchTrueFalseTotal
if (SvIsUV(sv)) return yyjson_mut_uint(doc, (uint64_t)SvUV(sv)); 2 1688 1690
760 3376 return yyjson_mut_sint(doc, (int64_t)SvIV(sv));
761 }
762 24270 ▶ if (SvNOK(sv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvNOK(sv)) { 6019 18251 24270
763 12038 return yyjson_mut_real(doc, SvNV(sv));
764 }
765 {
766 STRLEN len;
767 18251 const char *s = SvPV(sv, len);
768 36502 ▶ return yyjson_mut_strn(doc, s, (size_t)len);
Branch: 1 branch
BranchTrueFalseTotal
return yyjson_mut_strn(doc, s, (size_t)len); 18251 0 18251
769 }
770 }
771  
772 /* Recognise known boolean sentinel classes.
773 *
774 * Hot path: pointer-compare against g_frj_default_stash (cached at
775 * BOOT for File::Raw::JSON::Boolean). ~99% of decoded booleans
776 * come back blessed into this class, so a single pointer comparison
777 * resolves them without touching the stash name. Foreign classes
778 * fall through to the HvNAME_get + strEQ chain. */
779 static int
780 16 sv_is_known_boolean_class(pTHX_ SV *sv)
781 {
782 HV *stash;
783 const char *name;
784 16 ▶ if (!SvROK(sv)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvROK(sv)) return 0; 0 16 16
785 16 ▶ if (!SvOBJECT(SvRV(sv))) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOBJECT(SvRV(sv))) return 0; 0 16 16
786 16 stash = SvSTASH(SvRV(sv));
787 16 ▶ if (!stash) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!stash) return 0; 0 16 16
788 /* Hot path: our default class. */
789 16 ▶ if (g_frj_default_stash && stash == g_frj_default_stash) return 1;
Branch: 2 branches
BranchTrueFalseTotal
if (g_frj_default_stash && stash == g_frj_default_stash) return 1; 16 0 16
if (g_frj_default_stash && stash == g_frj_default_stash) return 1; 12 4 16
790 /* Cold path: foreign boolean sentinels. */
791 4 ▶ name = HvNAME_get(stash);
Branch: 6 branches
BranchTrueFalseTotal
name = HvNAME_get(stash); 4 0 4
name = HvNAME_get(stash); 4 0 4
name = HvNAME_get(stash); 0 4 4
name = HvNAME_get(stash); 0 0 0
name = HvNAME_get(stash); 4 0 4
name = HvNAME_get(stash); 0 4 4
792 4 ▶ if (!name) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!name) return 0; 0 4 4
793 4 ▶ if (strEQ(name, "JSON::PP::Boolean")) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(name, "JSON::PP::Boolean")) return 1; 2 2 4
794 2 ▶ if (strEQ(name, "Types::Serialiser::Boolean")) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(name, "Types::Serialiser::Boolean")) return 1; 0 2 2
795 2 ▶ if (strEQ(name, "Cpanel::JSON::XS::Boolean")) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(name, "Cpanel::JSON::XS::Boolean")) return 1; 0 2 2
796 2 ▶ if (strEQ(name, "JSON::XS::Boolean")) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(name, "JSON::XS::Boolean")) return 1; 0 2 2
797 2 ▶ if (strEQ(name, "boolean")) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(name, "boolean")) return 1; 0 2 2
798 /* Last: name-compare File::Raw::JSON::Boolean for the case where
799 * the stash pointer drifted (eg multiple interpreter contexts). */
800 2 return strEQ(name, "File::Raw::JSON::Boolean");
801 }
802  
803 /* ============================================================
804 * Decode entry points
805 * ============================================================ */
806  
807 static void
808 6 croak_yyjson_read(pTHX_ const yyjson_read_err *err,
809 const char *bytes, STRLEN len)
810 {
811 6 STRLEN ctx_off = err->pos > 16 ? err->pos - 16 : 0;
812 6 STRLEN ctx_end = err->pos + 16 < len ? err->pos + 16 : len;
813 6 STRLEN ctx_len = ctx_end - ctx_off;
814 6 SV *ctx = sv_2mortal(newSVpvn(bytes + ctx_off, ctx_len));
815 6 char *p = SvPVX(ctx);
816 STRLEN i;
817 50 ▶ for (i = 0; i < ctx_len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < ctx_len; i++) { 44 6 50
818 44 ▶ if (p[i] == '\n' || p[i] == '\r' || p[i] == '\t') p[i] = ' ';
Branch: 3 branches
BranchTrueFalseTotal
if (p[i] == '\n' || p[i] == '\r' || p[i] == '\t') p[i] = ' '; 43 1 44
if (p[i] == '\n' || p[i] == '\r' || p[i] == '\t') p[i] = ' '; 43 0 43
if (p[i] == '\n' || p[i] == '\r' || p[i] == '\t') p[i] = ' '; 0 43 43
819 }
820 6 ▶ croak("File::Raw::JSON: %s at byte offset %lu near \"%.*s\"",
Branch: 1 branch
BranchTrueFalseTotal
croak("File::Raw::JSON: %s at byte offset %lu near \"%.*s\"", 6 0 6
821 err->msg ? err->msg : "parse error",
822 (unsigned long)err->pos, (int)ctx_len, p);
823 }
824  
825 static yyjson_read_flag
826 236 build_read_flags(const json_options_t *opts)
827 {
828 236 yyjson_read_flag f = 0;
829 236 ▶ if (opts->relaxed) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->relaxed) { 5 231 236
830 5 f |= YYJSON_READ_ALLOW_COMMENTS;
831 5 f |= YYJSON_READ_ALLOW_TRAILING_COMMAS;
832 }
833 236 ▶ if (opts->allow_nan_inf) f |= YYJSON_READ_ALLOW_INF_AND_NAN;
Branch: 1 branch
BranchTrueFalseTotal
if (opts->allow_nan_inf) f |= YYJSON_READ_ALLOW_INF_AND_NAN; 1 235 236
834 236 return f;
835 }
836  
837 /* Hybrid bump-then-malloc allocator for yyjson read.
838 *
839 * yyjson allocates one ~16-byte mut_val per JSON value via its
840 * configured allocator (default: malloc). For small/medium docs
841 * those allocations are pure overhead - we'd rather slice them off
842 * a pre-allocated stack buffer.
843 *
844 * This allocator does exactly that: serves from a stack-resident
845 * pool by bump pointer until exhausted, then falls back to malloc
846 * for individual oversize requests. free() is a no-op for in-pool
847 * pointers, real free() for malloc'd ones.
848 *
849 * Why hybrid (rather than just yyjson_alc_pool_init): the built-in
850 * pool init returns NULL on overflow, which fails the parse. We
851 * want graceful fallback so any doc parses, with the small/medium
852 * fast path getting the perf win. */
853 typedef struct {
854 char *pool;
855 size_t pool_size;
856 size_t pool_used;
857 } frj_alc_ctx_t;
858  
859 static void *
860 551 frj_alc_malloc(void *ctx, size_t size)
861 {
862 551 frj_alc_ctx_t *c = (frj_alc_ctx_t *)ctx;
863 /* 16-byte aligned bump (yyjson values are typically 16-byte). */
864 551 size_t aligned = (c->pool_used + 15) & ~(size_t)15;
865 551 ▶ if (aligned + size <= c->pool_size) {
Branch: 1 branch
BranchTrueFalseTotal
if (aligned + size <= c->pool_size) { 542 9 551
866 542 c->pool_used = aligned + size;
867 542 return c->pool + aligned;
868 }
869 9 return malloc(size);
870 }
871  
872 static void *
873 83 frj_alc_realloc(void *ctx, void *ptr, size_t old_size, size_t size)
874 {
875 83 frj_alc_ctx_t *c = (frj_alc_ctx_t *)ctx;
876 83 ▶ if (ptr >= (void *)c->pool && ptr < (void *)(c->pool + c->pool_size)) {
Branch: 2 branches
BranchTrueFalseTotal
if (ptr >= (void *)c->pool && ptr < (void *)(c->pool + c->pool_size)) { 79 4 83
if (ptr >= (void *)c->pool && ptr < (void *)(c->pool + c->pool_size)) { 79 0 79
877 /* In-pool memory: allocate fresh, copy, leave the old block
878 * in the pool (will be reclaimed when the pool is reset). */
879 79 void *new_ptr = frj_alc_malloc(ctx, size);
880 79 ▶ if (new_ptr && old_size > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (new_ptr && old_size > 0) { 79 0 79
if (new_ptr && old_size > 0) { 79 0 79
881 79 memcpy(new_ptr, ptr, old_size < size ? old_size : size);
882 }
883 79 return new_ptr;
884 }
885 4 return realloc(ptr, size);
886 }
887  
888 static void
889 470 frj_alc_free(void *ctx, void *ptr)
890 {
891 470 frj_alc_ctx_t *c = (frj_alc_ctx_t *)ctx;
892 470 ▶ if (ptr >= (void *)c->pool && ptr < (void *)(c->pool + c->pool_size)) {
Branch: 2 branches
BranchTrueFalseTotal
if (ptr >= (void *)c->pool && ptr < (void *)(c->pool + c->pool_size)) { 462 8 470
if (ptr >= (void *)c->pool && ptr < (void *)(c->pool + c->pool_size)) { 462 0 462
893 462 return; /* No-op for pool memory; reset on caller exit */
894 }
895 8 free(ptr);
896 }
897  
898 #define FRJ_READ_POOL_BYTES (16 * 1024)
899  
900 SV *
901 146 json_decode_document(pTHX_ const char *bytes, STRLEN len,
902 const json_options_t *opts, HV *boolean_stash)
903 {
904 char pool_buf[FRJ_READ_POOL_BYTES];
905 frj_alc_ctx_t alc_ctx;
906 yyjson_alc alc;
907 yyjson_read_err err;
908 yyjson_doc *doc;
909 SV *out;
910 yyjson_val *root;
911  
912 146 alc_ctx.pool = pool_buf;
913 146 alc_ctx.pool_size = sizeof pool_buf;
914 146 alc_ctx.pool_used = 0;
915 146 alc.malloc = frj_alc_malloc;
916 146 alc.realloc = frj_alc_realloc;
917 146 alc.free = frj_alc_free;
918 146 alc.ctx = &alc_ctx;
919  
920 146 doc = yyjson_read_opts((char *)bytes, (size_t)len,
921 build_read_flags(opts), &alc, &err);
922  
923 146 ▶ if (!doc) {
Branch: 1 branch
BranchTrueFalseTotal
if (!doc) { 6 140 146
924 6 croak_yyjson_read(aTHX_ &err, bytes, len);
925 /* NOTREACHED */
926 }
927 140 root = yyjson_doc_get_root(doc);
928 140 ▶ if (!opts->allow_nonref && root) {
Branch: 2 branches
BranchTrueFalseTotal
if (!opts->allow_nonref && root) { 1 139 140
if (!opts->allow_nonref && root) { 1 0 1
929 1 yyjson_type t = yyjson_get_type(root);
930 1 ▶ if (t != YYJSON_TYPE_ARR && t != YYJSON_TYPE_OBJ) {
Branch: 2 branches
BranchTrueFalseTotal
if (t != YYJSON_TYPE_ARR && t != YYJSON_TYPE_OBJ) { 1 0 1
if (t != YYJSON_TYPE_ARR && t != YYJSON_TYPE_OBJ) { 1 0 1
931 yyjson_doc_free(doc);
932 1 croak("File::Raw::JSON: top-level value is not an object/array "
933 "and allow_nonref is false");
934 }
935 }
936 139 out = json_sv_from_yyjson(aTHX_ root, boolean_stash,
937 139 opts->ordered, opts->max_depth);
938 yyjson_doc_free(doc);
939 138 return out;
940 }
941  
942 AV *
943 38 json_decode_lines(pTHX_ const char *bytes, STRLEN len,
944 const json_options_t *opts, HV *boolean_stash)
945 {
946 38 AV *result = newAV();
947 38 STRLEN cursor = 0;
948 /* Per-line pool: reused across all lines. Reset to empty after
949 * each parse (the doc is freed before next parse, so all in-pool
950 * memory is logically reclaimed). */
951 char pool_buf[FRJ_READ_POOL_BYTES];
952 frj_alc_ctx_t alc_ctx;
953 yyjson_alc alc;
954 38 alc_ctx.pool = pool_buf;
955 38 alc_ctx.pool_size = sizeof pool_buf;
956 38 alc.malloc = frj_alc_malloc;
957 38 alc.realloc = frj_alc_realloc;
958 38 alc.free = frj_alc_free;
959 38 alc.ctx = &alc_ctx;
960  
961 128 ▶ while (cursor < len) {
Branch: 1 branch
BranchTrueFalseTotal
while (cursor < len) { 92 36 128
962 STRLEN s, e, np;
963 jsonl_scan_t rc =
964 92 json_jsonl_next(bytes + cursor, len - cursor, &s, &e, &np);
965 92 ▶ if (rc == JSONL_FOUND) {
Branch: 1 branch
BranchTrueFalseTotal
if (rc == JSONL_FOUND) { 90 2 92
966 yyjson_read_err err;
967 yyjson_doc *doc;
968 90 alc_ctx.pool_used = 0; /* reset pool for next line */
969 90 doc = yyjson_read_opts(
970 90 (char *)bytes + cursor + s, (size_t)(e - s),
971 build_read_flags(opts), &alc, &err);
972 90 ▶ if (!doc) {
Branch: 1 branch
BranchTrueFalseTotal
if (!doc) { 0 90 90
973 0 err.pos += cursor + s;
974 0 SvREFCNT_dec((SV *)result);
975 0 croak_yyjson_read(aTHX_ &err, bytes, len);
976 }
977 180 ▶ av_push(result,
Branch: 1 branch
BranchTrueFalseTotal
av_push(result, 90 0 90
978 json_sv_from_yyjson(aTHX_ yyjson_doc_get_root(doc),
979 boolean_stash, opts->ordered,
980 opts->max_depth));
981 yyjson_doc_free(doc);
982 90 cursor += np;
983 90 continue;
984 }
985 2 ▶ if (rc == JSONL_NEED_MORE) {
Branch: 1 branch
BranchTrueFalseTotal
if (rc == JSONL_NEED_MORE) { 1 1 2
986 1 SvREFCNT_dec((SV *)result);
987 1 croak("File::Raw::JSON: truncated JSON value at byte offset %lu",
988 (unsigned long)(cursor + s));
989 }
990 /* JSONL_NO_OPENER: lenient = skip; strict = croak. */
991 1 ▶ if (s >= len - cursor) break; /* trailing whitespace */
Branch: 1 branch
BranchTrueFalseTotal
if (s >= len - cursor) break; /* trailing whitespace */ 1 0 1
992 0 ▶ if (opts->relaxed) { cursor += s + 1; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (opts->relaxed) { cursor += s + 1; continue; } 0 0 0
993 0 SvREFCNT_dec((SV *)result);
994 0 croak("File::Raw::JSON: unexpected byte at offset %lu "
995 "(expected '{' or '[' to start a JSONL value)",
996 (unsigned long)(cursor + s));
997 }
998 37 return result;
999 }
1000  
1001 /* ============================================================
1002 * Encode entry points
1003 * ============================================================ */
1004  
1005 static yyjson_write_flag
1006 1151 build_write_flags(const json_options_t *opts)
1007 {
1008 1151 yyjson_write_flag f = 0;
1009 1151 ▶ if (opts->pretty && !opts->canonical) {
Branch: 2 branches
BranchTrueFalseTotal
if (opts->pretty && !opts->canonical) { 14 1137 1151
if (opts->pretty && !opts->canonical) { 14 0 14
1010 14 ▶ if (opts->indent == 4) {
Branch: 1 branch
BranchTrueFalseTotal
if (opts->indent == 4) { 1 13 14
1011 1 f |= YYJSON_WRITE_PRETTY; /* 4 spaces */
1012 } else {
1013 13 f |= YYJSON_WRITE_PRETTY_TWO_SPACES;
1014 }
1015 }
1016 1151 ▶ if (!opts->utf8) f |= YYJSON_WRITE_ESCAPE_UNICODE;
Branch: 1 branch
BranchTrueFalseTotal
if (!opts->utf8) f |= YYJSON_WRITE_ESCAPE_UNICODE; 0 1151 1151
1017 1151 ▶ if (opts->allow_nan_inf) f |= YYJSON_WRITE_ALLOW_INF_AND_NAN;
Branch: 1 branch
BranchTrueFalseTotal
if (opts->allow_nan_inf) f |= YYJSON_WRITE_ALLOW_INF_AND_NAN; 1 1150 1151
1018 1151 return f;
1019 }
1020  
1021 SV *
1022 1156 json_encode_document(pTHX_ SV *value, const json_options_t *opts)
1023 {
1024 1156 yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
1025 yyjson_mut_val *root;
1026 yyjson_write_err err;
1027 char *out;
1028 size_t out_len;
1029 SV *result;
1030  
1031 1156 ▶ if (!doc) croak("File::Raw::JSON: out of memory (mut_doc_new)");
Branch: 1 branch
BranchTrueFalseTotal
if (!doc) croak("File::Raw::JSON: out of memory (mut_doc_new)"); 0 1156 1156
1032  
1033 1156 root = json_sv_to_yyjson(aTHX_ value, doc, opts);
1034 yyjson_mut_doc_set_root(doc, root);
1035  
1036 1151 out = yyjson_mut_write_opts(doc, build_write_flags(opts), NULL,
1037 &out_len, &err);
1038 1151 ▶ if (!out) {
Branch: 1 branch
BranchTrueFalseTotal
if (!out) { 0 1151 1151
1039 0 yyjson_mut_doc_free(doc);
1040 0 ▶ croak("File::Raw::JSON: encode failed: %s",
Branch: 1 branch
BranchTrueFalseTotal
croak("File::Raw::JSON: encode failed: %s", 0 0 0
1041 err.msg ? err.msg : "unknown error");
1042 }
1043 1151 result = newSVpvn(out, out_len);
1044 1151 free(out);
1045 1151 yyjson_mut_doc_free(doc);
1046 1151 return result;
1047 }
1048  
1049 SV *
1050 13 json_encode_lines(pTHX_ SV *payload, const json_options_t *opts)
1051 {
1052 AV *av;
1053 SSize_t i, n;
1054 SV *out;
1055  
1056 13 ▶ if (!payload || !SvROK(payload) || SvTYPE(SvRV(payload)) != SVt_PVAV)
Branch: 3 branches
BranchTrueFalseTotal
if (!payload || !SvROK(payload) || SvTYPE(SvRV(payload)) != SVt_PVAV) 13 0 13
if (!payload || !SvROK(payload) || SvTYPE(SvRV(payload)) != SVt_PVAV) 12 1 13
if (!payload || !SvROK(payload) || SvTYPE(SvRV(payload)) != SVt_PVAV) 1 11 12
1057 2 croak("File::Raw::JSON: jsonl write expects an arrayref of records");
1058  
1059 11 av = (AV *)SvRV(payload);
1060 11 n = av_len(av) + 1;
1061 11 out = newSVpvn("", 0);
1062  
1063 1032 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 1021 11 1032
1064 1021 SV **ep = av_fetch(av, i, 0);
1065 SV *rec_bytes;
1066 STRLEN blen;
1067 const char *bp;
1068 2042 ▶ rec_bytes = json_encode_document(aTHX_
Branch: 1 branch
BranchTrueFalseTotal
rec_bytes = json_encode_document(aTHX_ 1021 0 1021
1069 1021 ▶ (ep && *ep) ? *ep : &PL_sv_undef, opts);
Branch: 1 branch
BranchTrueFalseTotal
(ep && *ep) ? *ep : &PL_sv_undef, opts); 1021 0 1021
1070 1021 bp = SvPV(rec_bytes, blen);
1071 1021 sv_catpvn(out, bp, blen);
1072 1021 sv_catpvn(out, opts->eol, opts->eol_len);
1073 1021 SvREFCNT_dec(rec_bytes);
1074 }
1075 11 return out;
1076 }
« yyjson.c ↑ Summary include/yyjson.h »