1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// SPDX-FileCopyrightText: 2025 - 2026 Frederic Ruget <fred@atlant.is> <fred@s3ns.io> (GitHub: @douzebis)
// SPDX-FileCopyrightText: 2025 - 2026 Thales Cloud Sécurisé
//
// SPDX-License-Identifier: MIT
use std::collections::HashMap;
use std::sync::Arc;
use prost_reflect::{Cardinality, Kind, MessageDescriptor};
use super::super::{enter_level, render_message, FieldOrExt, ANNOTATIONS, CBL_START};
use super::annotations::{field_decl, push_tag_modifiers, AnnWriter};
use super::output::{wfl_prefix_n, wob_prefix_n, write_close_brace, write_dec_u64};
use super::scalar::render_invalid;
use crate::serialize::common::{escape_bytes_into, escape_string_into};
use super::super::packed::render_packed;
/// Render a length-delimited field (string, bytes, message, packed, wire-bytes).
#[allow(clippy::too_many_arguments)]
pub(in super::super) fn render_len_field(
field_number: u64,
field_schema: Option<&FieldOrExt>,
all_schemas: Option<&HashMap<String, Arc<MessageDescriptor>>>,
tag_ohb: Option<u64>,
tag_oor: bool,
len_ohb: Option<u64>,
data: &[u8],
out: &mut Vec<u8>,
) {
let annotations = ANNOTATIONS.with(|c| c.get());
let Some(fs) = field_schema else {
// Unknown field: WireBytes — skip when annotations=false (like render_scalar would).
if !annotations {
return;
}
// v2: numeric key, `bytes` wire type FIRST, no field_decl.
wfl_prefix_n(field_number, None, true, out);
out.push(b'"');
escape_bytes_into(data, out);
out.push(b'"');
let mut aw = AnnWriter::new();
aw.push_wire(out, "bytes");
push_tag_modifiers(&mut aw, out, tag_ohb, tag_oor, len_ohb);
out.push(b'\n');
CBL_START.with(|c| c.set(out.len())); // content line: set past-end to inhibit folding
return;
};
let is_repeated = fs.cardinality() == Cardinality::Repeated;
// ── Packed repeated ───────────────────────────────────────────────────────
if is_repeated && fs.is_packed() {
render_packed(field_number, fs, tag_ohb, tag_oor, len_ohb, data, out);
return;
}
// ── String ────────────────────────────────────────────────────────────────
if fs.kind() == Kind::String {
match std::str::from_utf8(data) {
Ok(s) => {
// Valid UTF-8: write directly — no format! or escape_string allocation.
wfl_prefix_n(field_number, Some(fs), false, out);
out.push(b'"');
escape_string_into(s, out);
out.push(b'"');
if annotations {
let mut aw = AnnWriter::new();
// v2: field_decl FIRST, then modifiers.
aw.push_field_decl(out, field_number, Some(fs), None, None);
push_tag_modifiers(&mut aw, out, tag_ohb, tag_oor, len_ohb);
}
out.push(b'\n');
CBL_START.with(|c| c.set(out.len())); // content line: set past-end to inhibit folding
}
Err(_) => {
render_invalid(
field_number,
Some(fs),
tag_ohb,
tag_oor,
"INVALID_STRING",
data,
out,
);
// render_invalid already updates CBL_START
}
}
return;
}
// ── Bytes ─────────────────────────────────────────────────────────────────
if fs.kind() == Kind::Bytes {
wfl_prefix_n(field_number, Some(fs), false, out);
out.push(b'"');
escape_bytes_into(data, out);
out.push(b'"');
if annotations {
let mut aw = AnnWriter::new();
// v2: field_decl FIRST, then modifiers.
aw.push_field_decl(out, field_number, Some(fs), None, None);
push_tag_modifiers(&mut aw, out, tag_ohb, tag_oor, len_ohb);
}
out.push(b'\n');
CBL_START.with(|c| c.set(out.len())); // content line: set past-end to inhibit folding
return;
}
// ── Nested message ────────────────────────────────────────────────────────
// Note: groups are represented as Kind::Message in prost-reflect. A GROUP
// field received on a LEN wire record is a wire-type mismatch — fall through
// to the mismatch handler below.
if let Kind::Message(nested_msg_desc) = fs.kind() {
if !fs.is_group() {
let nested_schema: Option<&MessageDescriptor> = all_schemas
.and_then(|m| m.get(nested_msg_desc.full_name()))
.map(|v| &**v);
wob_prefix_n(field_number, Some(fs), false, out);
if annotations {
let mut aw = AnnWriter::new();
// v2: NO wire type for known MESSAGE; field_decl FIRST, then modifiers.
aw.push_field_decl(out, field_number, Some(fs), None, None);
push_tag_modifiers(&mut aw, out, tag_ohb, tag_oor, len_ohb);
}
out.push(b'\n');
CBL_START.with(|c| c.set(out.len())); // open-brace line: set past-end to inhibit folding
{
let _guard = enter_level();
render_message(data, 0, None, nested_schema, all_schemas, out);
}
write_close_brace(out);
return;
}
}
// ── Wire-type mismatch (schema says non-LEN type but wire says LEN) ───────
// v2: numeric key, `bytes` wire type FIRST, no field_decl; skip when annotations=false.
if !annotations {
return;
}
wfl_prefix_n(field_number, field_schema, true, out);
out.push(b'"');
escape_bytes_into(data, out);
out.push(b'"');
let mut aw = AnnWriter::new();
aw.push_wire(out, "bytes");
push_tag_modifiers(&mut aw, out, tag_ohb, tag_oor, len_ohb);
out.push(b'\n');
CBL_START.with(|c| c.set(out.len())); // content line: set past-end to inhibit folding
}
/// Render a GROUP field (proto2), with greedy rendering and post-hoc fixup.
#[allow(clippy::too_many_arguments)]
pub(in super::super) fn render_group_field(
buf: &[u8],
pos: &mut usize,
field_number: u64,
field_schema: Option<&FieldOrExt>,
all_schemas: Option<&HashMap<String, Arc<MessageDescriptor>>>,
tag_ohb: Option<u64>,
tag_oor: bool,
out: &mut Vec<u8>,
) {
let annotations = ANNOTATIONS.with(|c| c.get());
// Determine nested schema and whether this is a wire-type mismatch
// (GROUP wire but schema declares a non-GROUP type).
// A mismatch is treated as unknown: field number as name, no field_decl.
let is_mismatch = field_schema.is_some_and(|fs| !fs.is_group());
let nested_schema_opt: Option<&MessageDescriptor> = if let Some(fs) = field_schema {
if fs.is_group() {
if let Kind::Message(msg_desc) = fs.kind() {
all_schemas
.and_then(|m| m.get(msg_desc.full_name()))
.map(|v| &**v)
} else {
None
}
} else {
None
}
} else {
None
};
// ── Greedy: write opening brace line immediately ──────────────────────────
// v2 annotation structure: `group; field_decl [; modifier]*`
// known_field_ann := ["group" ";"] field_decl [";" modifier (";" modifier)*]
//
// Greedy write: write ` # group` now (the `group` token only).
// Post-hoc splice (after recursion): insert `; field_decl [; tag_ohb: N] [; TAG_OOR]
// [; OPEN_GROUP | ; etag_ohb: N | ; ETAG_OOR | ; END_MISMATCH: N]` before '\n'.
//
// For mismatch/unknown GROUP: unknown_field_ann := wire_type [";" modifier]*
// Greedy: ` # group`; post-hoc: `[; tag_ohb: N] [; TAG_OOR] [; close-tag mods]`.
//
// Known GROUP → borrow type display name from schema; mismatch/unknown → decimal number.
use super::output::push_indent;
push_indent(out);
if let Some(fs) = field_schema.filter(|fs| fs.is_group()) {
if let Kind::Message(msg_desc) = fs.kind() {
out.extend_from_slice(msg_desc.name().as_bytes());
} else {
write_dec_u64(field_number, out);
}
} else {
write_dec_u64(field_number, out);
}
out.extend_from_slice(b" {");
if annotations {
let mut aw = AnnWriter::new();
aw.push(out, b"group"); // v2: lowercase, no trailing `;` — field_decl+modifiers go post-hoc
}
out.push(b'\n');
CBL_START.with(|c| c.set(out.len())); // open-brace line: set past-end to inhibit folding
// The '\n' is the last byte written; record its index for post-hoc splice.
let header_nl_pos = out.len() - 1;
// ── Recurse: parse and render child fields ────────────────────────────────
let start = *pos;
let (new_pos, end_tag) = {
let _guard = enter_level();
render_message(
buf,
start,
Some(field_number),
nested_schema_opt,
all_schemas,
out,
)
};
*pos = new_pos;
// ── Collect all post-hoc annotation content ───────────────────────────────
// v2 order (for known non-mismatch GROUP):
// ; field_decl [; tag_ohb: N] [; TAG_OOR] [; close-tag modifiers...]
// v2 order (for unknown/mismatch GROUP, no field_decl):
// [; tag_ohb: N] [; TAG_OOR] [; close-tag modifiers...]
// Close-tag modifiers.
let mut close_mods: Vec<String> = Vec::new();
if end_tag.is_none() {
close_mods.push("OPEN_GROUP".to_owned());
} else if let Some(ref et) = end_tag {
if let Some(ohb) = et.wfield_ohb {
close_mods.push(format!("etag_ohb: {}", ohb));
}
if et.wfield_oor.is_some() {
close_mods.push("ETAG_OOR".to_owned());
}
let end_field = et.wfield.unwrap_or(0);
if end_field != field_number {
close_mods.push(format!("END_MISMATCH: {}", end_field));
}
}
// ── Fixup: splice post-hoc content before '\n' ───────────────────────────
let decl_opt = if annotations && !is_mismatch {
field_decl(field_number, field_schema)
} else {
None
};
// Does annotations=true and we have anything to splice?
let has_field_decl = decl_opt.is_some();
let has_open_tag_mods = annotations && (tag_ohb.is_some() || tag_oor);
let has_close_mods = annotations && !close_mods.is_empty();
if has_field_decl || has_open_tag_mods || has_close_mods {
// Build insert: each part contributes `"; " + text`.
// Since `group` was already written greedily, the first element of the
// insert begins with `"; "` to become the separator after `group`.
let mut insert = String::new();
if let Some(ref d) = decl_opt {
insert.push_str("; ");
insert.push_str(d);
}
if let Some(v) = tag_ohb {
insert.push_str("; tag_ohb: ");
insert.push_str(&v.to_string());
}
if tag_oor {
insert.push_str("; TAG_OOR");
}
for m in &close_mods {
insert.push_str("; ");
insert.push_str(m);
}
let insert_bytes = insert.as_bytes();
#[cfg(debug_assertions)]
eprintln!(
"[render_text] backtracking: field_number={} insert={:?} at offset={}",
field_number, insert, header_nl_pos
);
// Insert before the '\n' at header_nl_pos.
let n = insert_bytes.len();
out.splice(header_nl_pos..header_nl_pos, insert_bytes.iter().copied());
// Adjust CBL_START: the splice shifted all bytes after header_nl_pos.
CBL_START.with(|c| c.set(c.get() + n));
}
write_close_brace(out);
}