oxiproto-codegen 0.1.2

Pure Rust protobuf code generator from FileDescriptorSet to Rust structs/enums
Documentation
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
// Tests that verify JSON codegen produces valid Rust code containing the
// expected method signatures.  These tests check syntax (via `syn`) and
// content (via substring matching) but do NOT execute the generated code.

use prost_types::field_descriptor_proto::{Label, Type};
use prost_types::{
    DescriptorProto, EnumDescriptorProto, EnumValueDescriptorProto, FieldDescriptorProto,
    FileDescriptorProto, FileDescriptorSet, OneofDescriptorProto,
};

// ── helpers ────────────────────────────────────────────────────────────────────

fn make_field(name: &str, number: i32, r#type: Type, label: Label) -> FieldDescriptorProto {
    FieldDescriptorProto {
        name: Some(name.to_string()),
        number: Some(number),
        label: Some(label as i32),
        r#type: Some(r#type as i32),
        json_name: Some(to_camel_case(name)),
        ..Default::default()
    }
}

fn make_enum_field(name: &str, number: i32, type_name: &str) -> FieldDescriptorProto {
    FieldDescriptorProto {
        name: Some(name.to_string()),
        number: Some(number),
        label: Some(Label::Optional as i32),
        r#type: Some(Type::Enum as i32),
        type_name: Some(type_name.to_string()),
        json_name: Some(to_camel_case(name)),
        ..Default::default()
    }
}

fn make_message_field(name: &str, number: i32, type_name: &str) -> FieldDescriptorProto {
    FieldDescriptorProto {
        name: Some(name.to_string()),
        number: Some(number),
        label: Some(Label::Optional as i32),
        r#type: Some(Type::Message as i32),
        type_name: Some(type_name.to_string()),
        json_name: Some(to_camel_case(name)),
        ..Default::default()
    }
}

fn make_repeated_field(name: &str, number: i32, r#type: Type) -> FieldDescriptorProto {
    FieldDescriptorProto {
        name: Some(name.to_string()),
        number: Some(number),
        label: Some(Label::Repeated as i32),
        r#type: Some(r#type as i32),
        json_name: Some(to_camel_case(name)),
        ..Default::default()
    }
}

fn make_oneof_field(
    name: &str,
    number: i32,
    r#type: Type,
    oneof_index: i32,
) -> FieldDescriptorProto {
    FieldDescriptorProto {
        name: Some(name.to_string()),
        number: Some(number),
        label: Some(Label::Optional as i32),
        r#type: Some(r#type as i32),
        json_name: Some(to_camel_case(name)),
        oneof_index: Some(oneof_index),
        ..Default::default()
    }
}

fn to_camel_case(s: &str) -> String {
    let mut result = String::new();
    let mut next_upper = false;
    for c in s.chars() {
        if c == '_' {
            next_upper = true;
        } else if next_upper {
            result.extend(c.to_uppercase());
            next_upper = false;
        } else {
            result.push(c);
        }
    }
    result
}

fn make_status_enum() -> EnumDescriptorProto {
    EnumDescriptorProto {
        name: Some("Status".to_string()),
        value: vec![
            EnumValueDescriptorProto {
                name: Some("UNKNOWN".to_string()),
                number: Some(0),
                ..Default::default()
            },
            EnumValueDescriptorProto {
                name: Some("ACTIVE".to_string()),
                number: Some(1),
                ..Default::default()
            },
            EnumValueDescriptorProto {
                name: Some("INACTIVE".to_string()),
                number: Some(2),
                ..Default::default()
            },
        ],
        ..Default::default()
    }
}

fn gen_with_json(fds: &FileDescriptorSet) -> String {
    let mut opts = oxiproto_codegen::CodegenOptions::new();
    opts.emit_json = true;
    oxiproto_codegen::generate_with_options(fds, &opts).expect("codegen must succeed")
}

fn assert_valid_rust(code: &str) {
    syn::parse_str::<syn::File>(code)
        .unwrap_or_else(|e| panic!("Generated code failed to parse: {e}\n\nCode:\n{code}"));
}

// ── tests ──────────────────────────────────────────────────────────────────────

#[test]
fn json_emit_produces_to_json_and_from_json() {
    let msg = DescriptorProto {
        name: Some("Scalars".to_string()),
        field: vec![
            make_field("name", 1, Type::String, Label::Optional),
            make_field("count", 2, Type::Int32, Label::Optional),
            make_field("big_count", 3, Type::Int64, Label::Optional),
            make_field("active", 4, Type::Bool, Label::Optional),
            make_field("score", 5, Type::Float, Label::Optional),
            make_field("ratio", 6, Type::Double, Label::Optional),
            make_field("data", 7, Type::Bytes, Label::Optional),
        ],
        ..Default::default()
    };
    let fds = FileDescriptorSet {
        file: vec![FileDescriptorProto {
            name: Some("scalars.proto".to_string()),
            package: Some("".to_string()),
            message_type: vec![msg],
            ..Default::default()
        }],
    };

    let code = gen_with_json(&fds);
    assert_valid_rust(&code);
    assert!(
        code.contains("pub fn to_json"),
        "Missing to_json in:\n{code}"
    );
    assert!(
        code.contains("pub fn from_json"),
        "Missing from_json in:\n{code}"
    );
    assert!(code.contains("JsonError"), "Missing JsonError in:\n{code}");
    assert!(
        code.contains("_json_type"),
        "Missing _json_type in:\n{code}"
    );
}

#[test]
fn json_emit_repeated_fields() {
    let msg = DescriptorProto {
        name: Some("Lists".to_string()),
        field: vec![
            make_repeated_field("tags", 1, Type::String),
            make_repeated_field("scores", 2, Type::Int32),
            make_repeated_field("ids", 3, Type::Int64),
            make_repeated_field("flags", 4, Type::Bool),
        ],
        ..Default::default()
    };
    let fds = FileDescriptorSet {
        file: vec![FileDescriptorProto {
            name: Some("lists.proto".to_string()),
            message_type: vec![msg],
            ..Default::default()
        }],
    };

    let code = gen_with_json(&fds);
    assert_valid_rust(&code);
    assert!(code.contains("pub fn to_json"), "Missing to_json:\n{code}");
    assert!(
        code.contains("pub fn from_json"),
        "Missing from_json:\n{code}"
    );
    assert!(
        code.contains("Array"),
        "Repeated fields should use Array:\n{code}"
    );
}

#[test]
fn json_emit_enum_has_to_json_str_and_from_json_value() {
    let en = make_status_enum();
    let fds = FileDescriptorSet {
        file: vec![FileDescriptorProto {
            name: Some("status.proto".to_string()),
            enum_type: vec![en],
            ..Default::default()
        }],
    };

    let code = gen_with_json(&fds);
    assert_valid_rust(&code);
    assert!(
        code.contains("pub fn to_json_str"),
        "Missing to_json_str:\n{code}"
    );
    assert!(
        code.contains("pub fn from_json_value"),
        "Missing from_json_value:\n{code}"
    );
    assert!(
        code.contains("\"UNKNOWN\""),
        "Should contain UNKNOWN variant name:\n{code}"
    );
    assert!(
        code.contains("\"ACTIVE\""),
        "Should contain ACTIVE variant name:\n{code}"
    );
}

#[test]
fn json_emit_nested_message() {
    let inner = DescriptorProto {
        name: Some("Address".to_string()),
        field: vec![make_field("street", 1, Type::String, Label::Optional)],
        ..Default::default()
    };
    let outer = DescriptorProto {
        name: Some("Person".to_string()),
        field: vec![
            make_field("name", 1, Type::String, Label::Optional),
            make_message_field("address", 2, ".Address"),
        ],
        ..Default::default()
    };
    let fds = FileDescriptorSet {
        file: vec![FileDescriptorProto {
            name: Some("nested.proto".to_string()),
            message_type: vec![inner, outer],
            ..Default::default()
        }],
    };

    let code = gen_with_json(&fds);
    assert_valid_rust(&code);
    assert!(code.contains("pub fn to_json"), "Missing to_json:\n{code}");
}

#[test]
fn json_emit_oneof() {
    let msg = DescriptorProto {
        name: Some("OneofMsg".to_string()),
        field: vec![
            make_oneof_field("int_val", 1, Type::Int32, 0),
            make_oneof_field("str_val", 2, Type::String, 0),
        ],
        oneof_decl: vec![OneofDescriptorProto {
            name: Some("value".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    };
    let fds = FileDescriptorSet {
        file: vec![FileDescriptorProto {
            name: Some("oneof.proto".to_string()),
            message_type: vec![msg],
            ..Default::default()
        }],
    };

    let code = gen_with_json(&fds);
    assert_valid_rust(&code);
    assert!(code.contains("pub fn to_json"), "Missing to_json:\n{code}");
    assert!(
        code.contains("pub fn from_json"),
        "Missing from_json:\n{code}"
    );
}

#[test]
fn json_emit_enum_field_in_message() {
    let en = make_status_enum();
    let msg = DescriptorProto {
        name: Some("Task".to_string()),
        field: vec![
            make_field("title", 1, Type::String, Label::Optional),
            make_enum_field("status", 2, ".Status"),
        ],
        ..Default::default()
    };
    let fds = FileDescriptorSet {
        file: vec![FileDescriptorProto {
            name: Some("task.proto".to_string()),
            message_type: vec![msg],
            enum_type: vec![en],
            ..Default::default()
        }],
    };

    let code = gen_with_json(&fds);
    assert_valid_rust(&code);
    assert!(code.contains("pub fn to_json"), "Missing to_json:\n{code}");
    assert!(
        code.contains("to_json_str"),
        "Enum field should use to_json_str:\n{code}"
    );
}

#[test]
fn json_emit_bytes_field_uses_base64() {
    let msg = DescriptorProto {
        name: Some("BinaryMsg".to_string()),
        field: vec![make_field("payload", 1, Type::Bytes, Label::Optional)],
        ..Default::default()
    };
    let fds = FileDescriptorSet {
        file: vec![FileDescriptorProto {
            name: Some("binary.proto".to_string()),
            message_type: vec![msg],
            ..Default::default()
        }],
    };

    let code = gen_with_json(&fds);
    assert_valid_rust(&code);
    assert!(
        code.contains("STANDARD"),
        "bytes field should use STANDARD base64:\n{code}"
    );
    assert!(code.contains("base64"), "Should reference base64:\n{code}");
}

#[test]
fn json_emit_int64_uses_string_repr() {
    let msg = DescriptorProto {
        name: Some("BigNums".to_string()),
        field: vec![
            make_field("big_signed", 1, Type::Int64, Label::Optional),
            make_field("big_unsigned", 2, Type::Uint64, Label::Optional),
            make_field("fixed64_val", 3, Type::Fixed64, Label::Optional),
        ],
        ..Default::default()
    };
    let fds = FileDescriptorSet {
        file: vec![FileDescriptorProto {
            name: Some("bignums.proto".to_string()),
            message_type: vec![msg],
            ..Default::default()
        }],
    };

    let code = gen_with_json(&fds);
    assert_valid_rust(&code);
    // i64/u64 must be serialised as JSON strings
    assert!(
        code.contains("::serde_json::Value::String"),
        "int64/uint64 should be JSON string:\n{code}"
    );
}

#[test]
fn json_emit_float_nan_inf() {
    let msg = DescriptorProto {
        name: Some("FloatMsg".to_string()),
        field: vec![
            make_field("f32_val", 1, Type::Float, Label::Optional),
            make_field("f64_val", 2, Type::Double, Label::Optional),
        ],
        ..Default::default()
    };
    let fds = FileDescriptorSet {
        file: vec![FileDescriptorProto {
            name: Some("float.proto".to_string()),
            message_type: vec![msg],
            ..Default::default()
        }],
    };

    let code = gen_with_json(&fds);
    assert_valid_rust(&code);
    assert!(code.contains("\"NaN\""), "Should handle NaN:\n{code}");
    assert!(code.contains("\"Infinity\""), "Should handle +Inf:\n{code}");
    assert!(
        code.contains("\"-Infinity\""),
        "Should handle -Inf:\n{code}"
    );
}

#[test]
fn json_emit_camel_case_keys() {
    let msg = DescriptorProto {
        name: Some("CamelTest".to_string()),
        field: vec![
            FieldDescriptorProto {
                name: Some("user_id".to_string()),
                number: Some(1),
                label: Some(Label::Optional as i32),
                r#type: Some(Type::Int32 as i32),
                json_name: Some("userId".to_string()),
                ..Default::default()
            },
            FieldDescriptorProto {
                name: Some("first_name".to_string()),
                number: Some(2),
                label: Some(Label::Optional as i32),
                r#type: Some(Type::String as i32),
                json_name: Some("firstName".to_string()),
                ..Default::default()
            },
        ],
        ..Default::default()
    };
    let fds = FileDescriptorSet {
        file: vec![FileDescriptorProto {
            name: Some("camel.proto".to_string()),
            message_type: vec![msg],
            ..Default::default()
        }],
    };

    let code = gen_with_json(&fds);
    assert_valid_rust(&code);
    // to_json should use camelCase keys from json_name
    assert!(
        code.contains("\"userId\""),
        "Expected userId key in:\n{code}"
    );
    assert!(
        code.contains("\"firstName\""),
        "Expected firstName key in:\n{code}"
    );
    // from_json should accept both camelCase and snake_case
    assert!(
        code.contains("\"userId\" | \"user_id\"") || code.contains("\"user_id\" | \"userId\""),
        "Expected both userId and user_id in from_json:\n{code}"
    );
}

#[test]
fn package_namespacing_and_emit_json_no_error() {
    // The guard has been lifted: emit_json + package_namespacing must NOT return Err.
    let msg = DescriptorProto {
        name: Some("Msg".to_string()),
        ..Default::default()
    };
    let fds = FileDescriptorSet {
        file: vec![FileDescriptorProto {
            name: Some("pkg.proto".to_string()),
            package: Some("foo".to_string()),
            message_type: vec![msg],
            ..Default::default()
        }],
    };

    let mut opts = oxiproto_codegen::CodegenOptions::new();
    opts.emit_json = true;
    opts.package_namespacing = true;

    let result = oxiproto_codegen::generate_with_options(&fds, &opts);
    assert!(
        result.is_ok(),
        "emit_json + package_namespacing should succeed after guard removal, got: {:?}",
        result.err()
    );
    let code = result.unwrap();
    assert_valid_rust(&code);
    // JSON prelude must appear inside the module, not at the root
    assert!(
        code.contains("pub mod foo"),
        "Expected module 'foo' in:\n{code}"
    );
    assert!(
        code.contains("pub fn to_json"),
        "Expected to_json in:\n{code}"
    );
    assert!(
        code.contains("pub fn from_json"),
        "Expected from_json in:\n{code}"
    );
}