encode.c

filter: Statementstmt 95.6% 956 / 1000 Branchbran 83.1% 750 / 902 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 89.7% 1706 / 1902 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« decimal.c ↑ Summary runtime.c »
1 #define PERL_NO_GET_CONTEXT
2 #include "EXTERN.h"
3 #include "perl.h"
4 #include "XSUB.h"
5  
6 #include <string.h>
7 #include <stdlib.h>
8 #include <stdint.h>
9 #include <math.h>
10  
11 #ifdef _WIN32
12 # include <winsock2.h>
13 # include <ws2tcpip.h>
14 #else
15 # include <sys/socket.h>
16 # include <arpa/inet.h>
17 #endif
18  
19 #include "types.h"
20 #include "buffer.h"
21 #include "decimal.h"
22 #include "scalar_kind.h"
23 #include "datetime.h"
24 #include "json_kind.h"
25 #include "encode.h"
26  
27 /* Build a recursive NULL placeholder for `t`. Returns a mortal SV.
28 * Leaf types get a defined zero/empty SV (not &PL_sv_undef) so that the
29 * encoder doesn't warn about uninit values when filling padding bytes. */
30 88 static SV *make_null_placeholder(pTHX_ TypeInfo *t) {
31 88 ▶ if (t->code == T_NULLABLE) return &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
if (t->code == T_NULLABLE) return &PL_sv_undef; 4 84 88
32 84 ▶ if (t->code == T_ARRAY || t->code == T_MAP) {
Branch: 2 branches
BranchTrueFalseTotal
if (t->code == T_ARRAY || t->code == T_MAP) { 80 4 84
if (t->code == T_ARRAY || t->code == T_MAP) { 4 76 80
33 8 AV *empty = newAV();
34 8 return sv_2mortal(newRV_noinc((SV*)empty));
35 }
36 76 ▶ if (t->code == T_TUPLE) {
Branch: 1 branch
BranchTrueFalseTotal
if (t->code == T_TUPLE) { 15 61 76
37 15 AV *tuple = newAV();
38 int i;
39 44 ▶ for (i = 0; i < t->tuple_len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < t->tuple_len; i++) { 29 15 44
40 29 SV *child = make_null_placeholder(aTHX_ t->tuple[i]);
41 29 av_push(tuple, SvREFCNT_inc(child));
42 }
43 15 return sv_2mortal(newRV_noinc((SV*)tuple));
44 }
45 61 ▶ if (t->code == T_LOWCARDINALITY)
Branch: 1 branch
BranchTrueFalseTotal
if (t->code == T_LOWCARDINALITY) 0 61 61
46 0 return make_null_placeholder(aTHX_ t->inner);
47 61 ▶ if (t->code == T_VARIANT || t->code == T_JSON || t->code == T_DYNAMIC)
Branch: 3 branches
BranchTrueFalseTotal
if (t->code == T_VARIANT || t->code == T_JSON || t->code == T_DYNAMIC) 61 0 61
if (t->code == T_VARIANT || t->code == T_JSON || t->code == T_DYNAMIC) 61 0 61
if (t->code == T_VARIANT || t->code == T_JSON || t->code == T_DYNAMIC) 0 61 61
48 /* Variant's encoder treats undef as the NULL discriminator. */
49 0 return &PL_sv_undef;
50 61 ▶ if (t->code == T_ENUM8 || t->code == T_ENUM16) return &PL_sv_undef;
Branch: 2 branches
BranchTrueFalseTotal
if (t->code == T_ENUM8 || t->code == T_ENUM16) return &PL_sv_undef; 58 3 61
if (t->code == T_ENUM8 || t->code == T_ENUM16) return &PL_sv_undef; 3 55 58
51 55 ▶ if (t->code == T_STRING || t->code == T_FIXEDSTRING)
Branch: 2 branches
BranchTrueFalseTotal
if (t->code == T_STRING || t->code == T_FIXEDSTRING) 41 14 55
if (t->code == T_STRING || t->code == T_FIXEDSTRING) 0 41 41
52 14 return sv_2mortal(newSVpvn("", 0));
53 41 ▶ if (t->code == T_UUID || t->code == T_IPV6)
Branch: 2 branches
BranchTrueFalseTotal
if (t->code == T_UUID || t->code == T_IPV6) 41 0 41
if (t->code == T_UUID || t->code == T_IPV6) 0 41 41
54 0 return sv_2mortal(newSVpvn("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16));
55 41 ▶ if (t->code == T_FLOAT32 || t->code == T_FLOAT64 || t->code == T_BFLOAT16)
Branch: 3 branches
BranchTrueFalseTotal
if (t->code == T_FLOAT32 || t->code == T_FLOAT64 || t->code == T_BFLOAT16) 41 0 41
if (t->code == T_FLOAT32 || t->code == T_FLOAT64 || t->code == T_BFLOAT16) 41 0 41
if (t->code == T_FLOAT32 || t->code == T_FLOAT64 || t->code == T_BFLOAT16) 0 41 41
56 0 return sv_2mortal(newSVnv(0.0));
57 /* numeric / date / decimal / bool / ipv4: a defined integer 0 is fine */
58 41 return sv_2mortal(newSViv(0));
59 }
60  
61 2095 static int enum_lookup_name(pTHX_ TypeInfo *t, const char *s, STRLEN slen, int16_t *out) {
62 2095 SV **psv = hv_fetch(t->enum_lookup, s, slen, 0);
63 2095 ▶ if (!psv) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!psv) return 0; 35 2060 2095
64 2060 *out = (int16_t)SvIV(*psv);
65 2060 return 1;
66 }
67  
68 45819 int nullable_is_null(SV *value, TypeInfo *t) {
69 45819 ▶ return !SvOK(value) || (t->empty_as_null && SvPOK(value) && !SvCUR(value));
Branch: 4 branches
BranchTrueFalseTotal
return !SvOK(value) || (t->empty_as_null && SvPOK(value) && !SvCUR(value)); 35408 10411 45819
return !SvOK(value) || (t->empty_as_null && SvPOK(value) && !SvCUR(value)); 55 35353 35408
return !SvOK(value) || (t->empty_as_null && SvPOK(value) && !SvCUR(value)); 40 15 55
return !SvOK(value) || (t->empty_as_null && SvPOK(value) && !SvCUR(value)); 35 5 40
70 }
71  
72 190961 static int empty_container(SV *value) {
73 190961 ▶ return !SvOK(value) || (!SvROK(value) && SvPOK(value) && !SvCUR(value));
Branch: 4 branches
BranchTrueFalseTotal
return !SvOK(value) || (!SvROK(value) && SvPOK(value) && !SvCUR(value)); 190944 17 190961
return !SvOK(value) || (!SvROK(value) && SvPOK(value) && !SvCUR(value)); 16 190928 190944
return !SvOK(value) || (!SvROK(value) && SvPOK(value) && !SvCUR(value)); 16 0 16
return !SvOK(value) || (!SvROK(value) && SvPOK(value) && !SvCUR(value)); 14 2 16
74 }
75  
76 571518 static void check_string_reference(pTHX_ SV *value, TypeInfo *t) {
77 571518 ▶ if (SvROK(value) && !(SvAMAGIC(value) && gv_handler(SvSTASH(SvRV(value)), string_amg)))
Branch: 5 branches
BranchTrueFalseTotal
if (SvROK(value) && !(SvAMAGIC(value) && gv_handler(SvSTASH(SvRV(value)), string_amg))) 46 571472 571518
if (SvROK(value) && !(SvAMAGIC(value) && gv_handler(SvSTASH(SvRV(value)), string_amg))) 46 0 46
if (SvROK(value) && !(SvAMAGIC(value) && gv_handler(SvSTASH(SvRV(value)), string_amg))) 16 30 46
if (SvROK(value) && !(SvAMAGIC(value) && gv_handler(SvSTASH(SvRV(value)), string_amg))) 6 10 16
if (SvROK(value) && !(SvAMAGIC(value) && gv_handler(SvSTASH(SvRV(value)), string_amg))) 0 6 6
78 40 ▶ croak("%s cannot encode a reference without string overloading",
Branch: 1 branch
BranchTrueFalseTotal
croak("%s cannot encode a reference without string overloading", 16 24 40
79 t->code == T_FIXEDSTRING ? "FixedString" : "String");
80 571478 }
81  
82 2154 static int16_t enum_value(pTHX_ TypeInfo *t, SV *val) {
83 IV iv;
84 int16_t v;
85 2154 ▶ int bits = t->code == T_ENUM8 ? 8 : 16;
Branch: 1 branch
BranchTrueFalseTotal
int bits = t->code == T_ENUM8 ? 8 : 16; 2091 63 2154
86 unsigned index;
87 2154 ▶ if (!SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) { 18 2136 2154
88 /* The type's default, as on the server: the smallest declared code. */
89 int k;
90 18 ▶ v = t->enum_count ? t->enum_entries[0].value : 0;
Branch: 1 branch
BranchTrueFalseTotal
v = t->enum_count ? t->enum_entries[0].value : 0; 18 0 18
91 40 ▶ for (k = 1; k < t->enum_count; k++)
Branch: 1 branch
BranchTrueFalseTotal
for (k = 1; k < t->enum_count; k++) 22 18 40
92 22 ▶ if (t->enum_entries[k].value < v) v = t->enum_entries[k].value;
Branch: 1 branch
BranchTrueFalseTotal
if (t->enum_entries[k].value < v) v = t->enum_entries[k].value; 14 8 22
93 18 return v;
94 }
95 2136 ▶ if (SvPOK(val) || t->enum_has_integer_labels) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvPOK(val) || t->enum_has_integer_labels) { 57 2079 2136
if (SvPOK(val) || t->enum_has_integer_labels) { 16 41 57
96 STRLEN len;
97 2095 const char *s = SvPV(val, len);
98 2095 ▶ if (enum_lookup_name(aTHX_ t, s, len, &v)) return v;
Branch: 1 branch
BranchTrueFalseTotal
if (enum_lookup_name(aTHX_ t, s, len, &v)) return v; 2060 35 2095
99 35 ▶ if (looks_like_int_str(s, len)) {
Branch: 1 branch
BranchTrueFalseTotal
if (looks_like_int_str(s, len)) { 30 5 35
100 30 ▶ STRLEN i = (s[0] == '+' || s[0] == '-') ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
STRLEN i = (s[0] == '+' || s[0] == '-') ? 1 : 0; 26 4 30
STRLEN i = (s[0] == '+' || s[0] == '-') ? 1 : 0; 12 14 26
101 30 unsigned magnitude = 0, limit = 1U << (bits - 1);
102 30 int negative = s[0] == '-';
103 30 ▶ if (!negative) limit--;
Branch: 1 branch
BranchTrueFalseTotal
if (!negative) limit--; 18 12 30
104 77 ▶ for (; i < len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (; i < len; i++) { 55 22 77
105 55 unsigned digit = s[i] - '0';
106 55 ▶ if (magnitude > (limit - digit) / 10)
Branch: 1 branch
BranchTrueFalseTotal
if (magnitude > (limit - digit) / 10) 8 47 55
107 8 croak("Enum%d value %.*s out of range", bits, (int)len, s);
108 47 magnitude = magnitude * 10 + digit;
109 }
110 22 ▶ iv = negative ? -(IV)magnitude : (IV)magnitude;
Branch: 1 branch
BranchTrueFalseTotal
iv = negative ? -(IV)magnitude : (IV)magnitude; 10 12 22
111 22 goto validate;
112 }
113 5 ▶ if (!SvIOK(val) && !SvNOK(val))
Branch: 2 branches
BranchTrueFalseTotal
if (!SvIOK(val) && !SvNOK(val)) 5 0 5
if (!SvIOK(val) && !SvNOK(val)) 5 0 5
114 5 croak("Unknown enum value: %.*s", (int)len, s);
115 }
116 41 ▶ if (SvIOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvIOK(val)) { 41 0 41
117 41 ▶ if (SvIsUV(val) && SvUV(val) > (UV)((1 << (bits - 1)) - 1))
Branch: 2 branches
BranchTrueFalseTotal
if (SvIsUV(val) && SvUV(val) > (UV)((1 << (bits - 1)) - 1)) 0 41 41
if (SvIsUV(val) && SvUV(val) > (UV)((1 << (bits - 1)) - 1)) 0 0 0
118 0 croak("Enum%d value %" UVuf " out of range", bits, SvUV(val));
119 41 iv = SvIV(val);
120 } else {
121 0 NV nv = trunc(SvNV(val));
122 0 ▶ if (!isfinite(nv) || nv < -(1 << (bits - 1)) || nv > (1 << (bits - 1)) - 1)
Branch: 3 branches
BranchTrueFalseTotal
if (!isfinite(nv) || nv < -(1 << (bits - 1)) || nv > (1 << (bits - 1)) - 1) 0 0 0
if (!isfinite(nv) || nv < -(1 << (bits - 1)) || nv > (1 << (bits - 1)) - 1) 0 0 0
if (!isfinite(nv) || nv < -(1 << (bits - 1)) || nv > (1 << (bits - 1)) - 1) 0 0 0
123 0 croak("Enum%d value out of range", bits);
124 0 iv = (IV)nv;
125 }
126 41 ▶ if (iv < -(1 << (bits - 1)) || iv > (1 << (bits - 1)) - 1)
Branch: 2 branches
BranchTrueFalseTotal
if (iv < -(1 << (bits - 1)) || iv > (1 << (bits - 1)) - 1) 40 1 41
if (iv < -(1 << (bits - 1)) || iv > (1 << (bits - 1)) - 1) 3 37 40
127 4 croak("Enum%d value %" IVdf " out of range", bits, iv);
128 37 validate:
129 59 index = (unsigned)(iv + (1 << (bits - 1)));
130 59 ▶ if (!(t->enum_codes[index >> 3] & (1U << (index & 7))))
Branch: 1 branch
BranchTrueFalseTotal
if (!(t->enum_codes[index >> 3] & (1U << (index & 7)))) 16 43 59
131 16 croak("Enum%d undeclared code: %" IVdf, bits, iv);
132 43 return (int16_t)iv;
133 }
134  
135 310477 static uint64_t checked_integer(pTHX_ SV *val, const char *type,
136 unsigned bits, int is_unsigned) {
137 uint64_t magnitude;
138 310477 int negative = 0;
139 310477 SvGETMAGIC(val);
140 310477 ▶ if (!SvOK(val)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) return 0; 28 310449 310477
141 310449 ▶ if (SvIOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvIOK(val)) { 310392 57 310449
142 310392 ▶ if (SvIsUV(val)) magnitude = (uint64_t)SvUVX(val);
Branch: 1 branch
BranchTrueFalseTotal
if (SvIsUV(val)) magnitude = (uint64_t)SvUVX(val); 5 310387 310392
143 else {
144 310387 IV iv = SvIVX(val);
145 310387 negative = iv < 0;
146 310387 ▶ magnitude = negative ? (uint64_t)0 - (uint64_t)iv : (uint64_t)iv;
Branch: 1 branch
BranchTrueFalseTotal
magnitude = negative ? (uint64_t)0 - (uint64_t)iv : (uint64_t)iv; 95 310292 310387
147 }
148 57 ▶ } else if (SvPOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (SvPOK(val)) { 6 51 57
149 UV uv;
150 51 int flags = grok_number(SvPVX_const(val), SvCUR(val), &uv);
151 51 ▶ if (flags & (IS_NUMBER_INFINITY | IS_NUMBER_NAN))
Branch: 1 branch
BranchTrueFalseTotal
if (flags & (IS_NUMBER_INFINITY | IS_NUMBER_NAN)) 0 51 51
152 0 croak("%s out of range", type);
153 51 ▶ if (flags & IS_NUMBER_NOT_INT) goto numeric;
Branch: 1 branch
BranchTrueFalseTotal
if (flags & IS_NUMBER_NOT_INT) goto numeric; 4 47 51
154 47 ▶ if (!(flags & IS_NUMBER_IN_UV)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!(flags & IS_NUMBER_IN_UV)) { 4 43 47
155 4 croak("%s out of range", type);
156 }
157 43 magnitude = (uint64_t)uv;
158 43 negative = (flags & IS_NUMBER_NEG) != 0;
159 } else {
160 6 numeric: ;
161 10 NV nv = SvNV_nomg(val);
162 10 NV upper = is_unsigned ? (bits == 64 ? (NV)18446744073709551616.0
163 4 ▶ : (NV)((uint64_t)1 << bits))
Branch: 1 branch
BranchTrueFalseTotal
: (NV)((uint64_t)1 << bits)) 3 1 4
164 14 ▶ : (NV)((uint64_t)1 << (bits - 1));
Branch: 1 branch
BranchTrueFalseTotal
: (NV)((uint64_t)1 << (bits - 1)); 4 6 10
165 10 ▶ NV lower = is_unsigned ? (NV)0 : -upper;
Branch: 1 branch
BranchTrueFalseTotal
NV lower = is_unsigned ? (NV)0 : -upper; 6 4 10
166 10 ▶ if (!isfinite(nv) || nv < lower || nv >= upper)
Branch: 3 branches
BranchTrueFalseTotal
if (!isfinite(nv) || nv < lower || nv >= upper) 10 0 10
if (!isfinite(nv) || nv < lower || nv >= upper) 7 3 10
if (!isfinite(nv) || nv < lower || nv >= upper) 4 3 7
167 7 croak("%s out of range", type);
168 3 ▶ return is_unsigned ? (uint64_t)nv : (uint64_t)(int64_t)nv;
Branch: 1 branch
BranchTrueFalseTotal
return is_unsigned ? (uint64_t)nv : (uint64_t)(int64_t)nv; 1 2 3
169 }
170 310435 ▶ if (is_unsigned) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_unsigned) { 297985 12450 310435
171 297985 ▶ uint64_t max = bits == 64 ? UINT64_MAX : ((uint64_t)1 << bits) - 1;
Branch: 1 branch
BranchTrueFalseTotal
uint64_t max = bits == 64 ? UINT64_MAX : ((uint64_t)1 << bits) - 1; 256619 41366 297985
172 297985 ▶ if ((negative && magnitude) || magnitude > max)
Branch: 3 branches
BranchTrueFalseTotal
if ((negative && magnitude) || magnitude > max) 8 297977 297985
if ((negative && magnitude) || magnitude > max) 0 8 8
if ((negative && magnitude) || magnitude > max) 6 297971 297977
173 14 croak("%s out of range", type);
174 297971 return magnitude;
175 } else {
176 12450 uint64_t limit = (uint64_t)1 << (bits - 1);
177 12450 ▶ if (magnitude > limit || (!negative && magnitude == limit))
Branch: 3 branches
BranchTrueFalseTotal
if (magnitude > limit || (!negative && magnitude == limit)) 12445 5 12450
if (magnitude > limit || (!negative && magnitude == limit)) 12345 100 12445
if (magnitude > limit || (!negative && magnitude == limit)) 4 12341 12345
178 9 croak("%s out of range", type);
179 12441 ▶ return negative ? (uint64_t)0 - magnitude : magnitude;
Branch: 1 branch
BranchTrueFalseTotal
return negative ? (uint64_t)0 - magnitude : magnitude; 100 12341 12441
180 }
181 }
182  
183 2114 static void check_decimal_int64(pTHX_ TypeInfo *t, int64_t v, int bits) {
184 2114 ▶ uint64_t magnitude = v < 0 ? (uint64_t)0 - (uint64_t)v : (uint64_t)v;
Branch: 1 branch
BranchTrueFalseTotal
uint64_t magnitude = v < 0 ? (uint64_t)0 - (uint64_t)v : (uint64_t)v; 20 2094 2114
185 2114 ▶ if (t->precision > 0 && t->precision < 19 && magnitude >= pow10_u64[t->precision])
Branch: 3 branches
BranchTrueFalseTotal
if (t->precision > 0 && t->precision < 19 && magnitude >= pow10_u64[t->precision]) 2114 0 2114
if (t->precision > 0 && t->precision < 19 && magnitude >= pow10_u64[t->precision]) 2114 0 2114
if (t->precision > 0 && t->precision < 19 && magnitude >= pow10_u64[t->precision]) 12 2102 2114
186 12 croak("Decimal%d overflow: value exceeds Decimal(%d, %d)", bits, t->precision, t->param);
187 2102 }
188  
189 928217 void encode_scalar(pTHX_ Buffer *b, SV *val, TypeInfo *t) {
190 928217 switch (t->code) {
191 30 case T_INT8: buf_byte(aTHX_ b, (uint8_t)checked_integer(aTHX_ val, "Int8", 8, 0)); break;
192 24 case T_INT16: buf_le16(aTHX_ b, (uint16_t)checked_integer(aTHX_ val, "Int16", 16, 0)); break;
193 12363 case T_INT32: buf_le32(aTHX_ b, (uint32_t)checked_integer(aTHX_ val, "Int32", 32, 0)); break;
194 44 case T_INT64: buf_le64(aTHX_ b, checked_integer(aTHX_ val, "Int64", 64, 0)); break;
195 4893 case T_UINT8: buf_byte(aTHX_ b, (uint8_t)checked_integer(aTHX_ val, "UInt8", 8, 1)); break;
196 22 case T_UINT16: buf_le16(aTHX_ b, (uint16_t)checked_integer(aTHX_ val, "UInt16", 16, 1)); break;
197 251720 case T_UINT32: buf_le32(aTHX_ b, (uint32_t)checked_integer(aTHX_ val, "UInt32", 32, 1)); break;
198 41368 case T_UINT64: buf_le64(aTHX_ b, checked_integer(aTHX_ val, "UInt64", 64, 1)); break;
199 27 case T_FLOAT32: buf_lefloat(aTHX_ b,(float)SvNV(val)); break;
200 42956 case T_FLOAT64: buf_ledouble(aTHX_ b,SvNV(val)); break;
201 30 case T_BFLOAT16: {
202 /* BFloat16 = top 16 bits of the Float32 binary representation
203 * (truncation, no rounding -- matches ClickHouse server). */
204 union { float f; uint32_t u; } u;
205 30 u.f = (float)SvNV(val);
206 30 buf_le16(aTHX_ b, (uint16_t)(u.u >> 16));
207 30 break;
208 }
209 503981 case T_STRING: {
210 503981 check_string_reference(aTHX_ val, t);
211 503965 ▶ if (!SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) { 15 503950 503965
212 15 buf_varint(aTHX_ b,0);
213 } else {
214 STRLEN len;
215 503950 const char *s = SvPV(val, len);
216 503950 buf_string(aTHX_ b,s, len);
217 }
218 503965 break;
219 }
220 73 case T_FIXEDSTRING: {
221 73 check_string_reference(aTHX_ val, t);
222 65 buf_grow(aTHX_ b,t->param);
223 65 ▶ if (!SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) { 0 65 65
224 0 memset(b->ptr + b->len, 0, t->param);
225 0 b->len += t->param;
226 } else {
227 STRLEN len;
228 65 const char *s = SvPV(val, len);
229 65 ▶ if (len >= (STRLEN)t->param) {
Branch: 1 branch
BranchTrueFalseTotal
if (len >= (STRLEN)t->param) { 26 39 65
230 26 memcpy(b->ptr + b->len, s, t->param);
231 26 b->len += t->param;
232 } else {
233 39 memcpy(b->ptr + b->len, s, len);
234 39 memset(b->ptr + b->len + len, 0, t->param - len);
235 39 b->len += t->param;
236 }
237 }
238 65 break;
239 }
240 2091 case T_ENUM8: {
241 2091 int16_t v = enum_value(aTHX_ t, val);
242 2072 buf_byte(aTHX_ b,(uint8_t)(int8_t)v);
243 2072 break;
244 }
245 63 case T_ENUM16: {
246 63 int16_t v = enum_value(aTHX_ t, val);
247 49 buf_le16(aTHX_ b,(uint16_t)v);
248 49 break;
249 }
250 63 case T_DECIMAL32: {
251 int64_t v64;
252 63 ▶ if (looks_stringy(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (looks_stringy(val)) { 53 10 63
253 STRLEN slen;
254 53 const char *s = SvPV(val, slen);
255 53 ▶ if (!parse_decimal_int64_str(s, slen, t->param, t->precision, &v64))
Branch: 1 branch
BranchTrueFalseTotal
if (!parse_decimal_int64_str(s, slen, t->param, t->precision, &v64)) 8 45 53
256 8 croak("Invalid decimal string: %.*s", (int)slen, s);
257 } else {
258 10 double d = SvNV(val) * decimal_pow10(t->param);
259 10 ▶ if (!(d >= (double)INT32_MIN && d <= (double)INT32_MAX))
Branch: 2 branches
BranchTrueFalseTotal
if (!(d >= (double)INT32_MIN && d <= (double)INT32_MAX)) 10 0 10
if (!(d >= (double)INT32_MIN && d <= (double)INT32_MAX)) 0 10 10
260 0 croak("Decimal32 overflow");
261 10 v64 = (int64_t)llround(d);
262 }
263 55 check_decimal_int64(aTHX_ t, v64, 32);
264 45 ▶ if (v64 < INT32_MIN || v64 > INT32_MAX)
Branch: 2 branches
BranchTrueFalseTotal
if (v64 < INT32_MIN || v64 > INT32_MAX) 45 0 45
if (v64 < INT32_MIN || v64 > INT32_MAX) 0 45 45
265 0 croak("Decimal32 overflow");
266 45 buf_le32(aTHX_ b,(uint32_t)(int32_t)v64);
267 45 break;
268 }
269 2069 case T_DECIMAL64: {
270 int64_t v;
271 2069 ▶ if (looks_stringy(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (looks_stringy(val)) { 2061 8 2069
272 STRLEN slen;
273 2061 const char *s = SvPV(val, slen);
274 2061 ▶ if (!parse_decimal_int64_str(s, slen, t->param, t->precision, &v))
Branch: 1 branch
BranchTrueFalseTotal
if (!parse_decimal_int64_str(s, slen, t->param, t->precision, &v)) 7 2054 2061
275 7 croak("Invalid decimal string: %.*s", (int)slen, s);
276 } else {
277 8 double d = SvNV(val) * decimal_pow10(t->param);
278 /* INT64_MAX (2^63 - 1) isn't exactly representable in double;
279 * the next representable double above it is 2^63 itself, so use
280 * a strict less-than against 2^63 to bracket the valid range. */
281 8 ▶ if (!(d > -9.223372036854776e18 && d < 9.223372036854776e18))
Branch: 2 branches
BranchTrueFalseTotal
if (!(d > -9.223372036854776e18 && d < 9.223372036854776e18)) 8 0 8
if (!(d > -9.223372036854776e18 && d < 9.223372036854776e18)) 3 5 8
282 3 croak("Decimal64 overflow (or non-finite value)");
283 5 v = (int64_t)llround(d);
284 }
285 2059 check_decimal_int64(aTHX_ t, v, 64);
286 2057 buf_le64(aTHX_ b,(uint64_t)v);
287 2057 break;
288 }
289 865 case T_DECIMAL256: {
290 865 uint64_t limbs[4] = {0,0,0,0};
291 865 ▶ if (looks_stringy(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (looks_stringy(val)) { 857 8 865
292 STRLEN slen;
293 857 const char *s = SvPV(val, slen);
294 857 ▶ if (!parse_decimal256_str(s, slen, t->param, t->precision, limbs))
Branch: 1 branch
BranchTrueFalseTotal
if (!parse_decimal256_str(s, slen, t->param, t->precision, limbs)) 9 848 857
295 9 croak("Invalid decimal string: %.*s", (int)slen, s);
296 } else {
297 /* Float path through long double; lossy past ~18 digits. */
298 8 long double d = (long double)SvNV(val) * decimal_pow10l(t->param);
299 8 ▶ if (!isfinite(d))
Branch: 1 branch
BranchTrueFalseTotal
if (!isfinite(d)) 0 8 8
300 0 croak("Decimal256: cannot encode non-finite value");
301 8 int neg = d < 0;
302 8 ▶ if (neg) d = -d;
Branch: 1 branch
BranchTrueFalseTotal
if (neg) d = -d; 0 8 8
303 8 d = roundl(d);
304 8 long double two64 = (long double)18446744073709551616.0L;
305 8 long double two255 = two64 * two64 * two64
306 * (long double)9223372036854775808.0L;
307 /* Reject values that would overflow signed 256-bit (i.e. set
308 * the sign bit, which CH would interpret as negative).
309 * Mirrors the >= 2^127 check in the Decimal128 path. */
310 8 ▶ if (d >= two255)
Branch: 1 branch
BranchTrueFalseTotal
if (d >= two255) 3 5 8
311 3 croak("Decimal256 overflow");
312 int j;
313 9 ▶ for (j = 0; j < 4 && d > 0; j++) {
Branch: 2 branches
BranchTrueFalseTotal
for (j = 0; j < 4 && d > 0; j++) { 8 1 9
for (j = 0; j < 4 && d > 0; j++) { 4 4 8
314 4 limbs[j] = (uint64_t)fmodl(d, two64);
315 4 d = (d - limbs[j]) / two64;
316 }
317 5 ▶ if (neg) {
Branch: 1 branch
BranchTrueFalseTotal
if (neg) { 0 5 5
318 0 ▶ for (j = 0; j < 4; j++) limbs[j] = ~limbs[j];
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < 4; j++) limbs[j] = ~limbs[j]; 0 0 0
319 0 add_digit_256(limbs, 1);
320 }
321 }
322 853 ▶ if (t->precision > 0 && !decimal256_within_precision(limbs, t->precision))
Branch: 2 branches
BranchTrueFalseTotal
if (t->precision > 0 && !decimal256_within_precision(limbs, t->precision)) 853 0 853
if (t->precision > 0 && !decimal256_within_precision(limbs, t->precision)) 5 848 853
323 5 croak("Decimal256 overflow: value exceeds Decimal(%d, %d)", t->precision, t->param);
324 848 buf_le64(aTHX_ b, limbs[0]);
325 848 buf_le64(aTHX_ b, limbs[1]);
326 848 buf_le64(aTHX_ b, limbs[2]);
327 848 buf_le64(aTHX_ b, limbs[3]);
328 848 break;
329 }
330 871 case T_DECIMAL128: {
331 uint64_t lo, hi;
332 871 ▶ if (looks_stringy(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (looks_stringy(val)) { 867 4 871
333 STRLEN slen;
334 867 const char *s = SvPV(val, slen);
335 867 ▶ if (!parse_decimal128_str(s, slen, t->param, t->precision, &hi, &lo))
Branch: 1 branch
BranchTrueFalseTotal
if (!parse_decimal128_str(s, slen, t->param, t->precision, &hi, &lo)) 11 856 867
336 11 croak("Invalid decimal string: %.*s", (int)slen, s);
337 } else {
338 4 long double d = (long double)SvNV(val) * decimal_pow10l(t->param);
339 4 ▶ if (!isfinite(d))
Branch: 1 branch
BranchTrueFalseTotal
if (!isfinite(d)) 0 4 4
340 0 croak("Decimal128: cannot encode non-finite value");
341 4 int neg = d < 0;
342 4 ▶ if (neg) d = -d;
Branch: 1 branch
BranchTrueFalseTotal
if (neg) d = -d; 1 3 4
343 4 d = roundl(d);
344 4 long double two64 = (long double)18446744073709551616.0L;
345 4 long double two127 = two64 * (long double)9223372036854775808.0L;
346 4 ▶ if (d >= two127)
Branch: 1 branch
BranchTrueFalseTotal
if (d >= two127) 2 2 4
347 2 croak("Decimal128 overflow");
348 2 hi = (uint64_t)(d / two64);
349 2 lo = (uint64_t)fmodl(d, two64);
350 2 ▶ if (neg) {
Branch: 1 branch
BranchTrueFalseTotal
if (neg) { 1 1 2
351 1 lo = ~lo + 1;
352 1 ▶ hi = ~hi + (lo == 0 ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
hi = ~hi + (lo == 0 ? 1 : 0); 0 1 1
353 }
354 }
355 858 ▶ if (t->precision > 0 && !decimal128_within_precision(hi, lo, t->precision))
Branch: 2 branches
BranchTrueFalseTotal
if (t->precision > 0 && !decimal128_within_precision(hi, lo, t->precision)) 858 0 858
if (t->precision > 0 && !decimal128_within_precision(hi, lo, t->precision)) 6 852 858
356 6 croak("Decimal128 overflow: value exceeds Decimal(%d, %d)", t->precision, t->param);
357 852 buf_le64(aTHX_ b,lo);
358 852 buf_le64(aTHX_ b,hi);
359 852 break;
360 }
361 53 case T_DATE: {
362 /* UInt16 days since the epoch: 1970-01-01 .. 2149-06-06.
363 * Out-of-range values would wrap to a different but
364 * valid-looking date, so reject them as T_DATETIME does. */
365 53 IV days = 0;
366 53 ▶ if (SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(val)) { 49 4 53
367 49 ▶ if (SvIOK(val) || SvNOK(val)) days = SvIV(val);
Branch: 2 branches
BranchTrueFalseTotal
if (SvIOK(val) || SvNOK(val)) days = SvIV(val); 29 20 49
if (SvIOK(val) || SvNOK(val)) days = SvIV(val); 0 29 29
368 else {
369 STRLEN slen;
370 29 const char *s = SvPV(val, slen);
371 49 days = looks_like_int_str(s, slen)
372 1 ? SvIV(val)
373 29 ▶ : (IV)parse_date_string(aTHX_ s, slen);
Branch: 1 branch
BranchTrueFalseTotal
: (IV)parse_date_string(aTHX_ s, slen); 1 28 29
374 }
375 40 ▶ if (days < 0 || days > 65535) {
Branch: 2 branches
BranchTrueFalseTotal
if (days < 0 || days > 65535) { 38 2 40
if (days < 0 || days > 65535) { 2 36 38
376 STRLEN mlen;
377 4 const char *ms = SvPV(val, mlen);
378 4 ▶ croak("Date out of range "
Branch: 1 branch
BranchTrueFalseTotal
croak("Date out of range " 4 0 4
379 "(1970-01-01 .. 2149-06-06): %.*s",
380 (int)(mlen > 30 ? 30 : mlen), ms);
381 }
382 }
383 40 buf_le16(aTHX_ b, (uint16_t)days);
384 40 break;
385 }
386 61 case T_DATE32: {
387 /* Int32 days since the epoch. Date strings can't reach the
388 * limit (the year caps at 9999), but a raw number can. */
389 61 IV days = 0;
390 61 ▶ if (SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(val)) { 61 0 61
391 61 ▶ if (SvIOK(val) || SvNOK(val)) days = SvIV(val);
Branch: 2 branches
BranchTrueFalseTotal
if (SvIOK(val) || SvNOK(val)) days = SvIV(val); 13 48 61
if (SvIOK(val) || SvNOK(val)) days = SvIV(val); 1 12 13
392 else {
393 STRLEN slen;
394 12 const char *s = SvPV(val, slen);
395 24 days = looks_like_int_str(s, slen)
396 0 ? SvIV(val)
397 12 ▶ : (IV)parse_date_string(aTHX_ s, slen);
Branch: 1 branch
BranchTrueFalseTotal
: (IV)parse_date_string(aTHX_ s, slen); 0 12 12
398 }
399 61 ▶ if (days < INT32_MIN || days > INT32_MAX) {
Branch: 2 branches
BranchTrueFalseTotal
if (days < INT32_MIN || days > INT32_MAX) { 61 0 61
if (days < INT32_MIN || days > INT32_MAX) { 1 60 61
400 STRLEN mlen;
401 1 const char *ms = SvPV(val, mlen);
402 1 ▶ croak("Date32 out of range "
Branch: 1 branch
BranchTrueFalseTotal
croak("Date32 out of range " 1 0 1
403 "(CH accepts 1900-01-01 .. 2299-12-31): %.*s",
404 (int)(mlen > 30 ? 30 : mlen), ms);
405 }
406 }
407 60 buf_le32(aTHX_ b, (uint32_t)(int32_t)days);
408 60 break;
409 }
410 51171 case T_DATETIME: {
411 uint32_t v;
412 51171 ▶ if (!SvOK(val)) v = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) v = 0; 0 51171 51171
413 51171 ▶ else if (SvIOK(val) || SvNOK(val)) v = (uint32_t)SvUV(val);
Branch: 2 branches
BranchTrueFalseTotal
else if (SvIOK(val) || SvNOK(val)) v = (uint32_t)SvUV(val); 64 51107 51171
else if (SvIOK(val) || SvNOK(val)) v = (uint32_t)SvUV(val); 0 64 64
414 else {
415 STRLEN slen;
416 64 const char *s = SvPV(val, slen);
417 64 ▶ if (looks_like_int_str(s, slen)) v = (uint32_t)SvUV(val);
Branch: 1 branch
BranchTrueFalseTotal
if (looks_like_int_str(s, slen)) v = (uint32_t)SvUV(val); 2 62 64
418 62 else v = parse_datetime_string(aTHX_ s, slen, t);
419 }
420 51152 buf_le32(aTHX_ b,v);
421 51152 break;
422 }
423 47 case T_DATETIME64: {
424 int64_t v;
425 47 ▶ if (!SvOK(val)) v = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) v = 0; 0 47 47
426 47 ▶ else if (SvIOK(val)) v = (int64_t)SvIV(val);
Branch: 1 branch
BranchTrueFalseTotal
else if (SvIOK(val)) v = (int64_t)SvIV(val); 9 38 47
427 38 ▶ else if (SvNOK(val)) v = dt64_double_to_int64(aTHX_ SvNV(val), t->param);
Branch: 1 branch
BranchTrueFalseTotal
else if (SvNOK(val)) v = dt64_double_to_int64(aTHX_ SvNV(val), t->param); 4 34 38
428 else {
429 STRLEN slen;
430 34 const char *s = SvPV(val, slen);
431 34 ▶ if (looks_like_int_str(s, slen))
Branch: 1 branch
BranchTrueFalseTotal
if (looks_like_int_str(s, slen)) 2 32 34
432 2 v = (int64_t)SvIV(val);
433 32 ▶ else if (looks_like_number_str(s, slen))
Branch: 1 branch
BranchTrueFalseTotal
else if (looks_like_number_str(s, slen)) 3 29 32
434 3 v = dt64_double_to_int64(aTHX_ SvNV(val), t->param);
435 else
436 29 v = parse_datetime64_string(aTHX_ s, slen, t->param, t);
437 }
438 36 buf_le64(aTHX_ b,(uint64_t)v);
439 36 break;
440 }
441 10037 case T_BOOL: {
442 10037 ▶ uint8_t v = SvOK(val) && SvTRUE(val) ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
uint8_t v = SvOK(val) && SvTRUE(val) ? 1 : 0; 10032 5 10037
uint8_t v = SvOK(val) && SvTRUE(val) ? 1 : 0; 5013 5019 10032
443 10037 buf_byte(aTHX_ b, v);
444 10037 break;
445 }
446 2430 case T_UUID: {
447 /* Wire format: two LE UInt64 halves with bytes reversed within
448 * each half. Standard input is "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
449 * also accept 16 raw bytes. */
450 uint8_t buf16[16];
451 2430 ▶ if (!SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) { 4 2426 2430
452 4 memset(buf16, 0, 16);
453 } else {
454 STRLEN slen;
455 2426 const char *s = SvPV(val, slen);
456 2426 ▶ if (slen == 16) {
Branch: 1 branch
BranchTrueFalseTotal
if (slen == 16) { 9 2417 2426
457 9 memcpy(buf16, s, 16);
458 2417 ▶ } else if (slen == 36) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (slen == 36) { 2416 1 2417
459 /* parse hex with dashes at positions 8, 13, 18, 23 */
460 2416 int i, j = 0;
461 2416 ▶ if (s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-')
Branch: 4 branches
BranchTrueFalseTotal
if (s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-') 2416 0 2416
if (s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-') 2416 0 2416
if (s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-') 2416 0 2416
if (s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-') 0 2416 2416
462 0 croak("Invalid UUID format: %.*s", (int)slen, s);
463 89356 ▶ for (i = 0; i < 36; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 36; i++) { 86941 2415 89356
464 86941 ▶ if (i == 8 || i == 13 || i == 18 || i == 23) continue;
Branch: 4 branches
BranchTrueFalseTotal
if (i == 8 || i == 13 || i == 18 || i == 23) continue; 84526 2415 86941
if (i == 8 || i == 13 || i == 18 || i == 23) continue; 82111 2415 84526
if (i == 8 || i == 13 || i == 18 || i == 23) continue; 79696 2415 82111
if (i == 8 || i == 13 || i == 18 || i == 23) continue; 2415 77281 79696
465 77281 char c = s[i];
466 77281 ▶ int nyb = (c >= '0' && c <= '9') ? c - '0'
Branch: 1 branch
BranchTrueFalseTotal
int nyb = (c >= '0' && c <= '9') ? c - '0' 65240 12041 77281
467 166602 ▶ : (c >= 'a' && c <= 'f') ? c - 'a' + 10
Branch: 2 branches
BranchTrueFalseTotal
: (c >= 'a' && c <= 'f') ? c - 'a' + 10 77281 0 77281
: (c >= 'a' && c <= 'f') ? c - 'a' + 10 12040 0 12040
468 24083 ▶ : (c >= 'A' && c <= 'F') ? c - 'A' + 10
Branch: 2 branches
BranchTrueFalseTotal
: (c >= 'A' && c <= 'F') ? c - 'A' + 10 12040 1 12041
: (c >= 'A' && c <= 'F') ? c - 'A' + 10 0 1 1
469 2 ▶ : -1;
Branch: 1 branch
BranchTrueFalseTotal
: -1; 1 0 1
470 77281 ▶ if (nyb < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (nyb < 0) 1 77280 77281
471 1 croak("Invalid UUID hex digit: %.*s", (int)slen, s);
472 77280 ▶ if ((j & 1) == 0) buf16[j >> 1] = nyb << 4;
Branch: 1 branch
BranchTrueFalseTotal
if ((j & 1) == 0) buf16[j >> 1] = nyb << 4; 38640 38640 77280
473 38640 else buf16[j >> 1] |= nyb;
474 77280 j++;
475 }
476 } else {
477 1 croak("UUID requires 36-char string or 16 raw bytes, got %d bytes",
478 (int)slen);
479 }
480 }
481 /* Reverse first half then second half. */
482 uint8_t out[16];
483 int i;
484 21852 ▶ for (i = 0; i < 8; i++) out[i] = buf16[7 - i];
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 8; i++) out[i] = buf16[7 - i]; 19424 2428 21852
485 21852 ▶ for (i = 0; i < 8; i++) out[8+i] = buf16[15 - i];
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 8; i++) out[8+i] = buf16[15 - i]; 19424 2428 21852
486 2428 buf_append(aTHX_ b, (const char *)out, 16);
487 2428 break;
488 }
489 38 case T_IPV4: {
490 uint32_t v;
491 38 ▶ if (!SvOK(val)) v = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) v = 0; 4 34 38
492 34 ▶ else if (SvIOK(val) || SvNOK(val))
Branch: 2 branches
BranchTrueFalseTotal
else if (SvIOK(val) || SvNOK(val)) 22 12 34
else if (SvIOK(val) || SvNOK(val)) 0 22 22
493 12 v = (uint32_t)checked_integer(aTHX_ val, "IPv4 integer", 32, 1);
494 else {
495 STRLEN slen;
496 22 const char *s = SvPV(val, slen);
497 22 ▶ if (looks_like_int_str(s, slen)) {
Branch: 1 branch
BranchTrueFalseTotal
if (looks_like_int_str(s, slen)) { 1 21 22
498 1 v = (uint32_t)checked_integer(aTHX_ val, "IPv4 integer", 32, 1);
499 } else {
500 char tmp[INET_ADDRSTRLEN];
501 21 ▶ if (slen >= sizeof(tmp))
Branch: 1 branch
BranchTrueFalseTotal
if (slen >= sizeof(tmp)) 0 21 21
502 0 croak("IPv4 string too long: %.*s", (int)slen, s);
503 21 memcpy(tmp, s, slen);
504 21 tmp[slen] = 0;
505 struct in_addr addr;
506 21 ▶ if (inet_pton(AF_INET, tmp, &addr) != 1)
Branch: 1 branch
BranchTrueFalseTotal
if (inet_pton(AF_INET, tmp, &addr) != 1) 2 19 21
507 2 croak("Invalid IPv4 address: %s", tmp);
508 /* inet_pton stores in network byte order; ntohl gives
509 * the canonical host-order integer (e.g. 0x01020304
510 * for "1.2.3.4") on any host. buf_le32 then writes
511 * the LE wire bytes [04][03][02][01]. */
512 19 v = ntohl((uint32_t)addr.s_addr);
513 }
514 }
515 33 buf_le32(aTHX_ b, v);
516 33 break;
517 }
518 827 case T_IPV6: {
519 uint8_t out[16];
520 827 ▶ if (!SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) { 4 823 827
521 4 memset(out, 0, 16);
522 } else {
523 STRLEN slen;
524 823 const char *s = SvPV(val, slen);
525 823 ▶ if (slen == 16 && !memchr(s, ':', slen)) {
Branch: 2 branches
BranchTrueFalseTotal
if (slen == 16 && !memchr(s, ':', slen)) { 805 18 823
if (slen == 16 && !memchr(s, ':', slen)) { 405 400 805
526 405 memcpy(out, s, 16);
527 } else {
528 char tmp[INET6_ADDRSTRLEN];
529 418 ▶ if (slen >= sizeof(tmp))
Branch: 1 branch
BranchTrueFalseTotal
if (slen >= sizeof(tmp)) 0 418 418
530 0 croak("IPv6 string too long: %.*s", (int)slen, s);
531 418 memcpy(tmp, s, slen);
532 418 tmp[slen] = 0;
533 418 ▶ if (inet_pton(AF_INET6, tmp, out) != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (inet_pton(AF_INET6, tmp, out) != 1) { 6 412 418
534 struct in_addr v4;
535 6 ▶ if (inet_pton(AF_INET, tmp, &v4) == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (inet_pton(AF_INET, tmp, &v4) == 1) { 5 1 6
536 5 memset(out, 0, 10);
537 5 out[10] = out[11] = 255;
538 5 memcpy(out + 12, &v4, 4);
539 1 ▶ } else if (slen == 16) memcpy(out, s, 16);
Branch: 1 branch
BranchTrueFalseTotal
} else if (slen == 16) memcpy(out, s, 16); 0 1 1
540 1 else croak("Invalid IPv6 address: %s", tmp);
541 }
542 }
543 }
544 826 buf_append(aTHX_ b, (const char *)out, 16);
545 826 break;
546 }
547 0 default:
548 0 croak("encode_scalar called on non-scalar type");
549 }
550 928011 }
551  
552 14340 void encode_null_scalar(pTHX_ Buffer *b, TypeInfo *t) {
553 14340 switch (t->code) {
554 1380 case T_INT8: case T_UINT8: case T_ENUM8: case T_BOOL:
555 1380 buf_byte(aTHX_ b,0); break;
556 113 case T_INT16: case T_UINT16: case T_ENUM16: case T_DATE: case T_BFLOAT16:
557 113 buf_le16(aTHX_ b,0); break;
558 1089 case T_INT32: case T_UINT32: case T_FLOAT32:
559 case T_DECIMAL32: case T_DATE32: case T_DATETIME: case T_IPV4:
560 1089 buf_le32(aTHX_ b,0); break;
561 9885 case T_INT64: case T_UINT64: case T_FLOAT64:
562 case T_DECIMAL64: case T_DATETIME64:
563 9885 buf_le64(aTHX_ b,0); break;
564 96 case T_DECIMAL128: case T_UUID: case T_IPV6:
565 96 buf_le64(aTHX_ b,0); buf_le64(aTHX_ b,0); break;
566 50 case T_DECIMAL256:
567 50 buf_le64(aTHX_ b,0); buf_le64(aTHX_ b,0);
568 50 buf_le64(aTHX_ b,0); buf_le64(aTHX_ b,0); break;
569 1687 case T_STRING:
570 1687 buf_varint(aTHX_ b,0); break;
571 40 case T_FIXEDSTRING: {
572 40 buf_grow(aTHX_ b,t->param);
573 40 memset(b->ptr + b->len, 0, t->param);
574 40 b->len += t->param;
575 40 break;
576 }
577 0 default:
578 0 croak("encode_null_scalar called on complex type");
579 }
580 14340 }
581  
582 8148 int is_simple_type(TypeInfo *t) {
583 6589 ▶ return t->code != T_ARRAY && t->code != T_TUPLE && t->code != T_NULLABLE
Branch: 2 branches
BranchTrueFalseTotal
return t->code != T_ARRAY && t->code != T_TUPLE && t->code != T_NULLABLE 6503 86 6589
return t->code != T_ARRAY && t->code != T_TUPLE && t->code != T_NULLABLE 6503 0 6503
584 6503 ▶ && t->code != T_MAP && t->code != T_LOWCARDINALITY
Branch: 2 branches
BranchTrueFalseTotal
&& t->code != T_MAP && t->code != T_LOWCARDINALITY 6457 46 6503
&& t->code != T_MAP && t->code != T_LOWCARDINALITY 6380 77 6457
585 6380 ▶ && t->code != T_VARIANT && t->code != T_JSON
Branch: 2 branches
BranchTrueFalseTotal
&& t->code != T_VARIANT && t->code != T_JSON 6356 24 6380
&& t->code != T_VARIANT && t->code != T_JSON 6110 246 6356
586 14737 ▶ && t->code != T_DYNAMIC;
Branch: 2 branches
BranchTrueFalseTotal
&& t->code != T_DYNAMIC; 6589 1559 8148
&& t->code != T_DYNAMIC; 6097 13 6110
587 }
588  
589 /* Allocate an SV** array backed by a mortal SV (auto-freed on scope exit). */
590 5727 SV **alloc_sv_array(pTHX_ SSize_t n) {
591 5727 ▶ if (n <= 0) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return NULL; 1095 4632 5727
592 4632 STRLEN bytes = n * sizeof(SV*);
593 4632 SV *holder = sv_2mortal(newSV(bytes));
594 4632 SvPOK_only(holder);
595 4632 SvCUR_set(holder, bytes); /* keep the SV's claimed length in sync */
596 4632 return (SV**)SvPVX(holder);
597 }
598  
599 static int json_is_bool_ref(pTHX_ SV *val);
600  
601 /* For an arrayref leaf, infer the element kind. All elements must
602 * resolve to the same scalar kind (Bool/Float64/Int64/String) or be
603 * undef. Returns the matching JV_ARRAY_* kind, or -1 if heterogeneous
604 * / unsupported. NULL elements are accepted and encoded as zero-valued
605 * placeholders; CH represents them via the element type's Nullable
606 * wrapper if the user declares one - we use the bare type here. */
607 3410 static int json_classify_array(pTHX_ AV *av) {
608 3410 SSize_t n = av_len(av) + 1;
609 3410 int seen_kind = -1;
610 SSize_t i;
611 11444 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 8035 3409 11444
612 8035 SV **e = av_fetch(av, i, 0);
613 8035 ▶ if (!e || !SvOK(*e)) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!e || !SvOK(*e)) continue; 8035 0 8035
if (!e || !SvOK(*e)) continue; 0 8035 8035
614 8035 ▶ if (SvROK(*e)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvROK(*e)) { 620 7415 8035
615 /* recognized booleans only; nested arrays/hashes in array
616 * leaves are not yet supported */
617 620 ▶ if (json_is_bool_ref(aTHX_ *e)) {
Branch: 1 branch
BranchTrueFalseTotal
if (json_is_bool_ref(aTHX_ *e)) { 620 0 620
618 620 ▶ if (seen_kind == -1) seen_kind = JV_BOOL;
Branch: 1 branch
BranchTrueFalseTotal
if (seen_kind == -1) seen_kind = JV_BOOL; 234 386 620
619 386 ▶ else if (seen_kind != JV_BOOL) return -1;
Branch: 1 branch
BranchTrueFalseTotal
else if (seen_kind != JV_BOOL) return -1; 0 386 386
620 620 continue;
621 }
622 0 return -1;
623 }
624 int leaf;
625 #ifdef SvIsBOOL
626 7415 ▶ if (SvIsBOOL(*e)) leaf = JV_BOOL;
Branch: 1 branch
BranchTrueFalseTotal
if (SvIsBOOL(*e)) leaf = JV_BOOL; 0 7415 7415
627 else
628 #endif
629 7415 ▶ if (SvIOK(*e) && !SvNOK(*e))
Branch: 2 branches
BranchTrueFalseTotal
if (SvIOK(*e) && !SvNOK(*e)) 2316 5099 7415
if (SvIOK(*e) && !SvNOK(*e)) 2316 0 2316
630 2316 ▶ leaf = SvIsUV(*e) && SvUV(*e) > (UV)INT64_MAX ? JV_FLOAT64 : JV_INT64;
Branch: 2 branches
BranchTrueFalseTotal
leaf = SvIsUV(*e) && SvUV(*e) > (UV)INT64_MAX ? JV_FLOAT64 : JV_INT64; 0 2316 2316
leaf = SvIsUV(*e) && SvUV(*e) > (UV)INT64_MAX ? JV_FLOAT64 : JV_INT64; 0 0 0
631 5099 ▶ else if (SvNOK(*e)) {
Branch: 1 branch
BranchTrueFalseTotal
else if (SvNOK(*e)) { 1752 3347 5099
632 1752 NV nv = SvNV(*e);
633 3504 ▶ leaf = (nv >= (NV)INT64_MIN && nv < (NV)9223372036854775808.0L
Branch: 1 branch
BranchTrueFalseTotal
leaf = (nv >= (NV)INT64_MIN && nv < (NV)9223372036854775808.0L 1752 0 1752
634 1752 ▶ && nv == (NV)(int64_t)nv)
Branch: 1 branch
BranchTrueFalseTotal
&& nv == (NV)(int64_t)nv) 0 1752 1752
635 3504 ▶ ? JV_INT64 : JV_FLOAT64;
Branch: 1 branch
BranchTrueFalseTotal
? JV_INT64 : JV_FLOAT64; 1752 0 1752
636 } else {
637 3347 leaf = JV_STRING;
638 }
639 7415 ▶ if (seen_kind == -1) seen_kind = leaf;
Branch: 1 branch
BranchTrueFalseTotal
if (seen_kind == -1) seen_kind = leaf; 2950 4465 7415
640 4465 ▶ else if (seen_kind != leaf) return -1;
Branch: 1 branch
BranchTrueFalseTotal
else if (seen_kind != leaf) return -1; 1 4464 4465
641 }
642 /* all-NULL or empty: default to Array(Int64). The empty array
643 * doesn't carry an element type, so we pick one arbitrarily. If
644 * another row in the same path has a non-empty Array(T), the kind
645 * mask will then carry both Array(Int64) and Array(T); for a clean
646 * single-variant column the user can declare the column explicitly
647 * via a Variant(...) type. */
648 3409 ▶ if (seen_kind == -1) return JV_ARRAY_INT64;
Branch: 1 branch
BranchTrueFalseTotal
if (seen_kind == -1) return JV_ARRAY_INT64; 226 3183 3409
649 3183 switch (seen_kind) {
650 234 case JV_BOOL: return JV_ARRAY_BOOL;
651 806 case JV_FLOAT64: return JV_ARRAY_FLOAT64;
652 812 case JV_INT64: return JV_ARRAY_INT64;
653 1331 case JV_STRING: return JV_ARRAY_STRING;
654 0 default: return -1;
655 }
656 }
657  
658 2219 static int json_pkg_is_bool(const char *pkg) {
659 2234 ▶ return pkg && (strcmp(pkg, "JSON::PP::Boolean") == 0
Branch: 2 branches
BranchTrueFalseTotal
return pkg && (strcmp(pkg, "JSON::PP::Boolean") == 0 2219 0 2219
return pkg && (strcmp(pkg, "JSON::PP::Boolean") == 0 15 2204 2219
660 15 ▶ || strcmp(pkg, "Types::Serialiser::Boolean") == 0
Branch: 1 branch
BranchTrueFalseTotal
|| strcmp(pkg, "Types::Serialiser::Boolean") == 0 15 0 15
661 15 ▶ || strcmp(pkg, "JSON::XS::Boolean") == 0
Branch: 1 branch
BranchTrueFalseTotal
|| strcmp(pkg, "JSON::XS::Boolean") == 0 8 7 15
662 8 ▶ || strcmp(pkg, "Cpanel::JSON::XS::Boolean") == 0
Branch: 1 branch
BranchTrueFalseTotal
|| strcmp(pkg, "Cpanel::JSON::XS::Boolean") == 0 1 7 8
663 1 ▶ || strcmp(pkg, "boolean") == 0);
Branch: 1 branch
BranchTrueFalseTotal
|| strcmp(pkg, "boolean") == 0); 0 1 1
664 }
665  
666 /* True if val is a blessed ref into one of the recognized boolean packages. */
667 14043 static int json_is_bool_ref(pTHX_ SV *val) {
668 14043 ▶ if (!(SvROK(val) && sv_isobject(val))) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(val) && sv_isobject(val))) return 0; 8365 5678 14043
if (!(SvROK(val) && sv_isobject(val))) return 0; 6146 2219 8365
669 2219 HV *stash = SvSTASH(SvRV(val));
670 2219 ▶ return stash && json_pkg_is_bool(HvNAME(stash));
Branch: 8 branches
BranchTrueFalseTotal
return stash && json_pkg_is_bool(HvNAME(stash)); 2219 0 2219
return stash && json_pkg_is_bool(HvNAME(stash)); 2219 0 2219
return stash && json_pkg_is_bool(HvNAME(stash)); 2219 0 2219
return stash && json_pkg_is_bool(HvNAME(stash)); 0 2219 2219
return stash && json_pkg_is_bool(HvNAME(stash)); 0 0 0
return stash && json_pkg_is_bool(HvNAME(stash)); 2219 0 2219
return stash && json_pkg_is_bool(HvNAME(stash)); 0 2219 2219
return stash && json_pkg_is_bool(HvNAME(stash)); 2218 1 2219
671 }
672  
673 /* Classify a non-undef leaf SV for JSON encoding. Hash/array refs (other
674 * than recognized booleans) must be rejected by the caller before this. */
675 6363 static JsonValueKind json_classify_leaf(pTHX_ SV *val) {
676 6363 ▶ if (json_is_bool_ref(aTHX_ val)) return JV_BOOL;
Branch: 1 branch
BranchTrueFalseTotal
if (json_is_bool_ref(aTHX_ val)) return JV_BOOL; 685 5678 6363
677 #ifdef SvIsBOOL
678 5678 ▶ if (SvIsBOOL(val)) return JV_BOOL;
Branch: 1 branch
BranchTrueFalseTotal
if (SvIsBOOL(val)) return JV_BOOL; 6 5672 5678
679 #endif
680 5672 ▶ if (SvIOK(val) && !SvNOK(val))
Branch: 2 branches
BranchTrueFalseTotal
if (SvIOK(val) && !SvNOK(val)) 2504 3168 5672
if (SvIOK(val) && !SvNOK(val)) 2504 0 2504
681 2504 ▶ return SvIsUV(val) && SvUV(val) > (UV)INT64_MAX ? JV_FLOAT64 : JV_INT64;
Branch: 2 branches
BranchTrueFalseTotal
return SvIsUV(val) && SvUV(val) > (UV)INT64_MAX ? JV_FLOAT64 : JV_INT64; 0 2504 2504
return SvIsUV(val) && SvUV(val) > (UV)INT64_MAX ? JV_FLOAT64 : JV_INT64; 0 0 0
682 3168 ▶ if (SvNOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvNOK(val)) { 908 2260 3168
683 908 NV n = SvNV(val);
684 /* NV holding an exact integer value (e.g. `1.0`) collapses to
685 * Int64 - matches CH's JSONEachRow type-inference. Users who
686 * need `1.0` to survive as Float64 on the wire should put the
687 * value through a float-typed Variant or an explicit Float64
688 * column. NaN/Inf fall through to Float64 because the integer
689 * round-trip equality check fails for them. */
690 908 ▶ if (n >= (NV)INT64_MIN && n < (NV)9223372036854775808.0L
Branch: 2 branches
BranchTrueFalseTotal
if (n >= (NV)INT64_MIN && n < (NV)9223372036854775808.0L 908 0 908
if (n >= (NV)INT64_MIN && n < (NV)9223372036854775808.0L 908 0 908
691 908 ▶ && n == (NV)(int64_t)n)
Branch: 1 branch
BranchTrueFalseTotal
&& n == (NV)(int64_t)n) 0 908 908
692 0 return JV_INT64;
693 908 return JV_FLOAT64;
694 }
695 2260 return JV_STRING;
696 }
697  
698 /* Classify a (defined) JSON/Dynamic value SV. Dispatches arrayrefs to
699 * json_classify_array and everything else to json_classify_leaf, so the
700 * caller doesn't have to repeat the SvROK / bool-ref check. Returns the
701 * JsonValueKind, or -1 if `val` is an arrayref with heterogeneous
702 * elements. Caller has already ruled out hashref-non-bool refs. */
703 9773 static int json_classify_value(pTHX_ SV *val) {
704 9773 ▶ if (SvROK(val) && !json_is_bool_ref(aTHX_ val))
Branch: 2 branches
BranchTrueFalseTotal
if (SvROK(val) && !json_is_bool_ref(aTHX_ val)) 4095 5678 9773
if (SvROK(val) && !json_is_bool_ref(aTHX_ val)) 3410 685 4095
705 3410 return json_classify_array(aTHX_ (AV*)SvRV(val));
706 6363 return json_classify_leaf(aTHX_ val);
707 }
708  
709 /* Emit one element of an Array(T) Dynamic variant. Used by both T_JSON
710 * (per-path) and T_DYNAMIC (top-level) encode paths; `ev` may be undef
711 * in which case a zero-valued placeholder of the element type is written
712 * (CH represents nulls via Nullable wrappers, which we don't introduce
713 * inside Dynamic variant arrays). */
714 2006 static void json_emit_array_elem(pTHX_ Buffer *b, SV *ev, int k_match) {
715 2006 switch (k_match) {
716 153 case JV_ARRAY_BOOL: {
717 153 ▶ if (!SvOK(ev)) { buf_byte(aTHX_ b, 0); break; }
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(ev)) { buf_byte(aTHX_ b, 0); break; } 0 153 153
718 153 ▶ SV *bv = SvROK(ev) ? SvRV(ev) : ev;
Branch: 1 branch
BranchTrueFalseTotal
SV *bv = SvROK(ev) ? SvRV(ev) : ev; 153 0 153
719 153 buf_byte(aTHX_ b, SvTRUE(bv) ? 1 : 0);
720 153 break;
721 }
722 581 case JV_ARRAY_INT64:
723 581 ▶ buf_le64(aTHX_ b, SvOK(ev) ? (uint64_t)(int64_t)SvIV(ev) : 0);
Branch: 1 branch
BranchTrueFalseTotal
buf_le64(aTHX_ b, SvOK(ev) ? (uint64_t)(int64_t)SvIV(ev) : 0); 581 0 581
724 581 break;
725 436 case JV_ARRAY_FLOAT64:
726 436 ▶ buf_ledouble(aTHX_ b, SvOK(ev) ? SvNV(ev) : 0.0);
Branch: 1 branch
BranchTrueFalseTotal
buf_ledouble(aTHX_ b, SvOK(ev) ? SvNV(ev) : 0.0); 436 0 436
727 436 break;
728 836 case JV_ARRAY_STRING: {
729 836 ▶ if (!SvOK(ev)) { buf_varint(aTHX_ b, 0); break; }
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(ev)) { buf_varint(aTHX_ b, 0); break; } 0 836 836
730 STRLEN sl;
731 836 const char *ss = SvPV(ev, sl);
732 836 buf_string(aTHX_ b, ss, sl);
733 836 break;
734 }
735 }
736 2006 }
737  
738 /* Emit one scalar value of a Dynamic variant. `val` is assumed defined
739 * (the disc loop has already routed undef rows to disc 0xff). */
740 1849 static void json_emit_scalar(pTHX_ Buffer *b, SV *val, int k_match) {
741 1849 switch (k_match) {
742 230 case JV_BOOL: {
743 230 ▶ SV *bv = SvROK(val) ? SvRV(val) : val;
Branch: 1 branch
BranchTrueFalseTotal
SV *bv = SvROK(val) ? SvRV(val) : val; 228 2 230
744 230 buf_byte(aTHX_ b, SvTRUE(bv) ? 1 : 0);
745 230 break;
746 }
747 746 case JV_INT64:
748 746 buf_le64(aTHX_ b, (uint64_t)(int64_t)SvIV(val));
749 746 break;
750 210 case JV_FLOAT64:
751 210 buf_ledouble(aTHX_ b, SvNV(val));
752 210 break;
753 663 case JV_STRING: {
754 STRLEN sl;
755 663 const char *s = SvPV(val, sl);
756 663 buf_string(aTHX_ b, s, sl);
757 663 break;
758 }
759 0 default: break;
760 }
761 1849 }
762  
763 /* Cap on JSON object nesting: flatten_json_hash recurses once per level,
764 * so an unbounded structure overflows the C stack. Wire data reaches it
765 * too - a path name with N dotted segments decodes to an N-deep hash, so
766 * re-encoding a hostile block recurses just as far. 512 matches the
767 * default max_depth of the common JSON parsers. */
768 #define CHE_MAX_JSON_DEPTH 512
769  
770 /* Recursively flatten a JSON value hash into a flat HV of dotted-path
771 * names. Allocated SVs are mortalized so the caller never has to free
772 * them; the only references stored in `out_flat` are to leaf SVs from
773 * the original hash (which the caller pins).
774 *
775 * If `stop_paths` is non-NULL, it's a HV of dotted-path names to treat
776 * as leaves: when we encounter a hash value at a path in the set, we
777 * store the hashref directly rather than recursing. Used by JSON typed
778 * paths whose declared inner type is a hash-shape (Map / Tuple). */
779 3501 static void flatten_json_hash(pTHX_ HV *src,
780 const char *prefix, STRLEN prefix_len,
781 HV *out_flat, HV *stop_paths, int depth) {
782 3501 ▶ if (++depth > CHE_MAX_JSON_DEPTH)
Branch: 1 branch
BranchTrueFalseTotal
if (++depth > CHE_MAX_JSON_DEPTH) 2 3499 3501
783 2 croak("JSON column: object nesting deeper than %d levels",
784 CHE_MAX_JSON_DEPTH);
785 3499 hv_iterinit(src);
786 HE *he;
787 7278 ▶ while ((he = hv_iternext(src))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(src))) { 4806 2472 7278
788 STRLEN klen;
789 4806 const char *kstr = hash_key_bytes(aTHX_ he, &klen);
790 4806 SV *vsv = hv_iterval(src, he);
791  
792 4806 ▶ STRLEN new_len = prefix_len + (prefix ? 1 : 0) + klen;
Branch: 1 branch
BranchTrueFalseTotal
STRLEN new_len = prefix_len + (prefix ? 1 : 0) + klen; 2228 2578 4806
793 4806 SV *path_sv = sv_2mortal(newSV(new_len + 1));
794 4806 SvPOK_only(path_sv);
795 4806 char *pbuf = SvPVX(path_sv);
796 4806 ▶ if (prefix) {
Branch: 1 branch
BranchTrueFalseTotal
if (prefix) { 2228 2578 4806
797 2228 memcpy(pbuf, prefix, prefix_len);
798 2228 pbuf[prefix_len] = '.';
799 2228 memcpy(pbuf + prefix_len + 1, kstr, klen);
800 } else {
801 2578 memcpy(pbuf, kstr, klen);
802 }
803 4806 SvCUR_set(path_sv, new_len);
804  
805 4806 int stop_here = stop_paths
806 4806 ▶ && hv_exists(stop_paths, SvPVX(path_sv), new_len);
Branch: 2 branches
BranchTrueFalseTotal
&& hv_exists(stop_paths, SvPVX(path_sv), new_len); 40 4766 4806
&& hv_exists(stop_paths, SvPVX(path_sv), new_len); 6 34 40
807  
808 4806 ▶ if (!stop_here
Branch: 1 branch
BranchTrueFalseTotal
if (!stop_here 4800 6 4806
809 4800 ▶ && SvROK(vsv) && SvTYPE(SvRV(vsv)) == SVt_PVHV
Branch: 2 branches
BranchTrueFalseTotal
&& SvROK(vsv) && SvTYPE(SvRV(vsv)) == SVt_PVHV 2961 1839 4800
&& SvROK(vsv) && SvTYPE(SvRV(vsv)) == SVt_PVHV 1883 1078 2961
810 1883 ▶ && !json_is_bool_ref(aTHX_ vsv)) {
Branch: 1 branch
BranchTrueFalseTotal
&& !json_is_bool_ref(aTHX_ vsv)) { 1883 0 1883
811 /* Reject blessed hashrefs that aren't recognized Booleans:
812 * a JSON value of `bless {}, "Custom"` shouldn't silently
813 * flatten as if it were a plain hash. */
814 1883 ▶ if (sv_isobject(vsv))
Branch: 1 branch
BranchTrueFalseTotal
if (sv_isobject(vsv)) 1 1882 1883
815 1 ▶ croak("JSON column: opaque blessed hashref (package '%s') "
Branch: 6 branches
BranchTrueFalseTotal
croak("JSON column: opaque blessed hashref (package '%s') " 1 0 1
croak("JSON column: opaque blessed hashref (package '%s') " 1 0 1
croak("JSON column: opaque blessed hashref (package '%s') " 0 1 1
croak("JSON column: opaque blessed hashref (package '%s') " 0 0 0
croak("JSON column: opaque blessed hashref (package '%s') " 1 0 1
croak("JSON column: opaque blessed hashref (package '%s') " 0 1 1
816 "is not a JSON value; only known Boolean classes "
817 "are accepted as object leaves",
818 HvNAME(SvSTASH(SvRV(vsv))));
819 1882 flatten_json_hash(aTHX_ (HV*)SvRV(vsv),
820 1882 SvPVX(path_sv), new_len, out_flat,
821 stop_paths, depth);
822 } else {
823 2923 ▶ UV count = HvUSEDKEYS(out_flat);
Branch: 1 branch
BranchTrueFalseTotal
UV count = HvUSEDKEYS(out_flat); 0 2923 2923
824 2923 hv_store(out_flat, SvPVX(path_sv), new_len,
825 SvREFCNT_inc_simple_NN(vsv), 0);
826 2923 ▶ if (HvUSEDKEYS(out_flat) == count)
Branch: 2 branches
BranchTrueFalseTotal
if (HvUSEDKEYS(out_flat) == count) 0 2923 2923
if (HvUSEDKEYS(out_flat) == count) 1 2922 2923
827 1 croak("JSON column: duplicate path '%.*s' in one object", (int)new_len, SvPVX(path_sv));
828 }
829 }
830 2472 }
831  
832 /* (path, len) pair: lets the JSON encoder sort paths whose keys may
833 * contain embedded NUL bytes without falling back to strlen() after
834 * sort. Perl HV keys are NUL-terminated but the value bytes themselves
835 * are arbitrary, so we carry both together. */
836 typedef struct { char *path; STRLEN len; } PathEntry;
837  
838 5524 static int cmp_path_entry(const void *a, const void *b) {
839 5524 const PathEntry *pa = (const PathEntry *)a;
840 5524 const PathEntry *pb = (const PathEntry *)b;
841 5524 STRLEN n = pa->len < pb->len ? pa->len : pb->len;
842 5524 int r = memcmp(pa->path, pb->path, n);
843 5524 ▶ if (r) return r;
Branch: 1 branch
BranchTrueFalseTotal
if (r) return r; 5459 65 5524
844 65 ▶ if (pa->len < pb->len) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (pa->len < pb->len) return -1; 35 30 65
845 30 ▶ if (pa->len > pb->len) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (pa->len > pb->len) return 1; 30 0 30
846 0 return 0;
847 }
848  
849 static void encode_column_data(pTHX_ Buffer *b, Buffer *prefix,
850 SV **values, SSize_t num_rows, TypeInfo *t);
851  
852 2227 void encode_column(pTHX_ Buffer *b, SV **values, SSize_t num_rows, TypeInfo *t) {
853 2227 ▶ if (!num_rows) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!num_rows) return; 78 2149 2227
854 2149 ▶ if (t->split_prefix) {
Branch: 1 branch
BranchTrueFalseTotal
if (t->split_prefix) { 20 2129 2149
855 Buffer data;
856 20 buf_init(aTHX_ &data);
857 20 encode_column_data(aTHX_ &data, b, values, num_rows, t);
858 20 buf_append(aTHX_ b, data.ptr, data.len);
859 } else {
860 2129 encode_column_data(aTHX_ b, b, values, num_rows, t);
861 }
862 }
863  
864 /* Native writes every state prefix before any container or value data. */
865 6045 static void encode_column_data(pTHX_ Buffer *b, Buffer *prefix,
866 SV **values, SSize_t num_rows, TypeInfo *t) {
867 SSize_t r;
868  
869 6045 switch (t->code) {
870 1885 case T_INT8: case T_INT16: case T_INT32: case T_INT64:
871 case T_UINT8: case T_UINT16: case T_UINT32: case T_UINT64:
872 case T_FLOAT32: case T_FLOAT64: case T_BFLOAT16:
873 case T_STRING: case T_FIXEDSTRING:
874 case T_ENUM8: case T_ENUM16:
875 case T_DECIMAL32: case T_DECIMAL64: case T_DECIMAL128: case T_DECIMAL256:
876 case T_DATE: case T_DATE32: case T_DATETIME: case T_DATETIME64:
877 case T_BOOL: case T_UUID: case T_IPV4: case T_IPV6:
878 351020 ▶ for (r = 0; r < num_rows; r++) encode_scalar(aTHX_ b,values[r], t);
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) encode_scalar(aTHX_ b,values[r], t); 349149 1871 351020
879 1871 break;
880  
881 1613 case T_ARRAY: {
882 1613 uint64_t offset = 0;
883 1613 SSize_t total_elems = 0;
884  
885 96692 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 95080 1612 96692
886 95080 SV *val = values[r];
887 95080 ▶ if (empty_container(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (empty_container(val)) { 15 95065 95080
888 15 buf_le64(aTHX_ b, offset);
889 15 continue;
890 }
891 95065 ▶ if (!SvROK(val) || SvTYPE(SvRV(val)) != SVt_PVAV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(val) || SvTYPE(SvRV(val)) != SVt_PVAV) 95064 1 95065
if (!SvROK(val) || SvTYPE(SvRV(val)) != SVt_PVAV) 0 95064 95064
892 1 croak("Expected arrayref for Array type");
893 95064 AV *av = (AV*)SvRV(val);
894 95064 SSize_t n = av_len(av) + 1;
895 95064 offset += (uint64_t)n;
896 95064 total_elems += n;
897 95064 buf_le64(aTHX_ b,offset);
898 }
899  
900 1612 ▶ if (total_elems > 0 || t->inner->has_prefix) {
Branch: 2 branches
BranchTrueFalseTotal
if (total_elems > 0 || t->inner->has_prefix) { 63 1549 1612
if (total_elems > 0 || t->inner->has_prefix) { 3 60 63
901 1552 SV **all_elems = alloc_sv_array(aTHX_ total_elems);
902 1552 SSize_t idx = 0;
903 96559 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 95007 1552 96559
904 95007 ▶ if (empty_container(values[r])) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (empty_container(values[r])) continue; 6 95001 95007
905 95001 AV *av = (AV*)SvRV(values[r]);
906 95001 SSize_t n = av_len(av) + 1;
907 SSize_t i;
908 374541 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 279540 95001 374541
909 279540 SV **elem = av_fetch(av, i, 0);
910 279540 ▶ all_elems[idx++] = elem ? *elem : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
all_elems[idx++] = elem ? *elem : &PL_sv_undef; 279540 0 279540
911 }
912 }
913 1552 encode_column_data(aTHX_ b, prefix, all_elems, total_elems, t->inner);
914 }
915 1609 break;
916 }
917  
918 1076 case T_TUPLE: {
919 1076 ▶ if (!t->tuple_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (!t->tuple_len) { 1 1075 1076
920 1 buf_grow(aTHX_ b, num_rows);
921 1 memset(b->ptr + b->len, 0x30, num_rows);
922 1 b->len += num_rows;
923 1 break;
924 }
925 int i;
926 1075 SV **elem_values = alloc_sv_array(aTHX_ num_rows);
927  
928 3221 ▶ for (i = 0; i < t->tuple_len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < t->tuple_len; i++) { 2150 1071 3221
929 6457 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 4309 2148 6457
930 4309 SV *val = values[r];
931 4309 ▶ if (!SvROK(val))
Branch: 1 branch
BranchTrueFalseTotal
if (!SvROK(val)) 1 4308 4309
932 1 croak("Expected arrayref or hashref for Tuple type");
933 4308 SV *rv = SvRV(val);
934 4308 ▶ if (SvTYPE(rv) == SVt_PVAV) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvTYPE(rv) == SVt_PVAV) { 4300 8 4308
935 4300 SV **elem = av_fetch((AV*)rv, i, 0);
936 4300 ▶ elem_values[r] = elem ? *elem : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
elem_values[r] = elem ? *elem : &PL_sv_undef; 4300 0 4300
937 8 ▶ } else if (SvTYPE(rv) == SVt_PVHV
Branch: 1 branch
BranchTrueFalseTotal
} else if (SvTYPE(rv) == SVt_PVHV 8 0 8
938 8 ▶ && t->tuple_names && t->tuple_names[i]) {
Branch: 2 branches
BranchTrueFalseTotal
&& t->tuple_names && t->tuple_names[i]) { 7 1 8
&& t->tuple_names && t->tuple_names[i]) { 7 0 7
939 /* Named-tuple input as hashref: look up by name. */
940 7 SV **elem = fetch_named_value(aTHX_ (HV*)rv, t->tuple_names[i],
941 7 strlen(t->tuple_names[i]));
942 7 ▶ elem_values[r] = elem ? *elem : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
elem_values[r] = elem ? *elem : &PL_sv_undef; 6 1 7
943 1 ▶ } else if (SvTYPE(rv) == SVt_PVHV) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (SvTYPE(rv) == SVt_PVHV) { 1 0 1
944 1 croak("Tuple given as hashref but type is unnamed; "
945 "use arrayref or declare named Tuple(name Type, ...)");
946 } else {
947 0 croak("Expected arrayref or hashref for Tuple type");
948 }
949 }
950 2148 encode_column_data(aTHX_ b, prefix, elem_values, num_rows, t->tuple[i]);
951 }
952 1071 break;
953 }
954  
955 1056 case T_NULLABLE: {
956 3195 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 2139 1056 3195
957 2139 buf_byte(aTHX_ b, nullable_is_null(values[r], t) ? 1 : 0);
958 }
959  
960 1056 ▶ if (is_simple_type(t->inner)) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_simple_type(t->inner)) { 1042 14 1056
961 3139 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 2101 1038 3139
962 2101 ▶ if (nullable_is_null(values[r], t)) encode_null_scalar(aTHX_ b, t->inner);
Branch: 1 branch
BranchTrueFalseTotal
if (nullable_is_null(values[r], t)) encode_null_scalar(aTHX_ b, t->inner); 1054 1047 2101
963 1047 else encode_scalar(aTHX_ b,values[r], t->inner);
964 }
965 } else {
966 14 SV **inner_values = alloc_sv_array(aTHX_ num_rows);
967 52 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 38 14 52
968 38 ▶ if (nullable_is_null(values[r], t))
Branch: 1 branch
BranchTrueFalseTotal
if (nullable_is_null(values[r], t)) 15 23 38
969 15 inner_values[r] = make_null_placeholder(aTHX_ t->inner);
970 else
971 23 inner_values[r] = values[r];
972 }
973 14 encode_column_data(aTHX_ b, prefix, inner_values, num_rows, t->inner);
974 }
975 1052 break;
976 }
977  
978 41 case T_MAP: {
979 /* Wire format is identical to Array(Tuple(K, V)). Each row's value
980 * is either a hashref or arrayref-of-pairs; normalize to a flat
981 * arrayref of [k, v] pairs and reuse the Array(Tuple) path. */
982 41 SV **norm = alloc_sv_array(aTHX_ num_rows);
983 914 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 874 40 914
984 874 SV *val = values[r];
985 874 ▶ if (empty_container(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (empty_container(val)) { 10 864 874
986 10 norm[r] = sv_2mortal(newRV_noinc((SV *)newAV()));
987 10 continue;
988 }
989 864 ▶ if (!SvROK(val))
Branch: 1 branch
BranchTrueFalseTotal
if (!SvROK(val)) 1 863 864
990 1 croak("Expected hashref or arrayref for Map type");
991 863 SV *rv = SvRV(val);
992 863 ▶ if (SvTYPE(rv) == SVt_PVAV) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvTYPE(rv) == SVt_PVAV) { 50 813 863
993 50 norm[r] = val; /* already arrayref-of-pairs */
994 813 ▶ } else if (SvTYPE(rv) == SVt_PVHV) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (SvTYPE(rv) == SVt_PVHV) { 813 0 813
995 813 HV *hv = (HV *)rv;
996 813 AV *pairs = newAV();
997 813 hv_iterinit(hv);
998 HE *he;
999 2030 ▶ while ((he = hv_iternext(hv))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(hv))) { 1217 813 2030
1000 1217 SV *vsv = hv_iterval(hv, he);
1001 1217 AV *pair = newAV();
1002 STRLEN klen;
1003 1217 const char *kstr = hash_key_bytes(aTHX_ he, &klen);
1004 1217 av_push(pair, newSVpvn(kstr, klen));
1005 1217 av_push(pair, SvREFCNT_inc(vsv));
1006 1217 av_push(pairs, newRV_noinc((SV *)pair));
1007 }
1008 813 norm[r] = sv_2mortal(newRV_noinc((SV *)pairs));
1009 } else {
1010 0 croak("Expected hashref or arrayref for Map type");
1011 }
1012 }
1013  
1014 /* Synthesize the Array(Tuple(K,V)) wire path. */
1015 40 uint64_t offset = 0;
1016 40 SSize_t total = 0;
1017 913 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 873 40 913
1018 873 AV *av = (AV *)SvRV(norm[r]);
1019 873 SSize_t n = av_len(av) + 1;
1020 873 offset += (uint64_t)n;
1021 873 total += n;
1022 873 buf_le64(aTHX_ b, offset);
1023 }
1024 40 ▶ if (total > 0 || t->split_prefix) {
Branch: 2 branches
BranchTrueFalseTotal
if (total > 0 || t->split_prefix) { 17 23 40
if (total > 0 || t->split_prefix) { 0 17 17
1025 23 SV **all = alloc_sv_array(aTHX_ total);
1026 23 SSize_t idx = 0;
1027 870 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 847 23 870
1028 847 AV *av = (AV *)SvRV(norm[r]);
1029 847 SSize_t n = av_len(av) + 1;
1030 SSize_t i;
1031 2087 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 1240 847 2087
1032 1240 SV **elem = av_fetch(av, i, 0);
1033 1240 ▶ all[idx++] = elem ? *elem : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
all[idx++] = elem ? *elem : &PL_sv_undef; 1240 0 1240
1034 }
1035 }
1036 /* Encode as Tuple(K, V): first all keys, then all values. */
1037 int j;
1038 69 ▶ for (j = 0; j < 2; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < 2; j++) { 46 23 69
1039 46 SV **col = alloc_sv_array(aTHX_ total);
1040 SSize_t k;
1041 2526 ▶ for (k = 0; k < total; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < total; k++) { 2480 46 2526
1042 2480 ▶ if (!SvROK(all[k]) || SvTYPE(SvRV(all[k])) != SVt_PVAV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(all[k]) || SvTYPE(SvRV(all[k])) != SVt_PVAV) 2480 0 2480
if (!SvROK(all[k]) || SvTYPE(SvRV(all[k])) != SVt_PVAV) 0 2480 2480
1043 0 croak("Map pair must be a 2-element arrayref");
1044 2480 AV *pair = (AV *)SvRV(all[k]);
1045 2480 SV **e = av_fetch(pair, j, 0);
1046 2480 ▶ col[k] = e ? *e : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
col[k] = e ? *e : &PL_sv_undef; 2480 0 2480
1047 }
1048 46 encode_column_data(aTHX_ b, prefix, col, total, t->tuple[j]);
1049 }
1050 }
1051 40 break;
1052 }
1053  
1054 26 case T_VARIANT: {
1055 /* Variant wire format (CH 24.1+):
1056 * UInt64 LE mode = 0 (non-shared serialization)
1057 * UInt8[N] wire discriminators (255 = NULL, else 0..n-1
1058 * referring to the alphabetical-order position)
1059 * <sub-cols> one per variant, in alphabetical order of type
1060 * names; each contains the values whose
1061 * discriminator equals that variant's wire index
1062 *
1063 * The user passes [decl_idx, value] using declaration order;
1064 * variant_decl_to_wire[d] / variant_wire_to_decl[w] handle
1065 * the alphabetical reordering ClickHouse requires. */
1066 26 int nvar = t->tuple_len;
1067 #define VARIANT_NULL 255
1068  
1069 26 buf_le64(aTHX_ prefix, 0);
1070  
1071 int *counts; /* indexed by declaration idx */
1072 26 Newxz(counts, nvar, int);
1073 26 SAVEFREEPV(counts);
1074 SV ***per_var; /* per_var[decl_idx] = values for that variant */
1075 26 Newxz(per_var, nvar, SV **);
1076 26 SAVEFREEPV(per_var);
1077 int v;
1078 80 ▶ for (v = 0; v < nvar; v++)
Branch: 1 branch
BranchTrueFalseTotal
for (v = 0; v < nvar; v++) 54 26 80
1079 54 per_var[v] = alloc_sv_array(aTHX_ num_rows);
1080  
1081 77 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 56 21 77
1082 56 SV *val = values[r];
1083 56 ▶ if (!SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) { 22 34 56
1084 22 buf_byte(aTHX_ b, VARIANT_NULL);
1085 22 continue;
1086 }
1087 34 ▶ if (!SvROK(val) || SvTYPE(SvRV(val)) != SVt_PVAV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(val) || SvTYPE(SvRV(val)) != SVt_PVAV) 32 2 34
if (!SvROK(val) || SvTYPE(SvRV(val)) != SVt_PVAV) 0 32 32
1088 2 croak("Variant value must be undef or [variant_idx, value]");
1089 32 AV *av = (AV *)SvRV(val);
1090 32 ▶ if (av_len(av) + 1 != 2)
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(av) + 1 != 2) 1 31 32
1091 1 croak("Variant value must be a 2-element [idx, value] pair");
1092 31 SV **idx_sv = av_fetch(av, 0, 0);
1093 31 SV **vsv = av_fetch(av, 1, 0);
1094 31 ▶ IV idx = idx_sv ? SvIV(*idx_sv) : -1;
Branch: 1 branch
BranchTrueFalseTotal
IV idx = idx_sv ? SvIV(*idx_sv) : -1; 31 0 31
1095 31 ▶ if (idx < 0 || idx >= nvar)
Branch: 2 branches
BranchTrueFalseTotal
if (idx < 0 || idx >= nvar) 31 0 31
if (idx < 0 || idx >= nvar) 2 29 31
1096 2 croak("Variant index %" IVdf " out of range (0..%d)",
1097 idx, nvar - 1);
1098 29 buf_byte(aTHX_ b, (uint8_t)t->variant_decl_to_wire[idx]);
1099 29 ▶ per_var[idx][counts[idx]++] = vsv ? *vsv : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
per_var[idx][counts[idx]++] = vsv ? *vsv : &PL_sv_undef; 29 0 29
1100 }
1101  
1102 /* Emit sub-columns in wire (alphabetical) order. */
1103 65 ▶ for (v = 0; v < nvar; v++) {
Branch: 1 branch
BranchTrueFalseTotal
for (v = 0; v < nvar; v++) { 44 21 65
1104 44 int d = t->variant_wire_to_decl[v];
1105 44 encode_column_data(aTHX_ b, prefix, per_var[d], counts[d], t->tuple[d]);
1106 }
1107 #undef VARIANT_NULL
1108 21 break;
1109 }
1110  
1111 85 case T_LOWCARDINALITY: {
1112 /* LowCardinality block format (per ClickHouse Native protocol):
1113 * UInt64 LE serialization version (= 1)
1114 * UInt64 LE flags: HasAdditionalKeys(=1<<9) | index-type-bits(0..3)
1115 * UInt64 LE dictionary keys count
1116 * <dict> keys serialized using the inner type's column format
1117 * UInt64 LE index count (= num_rows)
1118 * <indices> packed UInt8/16/32/64 according to flags low byte
1119 *
1120 * For Nullable(T) the underlying inner type for serialization is
1121 * the bare T; NULL is represented by reserving dictionary index 0
1122 * (which always carries the "default" value) and the wire format
1123 * for the actual non-NULL dict starts at index 1.
1124 */
1125 85 buf_le64(aTHX_ prefix, 1);
1126 85 ▶ if (!num_rows) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!num_rows) break; 1 84 85
1127 84 TypeInfo *inner = t->inner;
1128 84 int is_null = (inner->code == T_NULLABLE);
1129 84 ▶ TypeInfo *leaf = is_null ? inner->inner : inner;
Branch: 1 branch
BranchTrueFalseTotal
TypeInfo *leaf = is_null ? inner->inner : inner; 34 50 84
1130 84 ▶ int numeric = leaf->code != T_STRING && leaf->code != T_FIXEDSTRING;
Branch: 2 branches
BranchTrueFalseTotal
int numeric = leaf->code != T_STRING && leaf->code != T_FIXEDSTRING; 28 56 84
int numeric = leaf->code != T_STRING && leaf->code != T_FIXEDSTRING; 17 11 28
1131 Buffer key_buf;
1132 84 ▶ if (numeric) buf_init(aTHX_ &key_buf);
Branch: 1 branch
BranchTrueFalseTotal
if (numeric) buf_init(aTHX_ &key_buf); 17 67 84
1133  
1134 84 HV *seen = (HV *)sv_2mortal((SV *)newHV());
1135 84 AV *dict_av = (AV *)sv_2mortal((SV *)newAV());
1136  
1137 /* For FixedString(N) inner, dedup by the canonical N-byte form
1138 * (truncate or zero-pad) so inputs of different length that
1139 * encode to the same wire bytes collapse into one dict slot. */
1140 84 ▶ int fixed_n = (leaf->code == T_FIXEDSTRING) ? leaf->param : 0;
Branch: 1 branch
BranchTrueFalseTotal
int fixed_n = (leaf->code == T_FIXEDSTRING) ? leaf->param : 0; 11 73 84
1141 84 SV *canon_holder = NULL;
1142 84 ▶ if (fixed_n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (fixed_n > 0) { 11 73 84
1143 11 canon_holder = sv_2mortal(newSV(fixed_n));
1144 11 SvPOK_only(canon_holder);
1145 11 SvCUR_set(canon_holder, fixed_n);
1146 }
1147  
1148 /* Reserve dict slot 0. For Nullable inner this slot is the NULL
1149 * sentinel and must not be reused for the literal default value;
1150 * for non-Nullable it IS the default (empty / N-zero-bytes). */
1151 84 ▶ av_push(dict_av, numeric ? newSVsv(make_null_placeholder(aTHX_ leaf))
Branch: 1 branch
BranchTrueFalseTotal
av_push(dict_av, numeric ? newSVsv(make_null_placeholder(aTHX_ leaf)) 17 67 84
1152 : newSVpvn("", 0));
1153 84 ▶ if (!is_null) {
Branch: 1 branch
BranchTrueFalseTotal
if (!is_null) { 50 34 84
1154 50 ▶ if (numeric) {
Branch: 1 branch
BranchTrueFalseTotal
if (numeric) { 5 45 50
1155 5 encode_scalar(aTHX_ &key_buf, *av_fetch(dict_av, 0, 0), leaf);
1156 5 hv_store(seen, key_buf.ptr, key_buf.len, newSViv(0), 0);
1157 45 ▶ } else if (fixed_n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (fixed_n > 0) { 1 44 45
1158 1 char *cz = SvPVX(canon_holder);
1159 1 memset(cz, 0, fixed_n);
1160 1 hv_store(seen, cz, fixed_n, newSViv(0), 0);
1161 } else {
1162 44 hv_store(seen, "", 0, newSViv(0), 0);
1163 }
1164 }
1165  
1166 /* Pre-allocate index buffer. */
1167 84 STRLEN idx_buf_len = num_rows * sizeof(uint64_t);
1168 84 SV *idx_sv = sv_2mortal(newSV(idx_buf_len));
1169 84 SvPOK_only(idx_sv);
1170 84 SvCUR_set(idx_sv, idx_buf_len);
1171 84 uint64_t *indices = (uint64_t *)SvPVX(idx_sv);
1172  
1173 67580 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 67514 66 67580
1174 67514 SV *val = values[r];
1175 67514 ▶ if (is_null && nullable_is_null(val, inner)) {
Branch: 2 branches
BranchTrueFalseTotal
if (is_null && nullable_is_null(val, inner)) { 379 67135 67514
if (is_null && nullable_is_null(val, inner)) { 30 349 379
1176 30 indices[r] = 0;
1177 30 continue;
1178 }
1179 67484 ▶ if (!SvOK(val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) { 3 67481 67484
1180 /* Nullable: slot 0 is the NULL sentinel. Non-nullable:
1181 * coerce undef to empty string (matches plain String
1182 * behaviour) without invoking SvPV on undef, which
1183 * would emit a "Use of uninitialized value" warning. */
1184 3 ▶ if (is_null) { indices[r] = 0; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (is_null) { indices[r] = 0; continue; } 0 3 3
1185 3 val = make_null_placeholder(aTHX_ leaf);
1186 }
1187 67484 ▶ if (!numeric) check_string_reference(aTHX_ val, leaf);
Branch: 1 branch
BranchTrueFalseTotal
if (!numeric) check_string_reference(aTHX_ val, leaf); 67464 20 67484
1188 67468 STRLEN slen = 0;
1189 134916 ▶ const char *s = numeric ? NULL : SvPV(val, slen);
Branch: 1 branch
BranchTrueFalseTotal
const char *s = numeric ? NULL : SvPV(val, slen); 67448 20 67468
1190 const char *key;
1191 STRLEN klen;
1192 67468 ▶ if (numeric) {
Branch: 1 branch
BranchTrueFalseTotal
if (numeric) { 20 67448 67468
1193 20 key_buf.len = 0;
1194 20 encode_scalar(aTHX_ &key_buf, val, leaf);
1195 18 key = key_buf.ptr;
1196 18 klen = key_buf.len;
1197 67448 ▶ } else if (fixed_n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (fixed_n > 0) { 8 67440 67448
1198 /* Canonicalize to exactly N bytes: truncate or zero-pad. */
1199 8 char *cz = SvPVX(canon_holder);
1200 8 ▶ if (slen >= (STRLEN)fixed_n) {
Branch: 1 branch
BranchTrueFalseTotal
if (slen >= (STRLEN)fixed_n) { 7 1 8
1201 7 memcpy(cz, s, fixed_n);
1202 } else {
1203 1 memcpy(cz, s, slen);
1204 1 memset(cz + slen, 0, fixed_n - slen);
1205 }
1206 8 key = cz;
1207 8 klen = fixed_n;
1208 } else {
1209 67440 key = s;
1210 67440 klen = slen;
1211 }
1212 67466 SV **slot_sv = hv_fetch(seen, key, klen, 0);
1213 67466 ▶ if (slot_sv) {
Branch: 1 branch
BranchTrueFalseTotal
if (slot_sv) { 744 66722 67466
1214 744 indices[r] = (uint64_t)SvUV(*slot_sv);
1215 } else {
1216 66722 UV pos = (UV)(av_len(dict_av) + 1);
1217 66722 ▶ av_push(dict_av, numeric ? newSVsv(val) : newSVpvn(key, klen));
Branch: 1 branch
BranchTrueFalseTotal
av_push(dict_av, numeric ? newSVsv(val) : newSVpvn(key, klen)); 12 66710 66722
1218 66722 hv_store(seen, key, klen, newSVuv(pos), 0);
1219 66722 indices[r] = (uint64_t)pos;
1220 }
1221 }
1222  
1223 66 UV dict_count = av_len(dict_av) + 1;
1224 int idx_bytes;
1225 int idx_type;
1226 66 ▶ if (dict_count <= 256) { idx_type = 0; idx_bytes = 1; }
Branch: 1 branch
BranchTrueFalseTotal
if (dict_count <= 256) { idx_type = 0; idx_bytes = 1; } 62 4 66
1227 4 ▶ else if (dict_count <= 65536) { idx_type = 1; idx_bytes = 2; }
Branch: 1 branch
BranchTrueFalseTotal
else if (dict_count <= 65536) { idx_type = 1; idx_bytes = 2; } 4 0 4
1228 0 ▶ else if (dict_count <= 0xFFFFFFFF) { idx_type = 2; idx_bytes = 4; }
Branch: 1 branch
BranchTrueFalseTotal
else if (dict_count <= 0xFFFFFFFF) { idx_type = 2; idx_bytes = 4; } 0 0 0
1229 0 else { idx_type = 3; idx_bytes = 8; }
1230  
1231 66 uint64_t flags = (uint64_t)idx_type | (1ULL << 9); /* HasAdditionalKeys */
1232  
1233 66 buf_le64(aTHX_ b, flags);
1234 66 buf_le64(aTHX_ b, (uint64_t)dict_count);
1235  
1236 /* Serialize the dict using the leaf type. */
1237 66 SV **dict_vals = alloc_sv_array(aTHX_ (SSize_t)dict_count);
1238 SSize_t di;
1239 66854 ▶ for (di = 0; di < (SSize_t)dict_count; di++) {
Branch: 1 branch
BranchTrueFalseTotal
for (di = 0; di < (SSize_t)dict_count; di++) { 66788 66 66854
1240 66788 SV **e = av_fetch(dict_av, di, 0);
1241 66788 ▶ dict_vals[di] = e ? *e : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
dict_vals[di] = e ? *e : &PL_sv_undef; 66788 0 66788
1242 }
1243 66 encode_column_data(aTHX_ b, prefix, dict_vals, (SSize_t)dict_count, leaf);
1244  
1245 66 buf_le64(aTHX_ b, (uint64_t)num_rows);
1246  
1247 67562 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 67496 66 67562
1248 67496 uint64_t v = indices[r];
1249 67496 switch (idx_bytes) {
1250 403 case 1: buf_byte(aTHX_ b, (uint8_t)v); break;
1251 67093 case 2: buf_le16(aTHX_ b, (uint16_t)v); break;
1252 0 case 4: buf_le32(aTHX_ b, (uint32_t)v); break;
1253 0 case 8: buf_le64(aTHX_ b, v); break;
1254 }
1255 }
1256 66 break;
1257 }
1258  
1259 247 case T_JSON: {
1260 /* Per doc/json-research/README.md (validated byte-for-byte
1261 * against ClickHouse 26.3). Wire layout (V1):
1262 * Object prefix: UInt64=0, varint K (twice for V1),
1263 * K * lenstr path -- K = dynamic paths
1264 * For each typed path (sorted): inner prefix (empty for simple types)
1265 * For each dynamic path: Dynamic prefix (UInt64=1, varint T x2,
1266 * T * lenstr type-name, UInt64=0)
1267 * SharedData prefix: empty for MAP version
1268 * For each typed path (sorted): inner column data
1269 * For each dynamic path: N disc bytes + per-variant data
1270 * Shared data: N * UInt64 LE zero
1271 *
1272 * t->tuple_len > 0 means JSON(name Type, ...) was declared:
1273 * those paths emit as regular columns, the rest as Dynamic.
1274 */
1275  
1276 /* Step 1: flatten each row's hashref to dotted-path leaves.
1277 * Typed paths whose declared inner type is itself a hash
1278 * shape (Map / Tuple) must not be recursed into during
1279 * flatten - the user's nested hash for those is the leaf
1280 * value, not a sub-object. Build a stop-set of those names
1281 * and pass it to flatten so it stops recursing at them. */
1282 247 HV *stop_paths = NULL;
1283 247 ▶ if (t->tuple_len > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (t->tuple_len > 0) { 18 229 247
1284 18 stop_paths = (HV*)sv_2mortal((SV*)newHV());
1285 int sk;
1286 44 ▶ for (sk = 0; sk < t->tuple_len; sk++) {
Branch: 1 branch
BranchTrueFalseTotal
for (sk = 0; sk < t->tuple_len; sk++) { 26 18 44
1287 /* Unwrap Nullable so JSON(x Nullable(Map(...))) also
1288 * stops at "x" rather than flattening the inner
1289 * hash and losing the user's data. */
1290 26 TypeInfo *inner = t->tuple[sk];
1291 26 ▶ if (inner->code == T_NULLABLE) inner = inner->inner;
Branch: 1 branch
BranchTrueFalseTotal
if (inner->code == T_NULLABLE) inner = inner->inner; 2 24 26
1292 26 ▶ if (inner->code == T_MAP || inner->code == T_TUPLE) {
Branch: 2 branches
BranchTrueFalseTotal
if (inner->code == T_MAP || inner->code == T_TUPLE) { 23 3 26
if (inner->code == T_MAP || inner->code == T_TUPLE) { 3 20 23
1293 6 STRLEN nlen = strlen(t->tuple_names[sk]);
1294 6 hv_store(stop_paths, t->tuple_names[sk],
1295 (I32)nlen, newSViv(1), 0);
1296 }
1297 }
1298 }
1299  
1300 247 HV **row_hvs = NULL;
1301 247 ▶ if (num_rows > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (num_rows > 0) { 246 1 247
1302 246 ▶ Newxz(row_hvs, num_rows, HV*);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(row_hvs, num_rows, HV*); 0 246 246
1303 246 SAVEFREEPV(row_hvs);
1304 }
1305 247 HV *all_paths = (HV*)sv_2mortal((SV*)newHV());
1306  
1307 2003 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 1761 242 2003
1308 1761 SV *val = values[r];
1309 1761 ▶ if (!SvOK(val)) { row_hvs[r] = NULL; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) { row_hvs[r] = NULL; continue; } 141 1620 1761
1310 1620 ▶ if (!SvROK(val) || SvTYPE(SvRV(val)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(val) || SvTYPE(SvRV(val)) != SVt_PVHV) 1619 1 1620
if (!SvROK(val) || SvTYPE(SvRV(val)) != SVt_PVHV) 0 1619 1619
1311 1 croak("JSON column row %" IVdf
1312 ": must be hashref or undef", (IV)r);
1313 1619 HV *flat = (HV*)sv_2mortal((SV*)newHV());
1314 1619 flatten_json_hash(aTHX_ (HV*)SvRV(val), NULL, 0, flat,
1315 stop_paths, 0);
1316 1615 row_hvs[r] = flat;
1317 }
1318  
1319 /* Step 1b: if typed paths are declared, extract their values
1320 * per row from each flat HV (and hv_delete to keep them out
1321 * of the dynamic-paths discovery below). For missing keys
1322 * we substitute a type-appropriate placeholder: undef for
1323 * Nullable/Variant, [] for Array/Map, "" for String, 0 for
1324 * numerics. The inner encoder then emits the default
1325 * bytes the same way it would for any other column. */
1326 242 SV ***typed_vals = NULL;
1327 242 int n_typed = t->tuple_len;
1328 242 ▶ if (n_typed > 0 && num_rows > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (n_typed > 0 && num_rows > 0) { 18 224 242
if (n_typed > 0 && num_rows > 0) { 18 0 18
1329 18 Newxz(typed_vals, n_typed, SV **);
1330 18 SAVEFREEPV(typed_vals);
1331 int tp;
1332 44 ▶ for (tp = 0; tp < n_typed; tp++) {
Branch: 1 branch
BranchTrueFalseTotal
for (tp = 0; tp < n_typed; tp++) { 26 18 44
1333 26 typed_vals[tp] = alloc_sv_array(aTHX_ num_rows);
1334 26 STRLEN nlen = strlen(t->tuple_names[tp]);
1335 52 SV *missing = (t->tuple[tp]->code == T_NULLABLE)
1336 ? &PL_sv_undef
1337 26 ▶ : make_null_placeholder(aTHX_ t->tuple[tp]);
Branch: 1 branch
BranchTrueFalseTotal
: make_null_placeholder(aTHX_ t->tuple[tp]); 24 2 26
1338 76 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 50 26 76
1339 50 ▶ if (!row_hvs[r]) {
Branch: 1 branch
BranchTrueFalseTotal
if (!row_hvs[r]) { 0 50 50
1340 0 typed_vals[tp][r] = missing;
1341 0 continue;
1342 }
1343 50 SV **e = hv_fetch(row_hvs[r], t->tuple_names[tp],
1344 (I32)nlen, 0);
1345 50 ▶ if (e) {
Branch: 1 branch
BranchTrueFalseTotal
if (e) { 36 14 50
1346 36 ▶ typed_vals[tp][r] = SvOK(*e) ? *e : missing;
Branch: 1 branch
BranchTrueFalseTotal
typed_vals[tp][r] = SvOK(*e) ? *e : missing; 33 3 36
1347 /* hv_delete unconditionally on key presence
1348 * so an explicit `undef` value doesn't leak
1349 * into the dynamic-paths discovery below
1350 * (would double-emit the path). */
1351 36 hv_delete(row_hvs[r], t->tuple_names[tp],
1352 (I32)nlen, G_DISCARD);
1353 } else {
1354 14 typed_vals[tp][r] = missing;
1355 }
1356 }
1357 }
1358 }
1359  
1360 /* Step 1c: union remaining dynamic-path keys across rows. */
1361 1998 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 1756 242 1998
1362 1756 ▶ if (!row_hvs[r]) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!row_hvs[r]) continue; 141 1615 1756
1363 1615 hv_iterinit(row_hvs[r]);
1364 HE *he;
1365 4500 ▶ while ((he = hv_iternext(row_hvs[r]))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(row_hvs[r]))) { 2885 1615 4500
1366 I32 klen;
1367 2885 char *kstr = hv_iterkey(he, &klen);
1368 2885 SV **e = hv_fetch(row_hvs[r], kstr, klen, 0);
1369 2885 ▶ if (e && SvOK(*e))
Branch: 2 branches
BranchTrueFalseTotal
if (e && SvOK(*e)) 2885 0 2885
if (e && SvOK(*e)) 2674 211 2885
1370 2674 hv_store(all_paths, kstr, klen, newSViv(1), 0);
1371 }
1372 }
1373  
1374 /* Step 2: collect & sort path names. Snapshot (ptr, len) into
1375 * a paired struct array so the sort preserves the original
1376 * length even if a key contains an embedded NUL byte (legal
1377 * in Perl HVs; strlen() after sort would silently truncate). */
1378 242 int num_paths = 0;
1379 242 char **paths = NULL;
1380 242 STRLEN *path_lens = NULL;
1381 {
1382 242 ▶ int total = (int)HvUSEDKEYS(all_paths);
Branch: 1 branch
BranchTrueFalseTotal
int total = (int)HvUSEDKEYS(all_paths); 0 242 242
1383 242 ▶ if (total > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (total > 0) { 221 21 242
1384 221 Newx(paths, total, char*);
1385 221 SAVEFREEPV(paths);
1386 221 Newx(path_lens, total, STRLEN);
1387 221 SAVEFREEPV(path_lens);
1388 PathEntry *pe;
1389 221 Newx(pe, total, PathEntry);
1390 221 SAVEFREEPV(pe);
1391 221 hv_iterinit(all_paths);
1392 HE *he;
1393 2312 ▶ while ((he = hv_iternext(all_paths))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(all_paths))) { 2091 221 2312
1394 I32 klen;
1395 2091 char *kstr = hv_iterkey(he, &klen);
1396 2091 pe[num_paths].path = kstr;
1397 2091 pe[num_paths].len = (STRLEN)klen;
1398 2091 num_paths++;
1399 }
1400 221 ▶ if (num_paths > 1)
Branch: 1 branch
BranchTrueFalseTotal
if (num_paths > 1) 192 29 221
1401 192 qsort(pe, num_paths, sizeof(*pe), cmp_path_entry);
1402 int pi;
1403 2312 ▶ for (pi = 0; pi < num_paths; pi++) {
Branch: 1 branch
BranchTrueFalseTotal
for (pi = 0; pi < num_paths; pi++) { 2091 221 2312
1404 2091 paths[pi] = pe[pi].path;
1405 2091 path_lens[pi] = pe[pi].len;
1406 }
1407 }
1408 }
1409  
1410 /* Step 3: per-path kind mask. Walk each leaf; scalars and
1411 * recognized bool refs classify directly; arrayrefs classify
1412 * via json_classify_array (homogeneous element kind). Hash
1413 * refs or heterogeneous arrays fail loud with location. */
1414 242 unsigned *kind_masks = NULL;
1415 242 ▶ if (num_paths > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (num_paths > 0) { 221 21 242
1416 221 Newxz(kind_masks, num_paths, unsigned);
1417 221 SAVEFREEPV(kind_masks);
1418 int p;
1419 2311 ▶ for (p = 0; p < num_paths; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = 0; p < num_paths; p++) { 2091 220 2311
1420 23688 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 21598 2090 23688
1421 21598 ▶ if (!row_hvs[r]) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!row_hvs[r]) continue; 1401 20197 21598
1422 20197 SV **e = hv_fetch(row_hvs[r], paths[p],
1423 (I32)path_lens[p], 0);
1424 20197 ▶ if (!e || !SvOK(*e)) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!e || !SvOK(*e)) continue; 2678 17519 20197
if (!e || !SvOK(*e)) continue; 4 2674 2678
1425 2674 ▶ if (SvROK(*e) && !json_is_bool_ref(aTHX_ *e)
Branch: 2 branches
BranchTrueFalseTotal
if (SvROK(*e) && !json_is_bool_ref(aTHX_ *e) 1076 1598 2674
if (SvROK(*e) && !json_is_bool_ref(aTHX_ *e) 849 227 1076
1426 849 ▶ && SvTYPE(SvRV(*e)) != SVt_PVAV)
Branch: 1 branch
BranchTrueFalseTotal
&& SvTYPE(SvRV(*e)) != SVt_PVAV) 0 849 849
1427 0 croak("JSON column row %" IVdf
1428 " path '%s': "
1429 "hash refs as leaves are not "
1430 "supported (already flattened); "
1431 "got %s",
1432 (IV)r, paths[p],
1433 sv_reftype(SvRV(*e), 0));
1434 2674 int k = json_classify_value(aTHX_ *e);
1435 2674 ▶ if (k < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (k < 0) 1 2673 2674
1436 1 croak("JSON column row %" IVdf " path '%s': "
1437 "heterogeneous or unsupported array "
1438 "(elements must all be int, float, "
1439 "bool, or string)",
1440 (IV)r, paths[p]);
1441 2673 kind_masks[p] |= 1u << k;
1442 }
1443 }
1444 }
1445  
1446 /* Step 4: emit Object structure prefix (V1). */
1447 241 buf_le64(aTHX_ prefix, 0); /* Object V1 */
1448 241 buf_varint(aTHX_ prefix, (UV)num_paths); /* max_dynamic_paths */
1449 241 buf_varint(aTHX_ prefix, (UV)num_paths); /* actual count */
1450 int p;
1451 2331 ▶ for (p = 0; p < num_paths; p++)
Branch: 1 branch
BranchTrueFalseTotal
for (p = 0; p < num_paths; p++) 2090 241 2331
1452 2090 buf_string(aTHX_ prefix, paths[p], path_lens[p]);
1453  
1454 /* Per-path wire-slot tables. path_slots[p*5+s] is the lex-ordered
1455 * slot at index s (kind index or -1 for SharedVariant);
1456 * wire_slot_counts[p] is the slot count for path p. Computed
1457 * once, used by both prefix and data loops below. */
1458 241 int *path_slots = NULL;
1459 241 int *wire_slot_counts = NULL;
1460 241 ▶ if (num_paths > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (num_paths > 0) { 220 21 241
1461 220 Newx(path_slots, num_paths * JSON_LEX_SLOTS, int);
1462 220 SAVEFREEPV(path_slots);
1463 220 Newx(wire_slot_counts, num_paths, int);
1464 220 SAVEFREEPV(wire_slot_counts);
1465 2310 ▶ for (p = 0; p < num_paths; p++)
Branch: 1 branch
BranchTrueFalseTotal
for (p = 0; p < num_paths; p++) 2090 220 2310
1466 2090 wire_slot_counts[p] =
1467 2090 json_build_lex_table(kind_masks[p], path_slots + p*JSON_LEX_SLOTS);
1468 }
1469  
1470 /* Step 5: per-path Dynamic V1 prefix + Variant mode. */
1471 2331 ▶ for (p = 0; p < num_paths; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = 0; p < num_paths; p++) { 2090 241 2331
1472 2090 int wire_slots = wire_slot_counts[p];
1473 2090 int kc = wire_slots - 1; /* minus SharedVariant */
1474  
1475 2090 buf_le64(aTHX_ prefix, 1); /* Dynamic V1 */
1476 2090 buf_varint(aTHX_ prefix, (UV)kc); /* max_dynamic_types */
1477 2090 buf_varint(aTHX_ prefix, (UV)kc); /* actual count */
1478  
1479 /* User variant type names in lex order (skip SharedVariant). */
1480 2090 int *slots = path_slots + p*JSON_LEX_SLOTS;
1481 int s;
1482 6562 ▶ for (s = 0; s < wire_slots; s++) {
Branch: 1 branch
BranchTrueFalseTotal
for (s = 0; s < wire_slots; s++) { 4472 2090 6562
1483 4472 int k = slots[s];
1484 4472 ▶ if (k < 0) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (k < 0) continue; 2090 2382 4472
1485 2382 const char *nm = json_kind_type_name[k];
1486 2382 buf_string(aTHX_ prefix, nm, strlen(nm));
1487 }
1488 2090 buf_le64(aTHX_ prefix, 0); /* Variant BASIC */
1489 }
1490  
1491 /* Step 5b: emit typed-path column data (sorted by name).
1492 * Typed paths come before dynamic-path Variant data on the
1493 * wire; their inner types are simple-prefix so encode_column
1494 * emits only the column body. typed_vals is only allocated
1495 * when both n_typed and num_rows are positive; skip when
1496 * num_rows == 0 to avoid dereferencing a NULL outer array. */
1497 241 ▶ if (n_typed > 0 && num_rows > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (n_typed > 0 && num_rows > 0) { 18 223 241
if (n_typed > 0 && num_rows > 0) { 18 0 18
1498 int tp;
1499 43 ▶ for (tp = 0; tp < n_typed; tp++)
Branch: 1 branch
BranchTrueFalseTotal
for (tp = 0; tp < n_typed; tp++) 26 17 43
1500 26 encode_column_data(aTHX_ b, prefix, typed_vals[tp], num_rows,
1501 26 t->tuple[tp]);
1502 }
1503  
1504 /* Step 6: per-path Variant data (discs + per-variant values).
1505 * For Array(T) variants the column's wire layout is:
1506 * N UInt64 LE offsets (cumulative element counts)
1507 * <inner-type values concatenated>
1508 * We emit offsets and inner data in a single pass per variant. */
1509 2330 ▶ for (p = 0; p < num_paths; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = 0; p < num_paths; p++) { 2090 240 2330
1510 2090 int wire_slots = wire_slot_counts[p];
1511 2090 int *slots = path_slots + p*JSON_LEX_SLOTS;
1512  
1513 /* Discriminator byte per row. */
1514 23687 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 21597 2090 23687
1515 21597 ▶ if (!row_hvs[r]) { buf_byte(aTHX_ b, 0xff); continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (!row_hvs[r]) { buf_byte(aTHX_ b, 0xff); continue; } 1401 20196 21597
1516 20196 SV **e = hv_fetch(row_hvs[r], paths[p],
1517 (I32)path_lens[p], 0);
1518 20196 ▶ if (!e || !SvOK(*e)) { buf_byte(aTHX_ b, 0xff); continue; }
Branch: 2 branches
BranchTrueFalseTotal
if (!e || !SvOK(*e)) { buf_byte(aTHX_ b, 0xff); continue; } 2677 17519 20196
if (!e || !SvOK(*e)) { buf_byte(aTHX_ b, 0xff); continue; } 4 2673 2677
1519 2673 int k = json_classify_value(aTHX_ *e);
1520 2673 buf_byte(aTHX_ b,
1521 2673 (uint8_t)json_kind_disc_in(k, slots, wire_slots));
1522 }
1523  
1524 /* Per-variant data in lex order. SharedVariant has zero
1525 * rows in our encoder's output. */
1526 int s;
1527 6562 ▶ for (s = 0; s < wire_slots; s++) {
Branch: 1 branch
BranchTrueFalseTotal
for (s = 0; s < wire_slots; s++) { 4472 2090 6562
1528 4472 int k_match = slots[s];
1529 4472 ▶ if (k_match < 0) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (k_match < 0) continue; 2090 2382 4472
1530  
1531 /* Array(T) variants: first pass emits offsets (so the
1532 * downstream offset cursor is contiguous) and counts
1533 * total elements; second pass emits inner values. */
1534 2382 int is_array = (k_match >= JV_ARRAY_BOOL
1535 2382 ▶ && k_match <= JV_ARRAY_STRING);
Branch: 2 branches
BranchTrueFalseTotal
&& k_match <= JV_ARRAY_STRING); 2382 0 2382
&& k_match <= JV_ARRAY_STRING); 847 1535 2382
1536 2382 ▶ if (is_array) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_array) { 847 1535 2382
1537 847 uint64_t offset = 0;
1538 9980 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 9133 847 9980
1539 9133 ▶ if (!row_hvs[r]) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!row_hvs[r]) continue; 560 8573 9133
1540 8573 SV **e = hv_fetch(row_hvs[r], paths[p],
1541 (I32)path_lens[p], 0);
1542 8573 ▶ if (!e || !SvOK(*e)) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!e || !SvOK(*e)) continue; 857 7716 8573
if (!e || !SvOK(*e)) continue; 2 855 857
1543 855 ▶ if (json_classify_value(aTHX_ *e) != k_match)
Branch: 1 branch
BranchTrueFalseTotal
if (json_classify_value(aTHX_ *e) != k_match) 7 848 855
1544 7 continue;
1545 848 AV *av = (AV*)SvRV(*e);
1546 848 SSize_t n = av_len(av) + 1;
1547 848 offset += (uint64_t)n;
1548 848 buf_le64(aTHX_ b, offset);
1549 }
1550 }
1551  
1552 /* Element-value pass (Array(T)) or scalar pass (T). */
1553 26856 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 24474 2382 26856
1554 24474 ▶ if (!row_hvs[r]) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!row_hvs[r]) continue; 1681 22793 24474
1555 22793 SV **e = hv_fetch(row_hvs[r], paths[p],
1556 (I32)path_lens[p], 0);
1557 22793 ▶ if (!e || !SvOK(*e)) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!e || !SvOK(*e)) continue; 3548 19245 22793
if (!e || !SvOK(*e)) continue; 5 3543 3548
1558 3543 ▶ if (json_classify_value(aTHX_ *e) != k_match) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (json_classify_value(aTHX_ *e) != k_match) continue; 870 2673 3543
1559  
1560 2673 ▶ if (is_array) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_array) { 848 1825 2673
1561 848 AV *av = (AV*)SvRV(*e);
1562 848 SSize_t n = av_len(av) + 1, i;
1563 2845 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 1997 848 2845
1564 1997 SV **elem = av_fetch(av, i, 0);
1565 1997 ▶ SV *ev = (elem && SvOK(*elem))
Branch: 1 branch
BranchTrueFalseTotal
SV *ev = (elem && SvOK(*elem)) 1997 0 1997
1566 3994 ▶ ? *elem : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
? *elem : &PL_sv_undef; 1997 0 1997
1567 1997 json_emit_array_elem(aTHX_ b, ev, k_match);
1568 }
1569 } else {
1570 1825 json_emit_scalar(aTHX_ b, *e, k_match);
1571 }
1572 }
1573 }
1574 }
1575  
1576 /* Step 7: shared data trailer (Array(Tuple(String,String))
1577 * with all rows empty -> N UInt64 LE zero offsets). */
1578 240 ▶ if (num_rows > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (num_rows > 0) { 239 1 240
1579 239 STRLEN nbytes = (STRLEN)num_rows * 8;
1580 239 buf_grow(aTHX_ b, nbytes);
1581 239 memset(b->ptr + b->len, 0, nbytes);
1582 239 b->len += nbytes;
1583 }
1584 240 break;
1585 }
1586  
1587 16 case T_DYNAMIC: {
1588 /* Standalone Dynamic column: same wire format as one JSON
1589 * path's Dynamic sub-column (Dynamic V1 prefix + Variant
1590 * mode + Variant data) with no Object wrapping or shared
1591 * data trailer. Each row is a scalar / array / undef. */
1592 16 unsigned mask = 0;
1593 16 int *row_kinds = NULL;
1594 16 ▶ if (num_rows > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (num_rows > 0) { 16 0 16
1595 16 ▶ Newx(row_kinds, num_rows, int);
Branch: 1 branch
BranchTrueFalseTotal
Newx(row_kinds, num_rows, int); 0 16 16
1596 16 SAVEFREEPV(row_kinds);
1597 }
1598 60 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 45 15 60
1599 45 SV *val = values[r];
1600 45 ▶ if (!SvOK(val)) { row_kinds[r] = -1; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(val)) { row_kinds[r] = -1; continue; } 16 29 45
1601 29 ▶ if (SvROK(val) && !json_is_bool_ref(aTHX_ val)
Branch: 2 branches
BranchTrueFalseTotal
if (SvROK(val) && !json_is_bool_ref(aTHX_ val) 6 23 29
if (SvROK(val) && !json_is_bool_ref(aTHX_ val) 5 1 6
1602 5 ▶ && SvTYPE(SvRV(val)) != SVt_PVAV)
Branch: 1 branch
BranchTrueFalseTotal
&& SvTYPE(SvRV(val)) != SVt_PVAV) 1 4 5
1603 1 croak("Dynamic row %" IVdf ": hash refs are not "
1604 "supported; use JSON column instead "
1605 "(got %s)", (IV)r, sv_reftype(SvRV(val), 0));
1606 28 int k = json_classify_value(aTHX_ val);
1607 28 ▶ if (k < 0)
Branch: 1 branch
BranchTrueFalseTotal
if (k < 0) 0 28 28
1608 0 croak("Dynamic row %" IVdf ": heterogeneous or "
1609 "unsupported array", (IV)r);
1610 28 row_kinds[r] = k;
1611 28 mask |= 1u << k;
1612 }
1613  
1614 int slots[JSON_LEX_SLOTS];
1615 15 int wire_slots = json_build_lex_table(mask, slots);
1616 15 int kc = wire_slots - 1;
1617  
1618 15 buf_le64(aTHX_ prefix, 1); /* Dynamic V1 */
1619 15 buf_varint(aTHX_ prefix, (UV)kc); /* max_dynamic_types */
1620 15 buf_varint(aTHX_ prefix, (UV)kc); /* actual count */
1621 int s;
1622 58 ▶ for (s = 0; s < wire_slots; s++) {
Branch: 1 branch
BranchTrueFalseTotal
for (s = 0; s < wire_slots; s++) { 43 15 58
1623 43 int k = slots[s];
1624 43 ▶ if (k < 0) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (k < 0) continue; 15 28 43
1625 28 const char *nm = json_kind_type_name[k];
1626 28 buf_string(aTHX_ prefix, nm, strlen(nm));
1627 }
1628 15 buf_le64(aTHX_ prefix, 0); /* Variant BASIC */
1629  
1630 /* Discriminator byte per row. */
1631 59 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 44 15 59
1632 44 ▶ if (row_kinds[r] < 0) { buf_byte(aTHX_ b, 0xff); continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (row_kinds[r] < 0) { buf_byte(aTHX_ b, 0xff); continue; } 16 28 44
1633 28 buf_byte(aTHX_ b,
1634 28 (uint8_t)json_kind_disc_in(row_kinds[r],
1635 slots, wire_slots));
1636 }
1637  
1638 /* Per-variant data in lex order. */
1639 58 ▶ for (s = 0; s < wire_slots; s++) {
Branch: 1 branch
BranchTrueFalseTotal
for (s = 0; s < wire_slots; s++) { 43 15 58
1640 43 int k_match = slots[s];
1641 43 ▶ if (k_match < 0) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (k_match < 0) continue; 15 28 43
1642 28 int is_array = (k_match >= JV_ARRAY_BOOL
1643 28 ▶ && k_match <= JV_ARRAY_STRING);
Branch: 2 branches
BranchTrueFalseTotal
&& k_match <= JV_ARRAY_STRING); 28 0 28
&& k_match <= JV_ARRAY_STRING); 4 24 28
1644  
1645 28 ▶ if (is_array) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_array) { 4 24 28
1646 4 uint64_t offset = 0;
1647 18 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 14 4 18
1648 14 ▶ if (row_kinds[r] != k_match) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (row_kinds[r] != k_match) continue; 10 4 14
1649 4 AV *av = (AV*)SvRV(values[r]);
1650 4 offset += (uint64_t)(av_len(av) + 1);
1651 4 buf_le64(aTHX_ b, offset);
1652 }
1653 18 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 14 4 18
1654 14 ▶ if (row_kinds[r] != k_match) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (row_kinds[r] != k_match) continue; 10 4 14
1655 4 AV *av = (AV*)SvRV(values[r]);
1656 4 SSize_t n = av_len(av) + 1, i;
1657 13 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 9 4 13
1658 9 SV **elem = av_fetch(av, i, 0);
1659 9 ▶ SV *ev = (elem && SvOK(*elem))
Branch: 1 branch
BranchTrueFalseTotal
SV *ev = (elem && SvOK(*elem)) 9 0 9
1660 18 ▶ ? *elem : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
? *elem : &PL_sv_undef; 9 0 9
1661 9 json_emit_array_elem(aTHX_ b, ev, k_match);
1662 }
1663 }
1664 } else {
1665 106 ▶ for (r = 0; r < num_rows; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < num_rows; r++) { 82 24 106
1666 82 ▶ if (row_kinds[r] != k_match) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (row_kinds[r] != k_match) continue; 58 24 82
1667 24 json_emit_scalar(aTHX_ b, values[r], k_match);
1668 }
1669 }
1670 }
1671 15 break;
1672 }
1673  
1674 0 default:
1675 0 croak("encode_column: unhandled type code %d", t->code);
1676 }
1677 5987 }
« decimal.c ↑ Summary runtime.c »