prototext 0.1.3

Lossless protobuf ↔ enhanced-textproto converter
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
// 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::path::{Path, PathBuf};

use prototext_core::{parse_schema, render_as_bytes, render_as_text, RenderOpts};

// ── Fixture helpers ───────────────────────────────────────────────────────────

#[derive(Debug, Clone)]
struct Fixture {
    name: String,
    schema: String,
    message: String,
}

fn repo_root() -> PathBuf {
    // CARGO_MANIFEST_DIR points to prototext/ (this crate's directory).
    // fixtures/ lives inside the crate directory.
    Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf()
}

fn load_fixtures() -> Vec<Fixture> {
    let index_path = repo_root().join("fixtures/index.toml");
    let text = std::fs::read_to_string(&index_path)
        .unwrap_or_else(|e| panic!("cannot read {}: {}", index_path.display(), e));
    let doc: toml::Value = text
        .parse()
        .unwrap_or_else(|e| panic!("cannot parse index.toml: {e}"));

    doc.get("fixture")
        .and_then(|v| v.as_array())
        .unwrap_or(&vec![])
        .iter()
        .map(|entry| Fixture {
            name: entry["name"].as_str().unwrap().to_owned(),
            schema: entry["schema"].as_str().unwrap().to_owned(),
            message: entry["message"].as_str().unwrap().to_owned(),
        })
        .collect()
}

fn load_case_text(name: &str) -> Option<Vec<u8>> {
    let path = repo_root()
        .join("fixtures/cases")
        .join(format!("{name}.pb"));
    match std::fs::read(&path) {
        Ok(b) => Some(b),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => panic!("cannot read {}: {e}", path.display()),
    }
}

fn schema_path(schema_rel: &str) -> PathBuf {
    // .pb schemas are generated by build.rs into OUT_DIR (not committed to git).
    let generated = ["descriptor.pb", "knife.pb", "enum_collision.pb"];
    if let Some(name) = generated
        .iter()
        .find(|&&n| schema_rel == format!("fixtures/schemas/{n}"))
    {
        return PathBuf::from(env!("OUT_DIR")).join(name);
    }
    repo_root().join(schema_rel)
}

fn load_schema(schema_rel: &str, message: &str) -> prototext_core::ParsedSchema {
    let path = schema_path(schema_rel);
    let bytes = std::fs::read(&path)
        .unwrap_or_else(|e| panic!("cannot read schema {}: {e}", path.display()));
    parse_schema(&bytes, message)
        .unwrap_or_else(|e| panic!("cannot parse schema {schema_rel}:{message}: {e}"))
}

// ── Helpers ───────────────────────────────────────────────────────────────────

fn enum_schema() -> prototext_core::ParsedSchema {
    load_schema("fixtures/schemas/enum_collision.pb", "EnumCollision")
}

fn opts(annotations: bool) -> RenderOpts {
    RenderOpts::new(true, annotations, 1)
}

// ── §7 Enum rendering tests ───────────────────────────────────────────────────

#[test]
fn enum_known_value_renders_symbolic_name() {
    // EnumCollision field 2 'color' (Color enum): wire value 1 = GREEN.
    // Tag: field 2, wire type varint = 0x10. Value: 0x01.
    let wire = vec![0x10, 0x01];
    let schema = enum_schema();
    let text = render_as_text(&wire, Some(&schema), opts(true)).unwrap();
    let text_str = String::from_utf8(text).unwrap();
    assert!(
        text_str.contains("GREEN"),
        "expected symbolic name GREEN in: {text_str}"
    );
    assert!(
        text_str.contains("Color(1)"),
        "expected Color(1) in annotation: {text_str}"
    );
}

#[test]
fn enum_unknown_value_renders_numeric_with_enum_unknown() {
    // EnumCollision field 2 'color' (Color enum): wire value 99 — not in enum.
    let wire = vec![0x10, 0x63]; // field 2 varint, value 99
    let schema = enum_schema();
    let text = render_as_text(&wire, Some(&schema), opts(true)).unwrap();
    let text_str = String::from_utf8(text).unwrap();
    assert!(
        text_str.contains("99"),
        "expected numeric 99 in: {text_str}"
    );
    assert!(
        text_str.contains("ENUM_UNKNOWN"),
        "expected ENUM_UNKNOWN in annotation: {text_str}"
    );
}

#[test]
fn packed_enum_renders_symbolic_names() {
    // EnumCollision field 5 'colors_pk' (repeated Color, packed).
    // Tag: field 5, wire type LEN = (5<<3)|2 = 0x2A. Payload: varint 1 (GREEN), varint 2 (BLUE).
    let wire = vec![0x2A, 0x02, 0x01, 0x02]; // tag, len=2, GREEN=1, BLUE=2
    let schema = enum_schema();
    let text = render_as_text(&wire, Some(&schema), opts(true)).unwrap();
    let text_str = String::from_utf8(text).unwrap();
    assert!(
        text_str.contains("GREEN"),
        "expected GREEN in packed: {text_str}"
    );
    assert!(
        text_str.contains("BLUE"),
        "expected BLUE in packed: {text_str}"
    );
    assert!(
        text_str.contains("Color([1, 2])"),
        "expected Color([1, 2]) in annotation: {text_str}"
    );
}

#[test]
fn enum_annotation_roundtrips_wire() {
    // EnumCollision field 2 'color' = GREEN (1).
    let wire = vec![0x10, 0x01];
    let schema = enum_schema();
    let text = render_as_text(&wire, Some(&schema), opts(true)).unwrap();
    let wire2 = render_as_bytes(&text, opts(true)).unwrap();
    assert_eq!(wire2, wire, "enum annotation must round-trip byte-for-byte");
}

#[test]
fn no_annotations_omits_unknown_fields() {
    // Unknown field (no schema): wire type varint, field 99.
    let wire = vec![0xb8, 0x06, 0x01]; // field 99, varint, value 1
    let schema = enum_schema();
    let text = render_as_text(&wire, Some(&schema), opts(false)).unwrap();
    let text_str = String::from_utf8(text).unwrap();
    assert!(
        !text_str.contains("99"),
        "unknown field should be omitted without annotations: {text_str}"
    );
}

#[test]
fn enum_named_float_roundtrip_is_varint() {
    // EnumCollision field 1 'kind' (enum float): value 1 = FLOAT_ONE.
    // Wire: tag field 1 varint = 0x08, value 0x01. Total 2 bytes.
    let wire = vec![0x08, 0x01];
    let schema = enum_schema();
    let text = render_as_text(&wire, Some(&schema), opts(true)).unwrap();
    let wire2 = render_as_bytes(&text, opts(true)).unwrap();
    assert_eq!(
        wire2, wire,
        "enum named 'float' must round-trip as varint (2 bytes), not fixed32 (5 bytes)"
    );
    assert_eq!(
        wire2.len(),
        2,
        "re-encoded wire must be 2 bytes (varint), not 5 (fixed32)"
    );
}

// ── §8 NaN encoding tests ────────────────────────────────────────────────────

fn knife_schema() -> prototext_core::ParsedSchema {
    load_schema("fixtures/schemas/knife.pb", "SwissArmyKnife")
}

// Wire helpers: encode a single scalar field.
//   floatOp  = field 22, wire type FIXED32 (5) → tag = (22 << 3) | 5 = 0xB5 0x01
//   doubleOp = field 21, wire type FIXED64 (1) → tag = (21 << 3) | 1 = 0xA9 0x01
fn float_wire(bits: u32) -> Vec<u8> {
    let mut v = vec![0xB5, 0x01]; // tag for floatOp (field 22, FIXED32)
    v.extend_from_slice(&bits.to_le_bytes());
    v
}

fn double_wire(bits: u64) -> Vec<u8> {
    let mut v = vec![0xA9, 0x01]; // tag for doubleOp (field 21, FIXED64)
    v.extend_from_slice(&bits.to_le_bytes());
    v
}

// Wire helpers: packed repeated fields.
//   floatPk  = field 82, wire type LEN (2) → tag = (82 << 3) | 2 = 0x92 0x05 (varint)
//   doublePk = field 81, wire type LEN (2) → tag = (81 << 3) | 2 = 0x8A 0x05 (varint)
fn float_packed_wire(bits: &[u32]) -> Vec<u8> {
    let payload: Vec<u8> = bits.iter().flat_map(|b| b.to_le_bytes()).collect();
    let mut v = vec![0x92, 0x05]; // tag
    v.push(payload.len() as u8);
    v.extend_from_slice(&payload);
    v
}

fn double_packed_wire(bits: &[u64]) -> Vec<u8> {
    let payload: Vec<u8> = bits.iter().flat_map(|b| b.to_le_bytes()).collect();
    let mut v = vec![0x8A, 0x05]; // tag
    v.push(payload.len() as u8);
    v.extend_from_slice(&payload);
    v
}

// f32 canonical quiet NaN: 0x7FC00000
const F32_CANONICAL_NAN: u32 = 0x7FC00000;
// f32 non-canonical NaNs used in tests
const F32_SIGNALING_NAN: u32 = 0x7F800001; // signaling NaN, payload 1
const F32_SIGNED_NAN: u32 = 0xFFC00000; // quiet NaN with sign bit set
const F32_PAYLOAD_NAN: u32 = 0x7FC0CAFE; // quiet NaN with custom payload

// f64 canonical quiet NaN: 0x7FF8000000000000
const F64_CANONICAL_NAN: u64 = 0x7FF8000000000000;
// f64 non-canonical NaNs used in tests
const F64_SIGNALING_NAN: u64 = 0x7FF0000000000001; // signaling NaN, payload 1
const F64_SIGNED_NAN: u64 = 0xFFF8000000000000; // quiet NaN with sign bit set
const F64_PAYLOAD_NAN: u64 = 0x7FF800000BADC0DE; // quiet NaN with custom payload

#[test]
fn float_canonical_nan_renders_bare_nan() {
    let wire = float_wire(F32_CANONICAL_NAN);
    let schema = knife_schema();
    let text = render_as_text(&wire, Some(&schema), opts(false)).unwrap();
    let text_str = String::from_utf8(text).unwrap();
    assert!(
        text_str.contains("nan"),
        "expected bare 'nan' for canonical NaN, got: {text_str}"
    );
    assert!(
        !text_str.contains("nan("),
        "canonical NaN must not have a modifier, got: {text_str}"
    );
}

#[test]
fn float_noncanonical_nan_renders_with_modifier() {
    for &bits in &[F32_SIGNALING_NAN, F32_SIGNED_NAN, F32_PAYLOAD_NAN] {
        let wire = float_wire(bits);
        let schema = knife_schema();
        let text = render_as_text(&wire, Some(&schema), opts(false)).unwrap();
        let text_str = String::from_utf8(text).unwrap();
        let expected = format!("nan(0x{:08x})", bits);
        assert!(
            text_str.contains(&expected),
            "bits 0x{:08x}: expected '{}' in: {text_str}",
            bits,
            expected
        );
    }
}

#[test]
fn float_noncanonical_nan_roundtrips() {
    for &bits in &[F32_SIGNALING_NAN, F32_SIGNED_NAN, F32_PAYLOAD_NAN] {
        let wire = float_wire(bits);
        let schema = knife_schema();
        let text = render_as_text(&wire, Some(&schema), opts(true)).unwrap();
        let wire2 = render_as_bytes(&text, opts(true)).unwrap();
        assert_eq!(
            wire2, wire,
            "float NaN 0x{:08x} must round-trip bit-exact",
            bits
        );
    }
}

#[test]
fn double_canonical_nan_renders_bare_nan() {
    let wire = double_wire(F64_CANONICAL_NAN);
    let schema = knife_schema();
    let text = render_as_text(&wire, Some(&schema), opts(false)).unwrap();
    let text_str = String::from_utf8(text).unwrap();
    assert!(
        text_str.contains("nan"),
        "expected bare 'nan' for canonical NaN, got: {text_str}"
    );
    assert!(
        !text_str.contains("nan("),
        "canonical NaN must not have a modifier, got: {text_str}"
    );
}

#[test]
fn double_noncanonical_nan_renders_with_modifier() {
    for &bits in &[F64_SIGNALING_NAN, F64_SIGNED_NAN, F64_PAYLOAD_NAN] {
        let wire = double_wire(bits);
        let schema = knife_schema();
        let text = render_as_text(&wire, Some(&schema), opts(false)).unwrap();
        let text_str = String::from_utf8(text).unwrap();
        let expected = format!("nan(0x{:016x})", bits);
        assert!(
            text_str.contains(&expected),
            "bits 0x{:016x}: expected '{}' in: {text_str}",
            bits,
            expected
        );
    }
}

#[test]
fn double_noncanonical_nan_roundtrips() {
    for &bits in &[F64_SIGNALING_NAN, F64_SIGNED_NAN, F64_PAYLOAD_NAN] {
        let wire = double_wire(bits);
        let schema = knife_schema();
        let text = render_as_text(&wire, Some(&schema), opts(true)).unwrap();
        let wire2 = render_as_bytes(&text, opts(true)).unwrap();
        assert_eq!(
            wire2, wire,
            "double NaN 0x{:016x} must round-trip bit-exact",
            bits
        );
    }
}

#[test]
fn float_packed_noncanonical_nan_renders_with_modifier() {
    // packed floatPk: canonical NaN, signaling NaN, payload NaN
    let wire = float_packed_wire(&[F32_CANONICAL_NAN, F32_SIGNALING_NAN, F32_PAYLOAD_NAN]);
    let schema = knife_schema();
    let text = render_as_text(&wire, Some(&schema), opts(false)).unwrap();
    let text_str = String::from_utf8(text).unwrap();
    // canonical: bare nan; non-canonical: nan(0x...)
    assert!(
        text_str.contains("nan,") || text_str.contains("nan]"),
        "expected bare nan element in packed, got: {text_str}"
    );
    assert!(
        text_str.contains(&format!("nan(0x{:08x})", F32_SIGNALING_NAN)),
        "expected signaling NaN modifier in packed, got: {text_str}"
    );
    assert!(
        text_str.contains(&format!("nan(0x{:08x})", F32_PAYLOAD_NAN)),
        "expected payload NaN modifier in packed, got: {text_str}"
    );
}

#[test]
fn float_packed_noncanonical_nan_roundtrips() {
    let wire = float_packed_wire(&[F32_CANONICAL_NAN, F32_SIGNALING_NAN, F32_PAYLOAD_NAN]);
    let schema = knife_schema();
    let text = render_as_text(&wire, Some(&schema), opts(true)).unwrap();
    let wire2 = render_as_bytes(&text, opts(true)).unwrap();
    assert_eq!(
        wire2, wire,
        "packed float NaN array must round-trip bit-exact"
    );
}

#[test]
fn double_packed_noncanonical_nan_renders_with_modifier() {
    let wire = double_packed_wire(&[F64_CANONICAL_NAN, F64_SIGNALING_NAN, F64_PAYLOAD_NAN]);
    let schema = knife_schema();
    let text = render_as_text(&wire, Some(&schema), opts(false)).unwrap();
    let text_str = String::from_utf8(text).unwrap();
    assert!(
        text_str.contains("nan,") || text_str.contains("nan]"),
        "expected bare nan element in packed, got: {text_str}"
    );
    assert!(
        text_str.contains(&format!("nan(0x{:016x})", F64_SIGNALING_NAN)),
        "expected signaling NaN modifier in packed, got: {text_str}"
    );
    assert!(
        text_str.contains(&format!("nan(0x{:016x})", F64_PAYLOAD_NAN)),
        "expected payload NaN modifier in packed, got: {text_str}"
    );
}

#[test]
fn double_packed_noncanonical_nan_roundtrips() {
    let wire = double_packed_wire(&[F64_CANONICAL_NAN, F64_SIGNALING_NAN, F64_PAYLOAD_NAN]);
    let schema = knife_schema();
    let text = render_as_text(&wire, Some(&schema), opts(true)).unwrap();
    let wire2 = render_as_bytes(&text, opts(true)).unwrap();
    assert_eq!(
        wire2, wire,
        "packed double NaN array must round-trip bit-exact"
    );
}

#[test]
fn float_packed_all_nan_variants_roundtrip() {
    // All four NaN variants together in one packed array.
    let wire = float_packed_wire(&[
        F32_CANONICAL_NAN,
        F32_SIGNALING_NAN,
        F32_SIGNED_NAN,
        F32_PAYLOAD_NAN,
    ]);
    let schema = knife_schema();
    let text = render_as_text(&wire, Some(&schema), opts(true)).unwrap();
    let wire2 = render_as_bytes(&text, opts(true)).unwrap();
    assert_eq!(
        wire2, wire,
        "packed float all-NaN-variants must round-trip bit-exact"
    );
}

#[test]
fn double_packed_all_nan_variants_roundtrip() {
    // All four NaN variants together in one packed array.
    let wire = double_packed_wire(&[
        F64_CANONICAL_NAN,
        F64_SIGNALING_NAN,
        F64_SIGNED_NAN,
        F64_PAYLOAD_NAN,
    ]);
    let schema = knife_schema();
    let text = render_as_text(&wire, Some(&schema), opts(true)).unwrap();
    let wire2 = render_as_bytes(&text, opts(true)).unwrap();
    assert_eq!(
        wire2, wire,
        "packed double all-NaN-variants must round-trip bit-exact"
    );
}

// ── §8b Subnormal encoding tests ─────────────────────────────────────────────

#[test]
fn float_subnormals_roundtrip() {
    let cases: &[u32] = &[
        0x00000001, // min positive subnormal
        0x007fffff, // max subnormal
        0x80000001, // min negative subnormal
        0x003fffff, // mid subnormal
    ];
    for &bits in cases {
        let wire = float_wire(bits);
        let schema = knife_schema();
        let text = render_as_text(&wire, Some(&schema), opts(true)).unwrap();
        let wire2 = render_as_bytes(&text, opts(true)).unwrap();
        assert_eq!(
            wire2, wire,
            "float subnormal 0x{:08x} must round-trip bit-exact",
            bits
        );
    }
}

#[test]
fn double_subnormals_roundtrip() {
    let cases: &[u64] = &[
        0x0000000000000001, // min positive subnormal
        0x000fffffffffffff, // max subnormal
        0x8000000000000001, // min negative subnormal
        0x0004000000000000, // mid subnormal
    ];
    for &bits in cases {
        let wire = double_wire(bits);
        let schema = knife_schema();
        let text = render_as_text(&wire, Some(&schema), opts(true)).unwrap();
        let wire2 = render_as_bytes(&text, opts(true)).unwrap();
        assert_eq!(
            wire2, wire,
            "double subnormal 0x{:016x} must round-trip bit-exact",
            bits
        );
    }
}

// ── Fixture roundtrip tests ───────────────────────────────────────────────────

fn to_wire(text: &[u8]) -> Vec<u8> {
    let opts = RenderOpts::new(true, true, 1);
    render_as_bytes(text, opts).expect("render_as_bytes failed")
}

#[test]
fn fixture_roundtrip_annotated() {
    let fixtures = load_fixtures();
    let mut ran = 0;
    let mut skipped = 0;

    for fx in &fixtures {
        let Some(text) = load_case_text(&fx.name) else {
            eprintln!("SKIP  {} (case file missing)", fx.name);
            skipped += 1;
            continue;
        };

        let wire = to_wire(&text);
        let schema = load_schema(&fx.schema, &fx.message);
        let opts = RenderOpts::new(true, true, 1);
        let text2 = render_as_text(&wire, Some(&schema), opts).expect("render_as_text failed");

        assert_eq!(
            text2,
            text,
            "round-trip mismatch for {} (annotations=true)\n  orig:\n{}\n  reenc:\n{}",
            fx.name,
            String::from_utf8_lossy(&text),
            String::from_utf8_lossy(&text2),
        );
        ran += 1;
    }

    eprintln!("roundtrip(annotations=true): {ran} passed, {skipped} skipped");
    assert!(
        ran > 0,
        "no fixtures ran — index.toml empty or all case files missing"
    );
}