fastxdr 1.0.2

Generate Rust types from XDR specs with fast, zero-copy deserialisation
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
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
use super::{NonDigitName, SafeName};
use crate::ast::{indexes::*, ArrayType, Ast, BasicType};
use crate::Result;

const TRAIT_BOUNDS: &str = "<T> where T: AsRef<[u8]> + Debug";

pub fn print_types<W: std::fmt::Write>(w: &mut W, ast: &Ast, derive: &str) -> Result<()> {
    for item in ast.constants().iter() {
        if !item.1.contains("::") {
            writeln!(w, "pub const {}: u32 = {};", item.0, item.1)?;
        }
    }

    for item in ast.types().iter() {
        match item {
            AstType::Struct(v) => {
                writeln!(w, "{}", derive)?;
                write!(w, "pub struct {}", v.name)?;
                if ast.generics().contains(v.name.as_str()) {
                    write!(w, "{}", TRAIT_BOUNDS)?;
                }

                writeln!(w, " {{")?;
                for f in v.fields.iter() {
                    write!(w, "pub {}: ", SafeName(&f.field_name))?;

                    // Optional fields require boxing to allow a self-referential
                    // type chain
                    if f.is_optional {
                        write!(w, "Option<Box<")?;
                    }

                    // For each field, replace any "opaque" types with T, which will
                    // be generic for AsRef<[u8]>.
                    //
                    // For each ident, check if it is in the generic index, and if
                    // so, append <T> for the AsRef.
                    match f.field_value.unwrap_array() {
                        BasicType::Opaque => write!(w, "T")?,
                        BasicType::String => write!(w, "String")?,
                        BasicType::Ident(i) if ast.generics().contains(i.as_ref()) => {
                            f.field_value
                                .write_with_bounds(w, Some(vec!["T"].as_ref()))?;
                        }
                        _ => write!(w, "{}", f.field_value)?,
                    }

                    if f.is_optional {
                        write!(w, ">>")?;
                    }

                    writeln!(w, ",")?;
                }
                writeln!(w, "}}")?;
            }
            AstType::Union(v) => {
                writeln!(w, "{}", derive)?;
                write!(w, "pub enum {}", v.name())?;
                if ast.generics().contains(v.name()) {
                    write!(w, "{}", TRAIT_BOUNDS)?;
                }

                writeln!(w, " {{")?;
                for case in v.cases.iter() {
                    // A single case statement may have many case values tied to it
                    // if fallthrough values are used:
                    //
                    // 	case 1:
                    // 	case 2:
                    // 		// statement
                    //
                    for c_value in case.case_values.iter() {
                        write!(w, "{}(", NonDigitName(SafeName(&c_value)))?;

                        match case.field_value.unwrap_array() {
                            BasicType::Opaque => write!(w, "T")?,
                            BasicType::String => write!(w, "String")?,
                            BasicType::Ident(i) if ast.generics().contains(i.as_ref()) => {
                                write!(w, "{}<T>", i)?
                            }
                            _ => write!(w, "{}", case.field_value)?,
                        }

                        writeln!(w, "),")?;
                    }
                }

                // There may also be several "void" cases
                for c in v.void_cases.iter() {
                    writeln!(w, "{},", NonDigitName(SafeName(c.as_str())))?;
                }

                if v.default.is_some() {
                    writeln!(w, "default,")?;
                }

                writeln!(w, "}}")?;
            }
            AstType::Enum(v) => {
                writeln!(w, "{}", derive)?;
                writeln!(w, "pub enum {} {{", v.name)?;
                for var in v.variants.iter() {
                    writeln!(w, "{} = {},", var.name, var.value)?;
                }
                writeln!(w, "}}")?;
            }
            AstType::Typedef(v) => {
                // No typedefs to self - this occurs because the ident/type values
                // convert common types directly.
                if v.target == *v.alias.unwrap_array() {
                    continue;
                }

                // For typedefs, the array identifier is defined on the alias.
                //
                // Wrap the target in the same array as the alias to generate the
                // array container for the target.
                let target = match &v.alias {
                    ArrayType::None(_) => ArrayType::None(&v.target),
                    ArrayType::FixedSize(_, s) => ArrayType::FixedSize(&v.target, s.clone()),
                    ArrayType::VariableSize(_, s) => ArrayType::VariableSize(&v.target, s.clone()),
                };

                writeln!(w, "{}", derive)?;
                write!(w, "pub struct {}", v.alias.unwrap_array().as_str())?;
                if ast.generics().contains(v.target.as_str()) || v.target.is_opaque() {
                    write!(
                        w,
                        "<{}>",
                        TRAIT_BOUNDS.split("where").nth(1).unwrap_or("").trim()
                    )?;
                }

                // If the target is the opaque type, it should not have array
                // quantifiers - the opaque type has a variable length already.
                if v.target.is_opaque() {
                    writeln!(w, "(pub T);")?;
                    continue;
                }

                if ast.generics().contains(v.target.as_str()) {
                    write!(w, " (pub ")?;
                    target.write_with_bounds(w, Some(&["T"]))?;
                    writeln!(w, ");")?;
                } else {
                    writeln!(w, "(pub {});", target)?;
                }
            }
        };
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    macro_rules! test_convert {
        ($name: ident, $input: expr, $want: expr) => {
            #[test]
            fn $name() {
                let ast = Ast::new($input).unwrap();

                let mut got = String::new();
                print_types(&mut got, &ast, "#[derive(Debug, PartialEq)]").unwrap();

                assert_eq!(got, $want);
            }
        };
    }

    test_convert!(
        test_union,
        r#"
			union locker4 switch (bool new_lock_owner) {
			case TRUE:
					open_to_lock_owner4     open_owner;
			case FALSE:
					exist_lock_owner4       lock_owner;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub enum locker4 {
TRUE(open_to_lock_owner4),
FALSE(exist_lock_owner4),
}
"#
    );

    test_convert!(
        test_union_with_default,
        r#"
			union LOCKT4res switch (nfsstat4 status) {
				case NFS4ERR_DENIED:
						LOCK4denied    denied;
				case NFS4_OK:
						void;
				default:
						void;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub enum LOCKT4res {
NFS4ERR_DENIED(LOCK4denied),
NFS4_OK,
default,
}
"#
    );

    test_convert!(
        test_union_fallthrough_with_void,
        r#"
			union createtype4 switch (nfs_ftype4 type) {
				case NF4LNK:
						linktext4 linkdata;
				case NF4BLK:
				case NF4CHR:
						specdata4 devdata;
				case NF4SOCK:
				case NF4FIFO:
				case NF4DIR:
						void;
				default:
						void;  /* server should return NFS4ERR_BADTYPE */
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub enum createtype4 {
NF4LNK(linktext4),
NF4BLK(specdata4),
NF4CHR(specdata4),
NF4SOCK,
NF4FIFO,
NF4DIR,
default,
}
"#
    );

    test_convert!(
        test_struct_nested_to_array_variable_max_union_generic,
        r#"
            union u_type_name switch (unsigned int s) {
                case 1:    opaque some_var;
            };
            struct CB_COMPOUND4res {
                u_type_name   resarray<42>;
            };
        "#,
        r#"#[derive(Debug, PartialEq)]
pub struct CB_COMPOUND4res<T> where T: AsRef<[u8]> + Debug {
pub resarray: Vec<u_type_name<T>>,
}
#[derive(Debug, PartialEq)]
pub enum u_type_name<T> where T: AsRef<[u8]> + Debug {
v_1(T),
}
"#
    );

    test_convert!(
        test_struct,
        r#"
			/*
			* LOCK/LOCKT/LOCKU: Record lock management
			*/
			struct LOCK4args {
					/* CURRENT_FH: file */
					nfs_lock_type4  locktype;
					bool            reclaim;
					offset4         offset;
					length4         length;
					locker4         locker;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct LOCK4args {
pub locktype: nfs_lock_type4,
pub reclaim: bool,
pub offset: offset4,
pub length: length4,
pub locker: locker4,
}
"#
    );

    test_convert!(
        test_struct_fixed_array,
        r#"
			struct stateid4 {
					uint32_t        seqid;
					opaque          other[3];
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct stateid4<T> where T: AsRef<[u8]> + Debug {
pub seqid: u32,
pub other: T,
}
"#
    );

    test_convert!(
        test_struct_fixed_array_const,
        r#"
            const SIZE = 3;
			struct stateid4 {
					uint32_t        seqid;
					opaque          other[SIZE];
			};
		"#,
        r#"pub const SIZE: u32 = 3;
#[derive(Debug, PartialEq)]
pub struct stateid4<T> where T: AsRef<[u8]> + Debug {
pub seqid: u32,
pub other: T,
}
"#
    );

    test_convert!(
        test_struct_variable_array_with_max,
        r#"
			struct nfs_client_id4 {
					verifier4       verifier;
					opaque          id<3>;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct nfs_client_id4<T> where T: AsRef<[u8]> + Debug {
pub verifier: verifier4,
pub id: T,
}
"#
    );

    test_convert!(
        test_struct_variable_array_with_max_const,
        r#"
            const SIZE = 3;
			struct nfs_client_id4 {
					verifier4       verifier;
					opaque          id<SIZE>;
			};
		"#,
        r#"pub const SIZE: u32 = 3;
#[derive(Debug, PartialEq)]
pub struct nfs_client_id4<T> where T: AsRef<[u8]> + Debug {
pub verifier: verifier4,
pub id: T,
}
"#
    );

    test_convert!(
        test_struct_variable_array_without_max,
        r#"
			struct READ4resok {
					bool            eof;
					opaque          data<>;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct READ4resok<T> where T: AsRef<[u8]> + Debug {
pub eof: bool,
pub data: T,
}
"#
    );

    test_convert!(
        test_struct_string,
        r#"
			struct clientaddr4 {
					/* see struct rpcb in RFC 1833 */
					string r_netid<>;       /* network id */
					string r_addr<>;        /* universal address */
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct clientaddr4 {
pub r_netid: String,
pub r_addr: String,
}
"#
    );

    test_convert!(
        test_struct_string_max_len,
        r#"
			struct clientaddr4 {
					/* see struct rpcb in RFC 1833 */
					string r_netid<42>;       /* network id */
					string r_addr<24>;        /* universal address */
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct clientaddr4 {
pub r_netid: String,
pub r_addr: String,
}
"#
    );

    test_convert!(
        test_enum,
        r#"
			enum opentype4 {
					OPEN4_NOCREATE  = 0,
					OPEN4_CREATE    = 1
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub enum opentype4 {
OPEN4_NOCREATE = 0,
OPEN4_CREATE = 1,
}
"#
    );

    test_convert!(
        test_const,
        r#"
			const ACL4_SUPPORT_ALLOW_ACL    = 0x00000001;
		"#,
        r#"pub const ACL4_SUPPORT_ALLOW_ACL: u32 = 0x00000001;
"#
    );

    test_convert!(
        test_typedef,
        r#"
			typedef uint32_t        acetype4;
			typedef opaque          utf8string<>;
			typedef opaque          sec_oid4;
			typedef utf8string      utf8str_cis;
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct acetype4(pub u32);
#[derive(Debug, PartialEq)]
pub struct sec_oid4<T: AsRef<[u8]> + Debug>(pub T);
#[derive(Debug, PartialEq)]
pub struct utf8str_cis<T: AsRef<[u8]> + Debug> (pub utf8string<T>);
#[derive(Debug, PartialEq)]
pub struct utf8string<T: AsRef<[u8]> + Debug>(pub T);
"#
    );

    test_convert!(
        test_struct_typedef_structs,
        r#"
            typedef uint32_t        acemask4;
            typedef utf8string      utf8str_mixed;
            typedef opaque  utf8string<>;
            struct nfsace4 {
                acemask4                access_mask;
                utf8str_mixed           who;
            };
        "#,
        r#"#[derive(Debug, PartialEq)]
pub struct acemask4(pub u32);
#[derive(Debug, PartialEq)]
pub struct nfsace4<T> where T: AsRef<[u8]> + Debug {
pub access_mask: acemask4,
pub who: utf8str_mixed<T>,
}
#[derive(Debug, PartialEq)]
pub struct utf8str_mixed<T: AsRef<[u8]> + Debug> (pub utf8string<T>);
#[derive(Debug, PartialEq)]
pub struct utf8string<T: AsRef<[u8]> + Debug>(pub T);
"#
    );

    test_convert!(
        test_convert_unsigned_int,
        r#"
			struct cb_client4 {
					unsigned int    cb_program;
					clientaddr4     cb_location;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct cb_client4 {
pub cb_program: u32,
pub cb_location: clientaddr4,
}
"#
    );

    test_convert!(
        test_generic_pushup_struct,
        r#"
			struct stateid4 {
				uint32_t        seqid;
				opaque          other[NFS4_OTHER_SIZE];
			};

			struct generic_field {
				stateid4        inner;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct generic_field<T> where T: AsRef<[u8]> + Debug {
pub inner: stateid4<T>,
}
#[derive(Debug, PartialEq)]
pub struct stateid4<T> where T: AsRef<[u8]> + Debug {
pub seqid: u32,
pub other: T,
}
"#
    );

    test_convert!(
        test_generic_pushup_union,
        r#"
			struct stateid4 {
				opaque          other[NFS4_OTHER_SIZE];
			};

			union nfs_argop4 switch (nfs_opnum4 argop) {
				case OP_GETATTR:       stateid4 field_name;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub enum nfs_argop4<T> where T: AsRef<[u8]> + Debug {
OP_GETATTR(stateid4<T>),
}
#[derive(Debug, PartialEq)]
pub struct stateid4<T> where T: AsRef<[u8]> + Debug {
pub other: T,
}
"#
    );

    test_convert!(
        test_reserved_keyword_struct_field_name,
        r#"
			struct nfsace4 {
					acetype4                type;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct nfsace4 {
pub type_v: acetype4,
}
"#
    );

    test_convert!(
        test_reserved_keyword_union_field_name_ignored,
        r#"
			union CB_GETATTR4res switch (unsigned int status) {
			case 1:
				CB_GETATTR4resok       resok4;
			case type:
				SomeType       async;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub enum CB_GETATTR4res {
v_1(CB_GETATTR4resok),
type(SomeType),
}
"#
    );

    test_convert!(
        test_multiple_void_union,
        r#"
			union nfs_argop4 switch (nfs_opnum4 argop) {
				case OP_GETATTR:       GETATTR4args opgetattr;
				case OP_GETFH:         void;
				case OP_LINK:          LINK4args oplink;
				case OP_LOOKUPP:       void;
				case OP_NVERIFY:       NVERIFY4args opnverify;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub enum nfs_argop4 {
OP_GETATTR(GETATTR4args),
OP_LINK(LINK4args),
OP_NVERIFY(NVERIFY4args),
OP_GETFH,
OP_LOOKUPP,
}
"#
    );

    test_convert!(
        test_linked_list,
        r#"
			struct entry4 {
					entry4          *nextentry;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct entry4 {
pub nextentry: Option<Box<entry4>>,
}
"#
    );

    test_convert!(
        test_typedef_array,
        r#"
            typedef small alias<>;
			struct small {
				uint32_t        id;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct alias(pub Vec<small>);
#[derive(Debug, PartialEq)]
pub struct small {
pub id: u32,
}
"#
    );

    test_convert!(
        test_typedef_array_generic,
        r#"
            typedef small alias<>;
			struct small {
				opaque        id;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct alias<T: AsRef<[u8]> + Debug> (pub Vec<small<T>>);
#[derive(Debug, PartialEq)]
pub struct small<T> where T: AsRef<[u8]> + Debug {
pub id: T,
}
"#
    );

    test_convert!(
        test_typedef_fixed_array_known,
        r#"
            typedef small alias[8];
			struct small {
				uint32_t        id;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct alias(pub [small; 8]);
#[derive(Debug, PartialEq)]
pub struct small {
pub id: u32,
}
"#
    );

    test_convert!(
        test_typedef_fixed_array_known_generic,
        r#"
            typedef small alias[8];
			struct small {
				opaque        id;
			};
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct alias<T: AsRef<[u8]> + Debug> (pub [small<T>; 8]);
#[derive(Debug, PartialEq)]
pub struct small<T> where T: AsRef<[u8]> + Debug {
pub id: T,
}
"#
    );

    test_convert!(
        test_typedef_fixed_array_constant,
        r#"
            const SIZE        = 8;
            typedef small alias[SIZE];
			struct small {
				uint32_t        id;
			};
		"#,
        r#"pub const SIZE: u32 = 8;
#[derive(Debug, PartialEq)]
pub struct alias(pub [small; SIZE as usize]);
#[derive(Debug, PartialEq)]
pub struct small {
pub id: u32,
}
"#
    );

    test_convert!(
        test_typedef_fixed_array_constant_generic,
        r#"
            const SIZE        = 8;
            typedef small alias[SIZE];
			struct small {
				opaque        id;
			};
		"#,
        r#"pub const SIZE: u32 = 8;
#[derive(Debug, PartialEq)]
pub struct alias<T: AsRef<[u8]> + Debug> (pub [small<T>; SIZE as usize]);
#[derive(Debug, PartialEq)]
pub struct small<T> where T: AsRef<[u8]> + Debug {
pub id: T,
}
"#
    );

    test_convert!(
        test_typedef_generic_array_fixed_opaque,
        r#"
            typedef opaque  alias[42];
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct alias<T: AsRef<[u8]> + Debug>(pub T);
"#
    );

    test_convert!(
        test_typedef_generic_array_fixed_constant_opaque,
        r#"
            const SIZE = 42;
            typedef opaque  alias[SIZE];
		"#,
        r#"pub const SIZE: u32 = 42;
#[derive(Debug, PartialEq)]
pub struct alias<T: AsRef<[u8]> + Debug>(pub T);
"#
    );

    test_convert!(
        test_typedef_generic_array_variable_opaque,
        r#"
            typedef opaque  alias<42>;
		"#,
        r#"#[derive(Debug, PartialEq)]
pub struct alias<T: AsRef<[u8]> + Debug>(pub T);
"#
    );

    test_convert!(
        test_typedef_generic_array_variable_constant_opaque,
        r#"
            const SIZE = 42;
            typedef opaque  alias<SIZE>;
		"#,
        r#"pub const SIZE: u32 = 42;
#[derive(Debug, PartialEq)]
pub struct alias<T: AsRef<[u8]> + Debug>(pub T);
"#
    );
}