forked from RustCrypto/formats
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1450 lines (1379 loc) · 57 KB
/
Copy pathlib.rs
File metadata and controls
1450 lines (1379 loc) · 57 KB
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Derive macros for traits in `tls_codec`
//!
//! Derive macros can be used to automatically implement the
//! [`Serialize`](../tls_codec::Serialize),
//! [`SerializeBytes`](../tls_codec::SerializeBytes),
//! [`Deserialize`](../tls_codec::Deserialize),
//! [`DeserializeBytes`](../tls_codec::DeserializeBytes), and
//! [`Size`](../tls_codec::Size) traits for structs and enums. Note that the
//! functions of the [`Serialize`](../tls_codec::Serialize) and
//! [`Deserialize`](../tls_codec::Deserialize) traits (and thus the
//! corresponding derive macros) require the `"std"` feature to work.
//!
//! ## Warning
//!
//! The derive macros support deriving the `tls_codec` traits for enumerations
//! and the resulting serialized format complies with [the "variants" section of
//! the TLS RFC](https://datatracker.ietf.org/doc/html/rfc8446#section-3.8).
//! However support is limited to enumerations that are serialized with their
//! discriminant immediately followed by the variant data. If this is not
//! appropriate (e.g. the format requires other fields between the discriminant
//! and variant data), the `tls_codec` traits can be implemented manually.
//!
//! ## Parsing unknown values
//!
//! In many cases it is necessary to deserialize structs with unknown values,
//! e.g. when receiving unknown TLS extensions. In this case the deserialize
//! function returns an `Error::UnknownValue` with a `u64` value of the unknown
//! type.
//!
//! ```
//! # #[cfg(feature = "std")]
//! # {
//! use tls_codec_derive::{TlsDeserialize, TlsSerialize, TlsSize};
//!
//! #[derive(TlsDeserialize, TlsSerialize, TlsSize)]
//! #[repr(u16)]
//! enum TypeWithUnknowns {
//! First = 1,
//! Second = 2,
//! }
//!
//! #[test]
//! fn type_with_unknowns() {
//! let incoming = [0x00u8, 0x03]; // This must be parsed into TypeWithUnknowns into an unknown
//! let deserialized = TypeWithUnknowns::tls_deserialize_exact(incoming);
//! assert!(matches!(deserialized, Err(Error::UnknownValue(3))));
//! }
//! # }
//! ```
//!
//! ## Available attributes
//!
//! Attributes can be used to control serialization and deserialization on a
//! per-field basis.
//!
//! ### with
//!
//! ```text
//! #[tls_codec(with = "prefix")]
//! ```
//!
//! This attribute may be applied to a struct field. It indicates that deriving
//! any of the `tls_codec` traits for the containing struct calls the following
//! functions:
//! - `prefix::tls_deserialize` when deriving `Deserialize`
//! - `prefix::tls_serialize` when deriving `Serialize`
//! - `prefix::tls_serialized_len` when deriving `Size`
//!
//! `prefix` can be a path to a module, type or trait where the functions are
//! defined.
//!
//! Their expected signatures match the corresponding methods in the traits.
//!
//! ```
//! # #[cfg(feature = "std")]
//! # {
//! use tls_codec_derive::{TlsSerialize, TlsSize};
//!
//! #[derive(TlsSerialize, TlsSize)]
//! struct Bytes {
//! #[tls_codec(with = "bytes")]
//! values: Vec<u8>,
//! }
//!
//! mod bytes {
//! use std::io::Write;
//! use tls_codec::{Serialize, Size, TlsByteSliceU32};
//!
//! pub fn tls_serialized_len(v: &[u8]) -> usize {
//! TlsByteSliceU32(v).tls_serialized_len()
//! }
//!
//! pub fn tls_serialized_len_checked(v: &[u8]) -> Option<usize> {
//! TlsByteSliceU32(v).tls_serialized_len_checked()
//! }
//!
//! pub fn tls_serialize<W: Write>(v: &[u8], writer: &mut W) -> Result<usize, tls_codec::Error> {
//! TlsByteSliceU32(v).tls_serialize(writer)
//! }
//! }
//! # }
//! ```
//!
//! ### discriminant
//!
//! ```text
//! #[tls_codec(discriminant = 123)]
//! #[tls_codec(discriminant = "path::to::const::or::enum::Variant")]
//! ```
//!
//! This attribute may be applied to an enum variant to specify the discriminant
//! to use when serializing it. If all variants are units (e.g. they do not have
//! any data), this attribute must not be used and the desired discriminants
//! should be assigned to the variants using standard Rust syntax (`Variant =
//! Discriminant`).
//!
//! For enumerations with non-unit variants, if no variant has this attribute,
//! the serialization discriminants will start from zero. If this attribute is
//! used on a variant and the following variant does not have it, its
//! discriminant will be equal to the previous variant discriminant plus 1. This
//! behavior is referred to as "implicit discriminants".
//!
//! You can also provide paths that lead to `const` definitions or enum
//! Variants. The important thing is that any of those path expressions must
//! resolve to something that can be coerced to the `#[repr(enum_repr)]` of the
//! enum. Please note that there are checks performed at compile time to check
//! if the provided value fits within the bounds of the `enum_repr` to avoid
//! misuse.
//!
//! Note: When using paths *once* in your enum discriminants, as we do not have
//! enough information to deduce the next implicit discriminant (the constant
//! expressions those paths resolve is only evaluated at a later compilation
//! stage than macros), you will be forced to use explicit discriminants for all
//! the other Variants of your enum.
//!
//! ```
//! # #[cfg(feature = "std")]
//! # {
//! use tls_codec_derive::{TlsSerialize, TlsSize};
//!
//! const CONST_DISCRIMINANT: u8 = 5;
//! #[repr(u8)]
//! enum TokenType {
//! Constant = 3,
//! Variant = 4,
//! }
//!
//! #[derive(TlsSerialize, TlsSize)]
//! #[repr(u8)]
//! enum TokenImplicit {
//! #[tls_codec(discriminant = 5)]
//! Int(u32),
//! // This will have the discriminant 6 as it's implicitly determined
//! Bytes([u8; 16]),
//! }
//!
//! #[derive(TlsSerialize, TlsSize)]
//! #[repr(u8)]
//! enum TokenExplicit {
//! #[tls_codec(discriminant = "TokenType::Constant")]
//! Constant(u32),
//! #[tls_codec(discriminant = "TokenType::Variant")]
//! Variant(Vec<u8>),
//! #[tls_codec(discriminant = "CONST_DISCRIMINANT")]
//! StaticConstant(u8),
//! }
//! # }
//! ```
//!
//! ### skip
//!
//! ```text
//! #[tls_codec(skip)]
//! ```
//!
//! This attribute may be applied to a struct field to specify that it should be
//! skipped. Skipping means that the field at hand will neither be serialized
//! into TLS bytes nor deserialized from TLS bytes. For deserialization, it is
//! required to populate the field with a known value. Thus, when `skip` is
//! used, the field type needs to implement the [Default] trait so it can be
//! populated with a default value.
//!
//! ```
//! # #[cfg(feature = "std")]
//! # {
//! use tls_codec_derive::{TlsSerialize, TlsDeserialize, TlsSize};
//!
//! struct CustomStruct;
//!
//! impl Default for CustomStruct {
//! fn default() -> Self {
//! CustomStruct {}
//! }
//! }
//!
//! #[derive(TlsSerialize, TlsDeserialize, TlsSize)]
//! struct StructWithSkip {
//! a: u8,
//! #[tls_codec(skip)]
//! b: CustomStruct,
//! c: u8,
//! }
//! # }
//! ```
//!
//! ## Conditional deserialization via the `conditionally_deserializable` attribute macro
//!
//! In some cases, it can be useful to have two variants of a struct, where one
//! is deserializable and one isn't. For example, the deserializable variant of
//! the struct could represent an unverified message, where only verification
//! produces the verified variant. Further processing could then be restricted
//! to the undeserializable struct variant.
//!
//! A pattern like this can be created via the `conditionally_deserializable`
//! attribute macro (requires the `conditional_deserialization` feature flag).
//!
//! The macro adds a boolean const generic to the struct and creates two
//! aliases, one for the deserializable variant (with a "`Deserializable`"
//! prefix) and one for the undeserializable one (with an "`Undeserializable`"
//! prefix).
//!
//! ```
//! # #[cfg(all(feature = "conditional_deserialization", feature = "std"))]
//! # {
//! use tls_codec::{Serialize, Deserialize};
//! use tls_codec_derive::{TlsSerialize, TlsSize, conditionally_deserializable};
//!
//! #[conditionally_deserializable]
//! #[derive(TlsSize, TlsSerialize, PartialEq, Debug)]
//! struct ExampleStruct {
//! a: u8,
//! b: u16,
//! }
//!
//! let undeserializable_struct = UndeserializableExampleStruct { a: 1, b: 2 };
//! let serialized = undeserializable_struct.tls_serialize_detached().unwrap();
//! let deserializable_struct =
//! DeserializableExampleStruct::tls_deserialize(&mut serialized.as_slice()).unwrap();
//! # }
//! ```
//!
//! The helper macro `#[tls_codec(cd_field)]` can be used to mark a field as
//! conditionally deserializable, thus allowing nested conditionally
//! deserializable structs.
//!
//! ```
//! # #[cfg(all(feature = "conditional_deserialization", feature = "std"))]
//! # {
//! use tls_codec::{Serialize, Deserialize};
//! use tls_codec_derive::{TlsSerialize, TlsSize, conditionally_deserializable};
//!
//! #[conditionally_deserializable]
//! #[derive(TlsSize, TlsSerialize, PartialEq, Debug)]
//! struct ExampleStruct {
//! a: u8,
//! b: u16,
//! }
//!
//! #[conditionally_deserializable]
//! #[derive(TlsSize, TlsSerialize, PartialEq, Debug)]
//! struct NestedExampleStruct {
//! #[tls_codec(cd_field)]
//! example_struct: ExampleStruct,
//! }
//! # }
//! ```
extern crate proc_macro;
extern crate proc_macro2;
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::quote;
use syn::{
self, Attribute, Data, DeriveInput, Expr, ExprLit, ExprPath, Field, Generics, Ident, Lit,
Member, Meta, Result, Token, Type, parse_macro_input, punctuated::Punctuated, token::Comma,
};
#[cfg(feature = "conditional_deserialization")]
use syn::{ConstParam, ImplGenerics, ItemStruct, TypeGenerics, parse_quote};
/// Attribute name to identify attributes to be processed by derive-macros in this crate.
const ATTR_IDENT: &str = "tls_codec";
/// Prefix to add to `tls_codec` functions
///
/// This is either `<Type as Trait>` or a custom module containing the functions.
#[derive(Clone)]
enum Prefix {
Type(Type),
Custom(ExprPath),
}
impl Prefix {
/// Returns the path prefix to use for functions from the given trait.
fn for_trait(&self, trait_name: &str) -> TokenStream2 {
let trait_name = Ident::new(trait_name, Span::call_site());
match self {
Prefix::Type(ty) => quote! { <#ty as tls_codec::#trait_name> },
Prefix::Custom(p) => quote! { #p },
}
}
}
#[derive(Clone)]
struct Struct {
call_site: Span,
ident: Ident,
generics: Generics,
members: Vec<Member>,
member_prefixes: Vec<Prefix>,
member_skips: Vec<bool>,
}
#[derive(Clone)]
struct Enum {
call_site: Span,
ident: Ident,
generics: Generics,
repr: Ident,
variants: Vec<Variant>,
discriminant_constants: TokenStream2,
}
#[derive(Clone)]
struct Variant {
ident: Ident,
members: Vec<Member>,
member_prefixes: Vec<Prefix>,
}
#[derive(Clone)]
enum DiscriminantValue {
Literal(usize),
Path(ExprPath),
}
#[derive(Clone)]
enum TlsStruct {
Struct(Struct),
Enum(Enum),
}
/// Attributes supported by derive-macros in this crate
#[derive(Clone)]
enum TlsAttr {
/// Prefix for custom serialization functions
With(ExprPath),
/// Custom literal discriminant for an enum variant
Discriminant(DiscriminantValue),
/// Skip this attribute during (de)serialization.
///
/// Note: The type of the attribute needs to implement [Default].
/// This is required to populate the field with a known
/// value during deserialization.
Skip,
#[cfg(feature = "conditional_deserialization")]
CdField,
}
impl TlsAttr {
fn name(&self) -> &'static str {
match self {
TlsAttr::With(_) => "with",
TlsAttr::Discriminant(_) => "discriminant",
TlsAttr::Skip => "skip",
#[cfg(feature = "conditional_deserialization")]
TlsAttr::CdField => "cd_field",
}
}
/// Parses attributes of the form, `#[tls_codec(with = <string>)]`,
/// `#[tls_codec(discriminant = <number>)]`, and `#[tls_codec(skip)]`.
fn parse(attr: &Attribute) -> Result<Vec<TlsAttr>> {
fn lit(e: &Expr) -> Result<&Lit> {
if let Expr::Lit(ExprLit { lit, .. }) = e {
Ok(lit)
} else {
Err(syn::Error::new_spanned(e, "expected literal"))
}
}
if attr.path().get_ident().is_none_or(|id| id != ATTR_IDENT) {
return Ok(Vec::new());
}
attr.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)?
.iter()
.map(|item| match item {
Meta::NameValue(kv) => kv
.path
.get_ident()
.map(|ident| {
let ident_str = ident.to_string();
match &*ident_str {
"discriminant" => match lit(&kv.value)? {
Lit::Int(i) => i
.base10_parse::<usize>()
.map(DiscriminantValue::Literal)
.map(TlsAttr::Discriminant),
Lit::Str(raw_path) => raw_path
.parse::<ExprPath>()
.map(DiscriminantValue::Path)
.map(TlsAttr::Discriminant),
_ => Err(syn::Error::new_spanned(
&kv.value,
"Expected integer literal",
)),
},
"with" => match lit(&kv.value)? {
Lit::Str(s) => s.parse::<ExprPath>().map(TlsAttr::With),
_ => Err(syn::Error::new_spanned(
&kv.value,
"Expected string literal",
)),
},
_ => Err(syn::Error::new_spanned(
ident,
format!("Unexpected identifier {ident}"),
)),
}
})
.unwrap_or_else(|| {
Err(syn::Error::new_spanned(&kv.path, "Expected identifier"))
}),
Meta::Path(path) => {
if let Some(ident) = path.get_ident() {
match ident.to_string().to_ascii_lowercase().as_ref() {
"skip" => Ok(TlsAttr::Skip),
#[cfg(feature = "conditional_deserialization")]
"cd_field" => Ok(TlsAttr::CdField),
_ => Err(syn::Error::new_spanned(
ident,
format!("Unexpected identifier {ident}"),
)),
}
} else {
Err(syn::Error::new_spanned(path, "Expected identifier"))
}
}
_ => Err(syn::Error::new_spanned(item, "Invalid attribute syntax")),
})
.collect()
}
/// Parses attributes of the form:
/// ```text
/// #[tls_codec(with = "module", ...)]
/// ```
fn parse_multi(attrs: &[Attribute]) -> Result<Vec<TlsAttr>> {
attrs.iter().try_fold(Vec::new(), |mut acc, attr| {
acc.extend(TlsAttr::parse(attr)?);
Ok(acc)
})
}
}
/// Gets the [`Prefix`] for a field, i.e. the type itself or a path to prepend to the `tls_codec`
/// functions (e.g. a module or type).
fn function_prefix(field: &Field) -> Result<Prefix> {
let prefix = TlsAttr::parse_multi(&field.attrs)?
.into_iter()
.try_fold(None, |path, attr| match (path, attr) {
(None, TlsAttr::With(p)) => Ok(Some(p)),
(Some(_), TlsAttr::With(p)) => Err(syn::Error::new_spanned(
p,
"Attribute `with` specified more than once",
)),
(path, _) => Ok(path),
})?
.map(Prefix::Custom)
.unwrap_or_else(|| Prefix::Type(field.ty.clone()));
Ok(prefix)
}
/// Process all attributes of a field and return a single, true or false, `skip` value.
/// This function will return an error in the case of multiple `skip` attributes.
fn function_skip(field: &Field) -> Result<bool> {
let skip = TlsAttr::parse_multi(&field.attrs)?
.into_iter()
.try_fold(None, |skip, attr| match (skip, attr) {
(None, TlsAttr::Skip) => Ok(Some(true)),
(Some(_), TlsAttr::Skip) => Err(syn::Error::new(
Span::call_site(),
"Attribute `skip` specified more than once",
)),
(skip, _) => Ok(skip),
})?
.unwrap_or(false);
Ok(skip)
}
/// Process all attributes of a field and return a single, true or false, `cd_field` value.
/// This function will return an error in the case of multiple `cd` attributes.
#[cfg(feature = "conditional_deserialization")]
fn function_cd(field: &Field) -> Result<bool> {
let skip = TlsAttr::parse_multi(&field.attrs)?
.into_iter()
.try_fold(None, |skip, attr| match (skip, attr) {
(None, TlsAttr::CdField) => Ok(Some(true)),
(Some(_), TlsAttr::CdField) => Err(syn::Error::new(
Span::call_site(),
"Attribute `cd_field` specified more than once",
)),
(skip, _) => Ok(skip),
})?
.unwrap_or(false);
Ok(skip)
}
/// Gets the serialization discriminant if specified.
fn discriminant_value(attrs: &[Attribute]) -> Result<Option<DiscriminantValue>> {
TlsAttr::parse_multi(attrs)?
.into_iter()
.try_fold(None, |discriminant, attr| match (discriminant, attr) {
(None, TlsAttr::Discriminant(d)) => Ok(Some(d)),
(Some(_), TlsAttr::Discriminant(_)) => Err(syn::Error::new(
Span::call_site(),
"Attribute `discriminant` specified more than once",
)),
(_, attr) => Err(syn::Error::new(
Span::call_site(),
format!("Unrecognized variant attribute `{}`", attr.name()),
)),
})
}
fn fields_to_members(fields: &syn::Fields) -> Vec<Member> {
fields
.iter()
.enumerate()
.map(|(i, field)| {
field
.ident
.clone()
.map_or_else(|| Member::Unnamed(syn::Index::from(i)), Member::Named)
})
.collect()
}
/// Gets the [`Prefix`]es for all fields, i.e. the types themselves or paths to prepend to the
/// `tls_codec` functions (e.g. a module or type).
fn fields_to_member_prefixes(fields: &syn::Fields) -> Result<Vec<Prefix>> {
fields.iter().map(function_prefix).collect()
}
fn fields_to_member_skips(fields: &syn::Fields) -> Result<Vec<bool>> {
fields.iter().map(function_skip).collect()
}
fn parse_ast(ast: DeriveInput) -> Result<TlsStruct> {
let call_site = Span::call_site();
let ident = ast.ident.clone();
let generics = ast.generics.clone();
match ast.data {
Data::Struct(st) => {
let members = fields_to_members(&st.fields);
let member_prefixes = fields_to_member_prefixes(&st.fields)?;
let member_skips = fields_to_member_skips(&st.fields)?;
Ok(TlsStruct::Struct(Struct {
call_site,
ident,
generics,
members,
member_prefixes,
member_skips,
}))
}
// Enums.
// Note that they require a repr attribute.
Data::Enum(syn::DataEnum { variants, .. }) => {
let mut repr = None;
for attr in ast.attrs {
if attr.path().is_ident("repr") {
let ty = attr.parse_args()?;
repr = Some(ty);
break;
}
}
let repr =
repr.ok_or_else(|| syn::Error::new(call_site, "missing #[repr(...)] attribute"))?;
let discriminant_constants = define_discriminant_constants(&ident, &repr, &variants)?;
let variants = variants
.into_iter()
.map(|variant| {
Ok(Variant {
ident: variant.ident,
members: fields_to_members(&variant.fields),
member_prefixes: fields_to_member_prefixes(&variant.fields)?,
})
})
.collect::<Result<Vec<_>>>()?;
Ok(TlsStruct::Enum(Enum {
call_site,
ident,
generics,
repr,
variants,
discriminant_constants,
}))
}
Data::Union(_) => unimplemented!(),
}
}
enum SerializeVariant {
Write,
Bytes,
}
#[proc_macro_derive(TlsSize, attributes(tls_codec))]
pub fn size_macro_derive(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let parsed_ast = match parse_ast(ast) {
Ok(ast) => ast,
Err(err_ts) => return err_ts.into_compile_error().into(),
};
impl_tls_size(parsed_ast).into()
}
#[proc_macro_derive(TlsSerialize, attributes(tls_codec))]
pub fn serialize_macro_derive(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let parsed_ast = match parse_ast(ast) {
Ok(ast) => ast,
Err(err_ts) => return err_ts.into_compile_error().into(),
};
impl_serialize(parsed_ast, SerializeVariant::Write).into()
}
#[proc_macro_derive(TlsDeserialize, attributes(tls_codec))]
pub fn deserialize_macro_derive(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let parsed_ast = match parse_ast(ast) {
Ok(ast) => ast,
Err(err_ts) => return err_ts.into_compile_error().into(),
};
impl_deserialize(parsed_ast).into()
}
#[proc_macro_derive(TlsDeserializeBytes, attributes(tls_codec))]
pub fn deserialize_bytes_macro_derive(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let parsed_ast = match parse_ast(ast) {
Ok(ast) => ast,
Err(err_ts) => return err_ts.into_compile_error().into(),
};
impl_deserialize_bytes(parsed_ast).into()
}
#[proc_macro_derive(TlsSerializeBytes, attributes(tls_codec))]
pub fn serialize_bytes_macro_derive(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let parsed_ast = match parse_ast(ast) {
Ok(ast) => ast,
Err(err_ts) => return err_ts.into_compile_error().into(),
};
impl_serialize(parsed_ast, SerializeVariant::Bytes).into()
}
/// Returns identifiers to use as bindings in generated code
fn make_n_ids(n: usize) -> Vec<Ident> {
(0..n)
.map(|i| Ident::new(&format!("__arg{i}"), Span::call_site()))
.collect()
}
/// Returns identifier to define a constant equal to the discriminant of a variant
fn discriminant_id(variant: &Ident) -> Ident {
Ident::new(&format!("__TLS_CODEC_{variant}"), Span::call_site())
}
/// Returns definitions of constants equal to the discriminants of each variant
fn define_discriminant_constants(
enum_ident: &Ident,
repr: &Ident,
variants: &Punctuated<syn::Variant, Comma>,
) -> Result<TokenStream2> {
let all_variants_are_unit = variants
.iter()
.all(|variant| matches!(variant.fields, syn::Fields::Unit));
let discriminant_constants = if all_variants_are_unit {
variants
.iter()
.map(|variant| {
let variant_id = &variant.ident;
let constant_id = discriminant_id(variant_id);
if discriminant_value(&variant.attrs)?.is_some() {
Err(syn::Error::new(
Span::call_site(),
"The tls_codec discriminant attribute must only be used in enumerations \
with at least one non-unit variant. When all variants are units, \
discriminants can be assigned to variants directly.",
))
} else {
Ok(quote! {
#[allow(non_upper_case_globals)]
const #constant_id: #repr = #enum_ident::#variant_id as #repr;
})
}
})
.collect::<Result<Vec<_>>>()?
} else {
let mut spans = Vec::with_capacity(variants.len());
let mut implicit_discriminant = 0usize;
let mut discriminant_has_paths = false;
for variant in variants.iter() {
let constant_id = discriminant_id(&variant.ident);
let tokens = if let Some(value) = discriminant_value(&variant.attrs)? {
match value {
DiscriminantValue::Literal(value) => {
implicit_discriminant = value;
quote! {
#[allow(non_upper_case_globals)]
const #constant_id: #repr = {
if #value < #repr::MIN as usize || #value > #repr::MAX as usize {
panic!("The value corresponding to that expression is outside the bounds of the enum representation");
}
#value as #repr
};
}
}
DiscriminantValue::Path(pathexpr) => {
discriminant_has_paths = true;
quote! {
#[allow(clippy::unnecessary_cast, non_upper_case_globals)]
const #constant_id: #repr = {
let pathexpr_usize = #pathexpr as usize;
if pathexpr_usize < #repr::MIN as usize || pathexpr_usize > #repr::MAX as usize {
panic!("The value corresponding to that expression is outside the bounds of the enum representation");
}
#pathexpr as #repr
};
}
}
}
} else if discriminant_has_paths {
return Err(syn::Error::new(
Span::call_site(),
"The tls_codec discriminant attribute is missing. \
Once you start using paths in #[tls_codec(discriminant = \"path::to::const::or::enum::variant\"], \
You **have** to provide the discriminant attribute on every single variant.",
));
} else {
quote! {
#[allow(non_upper_case_globals)]
const #constant_id: #repr = {
if #implicit_discriminant > #repr::MAX as usize {
panic!("The value corresponding to that expression is outside the bounds of the enum representation");
}
#implicit_discriminant as #repr
};
}
};
implicit_discriminant += 1;
spans.push(tokens);
}
spans
};
Ok(quote! { #(#discriminant_constants)* })
}
#[allow(unused_variables)]
fn impl_tls_size(parsed_ast: TlsStruct) -> TokenStream2 {
match parsed_ast {
TlsStruct::Struct(Struct {
call_site,
ident,
generics,
members,
member_prefixes,
member_skips,
}) => {
let ((members, member_prefixes), _) =
partition_skipped(members, member_prefixes, member_skips);
let prefixes = member_prefixes
.iter()
.map(|p| p.for_trait("Size"))
.collect::<Vec<_>>();
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
quote! {
impl #impl_generics tls_codec::Size for #ident #ty_generics #where_clause {
#[inline]
fn tls_serialized_len(&self) -> usize {
#(#prefixes::tls_serialized_len(&self.#members) + )*
0
}
#[inline]
#[allow(clippy::needless_question_mark)]
fn tls_serialized_len_checked(&self) -> Option<usize> {
Some(0usize#(.checked_add(#prefixes::tls_serialized_len_checked(&self.#members)?)?)*)
}
}
impl #impl_generics tls_codec::Size for &#ident #ty_generics #where_clause {
#[inline]
fn tls_serialized_len(&self) -> usize {
tls_codec::Size::tls_serialized_len(*self)
}
#[inline]
fn tls_serialized_len_checked(&self) -> Option<usize> {
tls_codec::Size::tls_serialized_len_checked(*self)
}
}
}
}
TlsStruct::Enum(Enum {
call_site,
ident,
generics,
repr,
variants,
..
}) => {
let field_arms = variants
.iter()
.map(|variant| {
let variant_id = &variant.ident;
let members = &variant.members;
let bindings = make_n_ids(members.len());
let prefixes = variant.member_prefixes.iter().map(|p| p.for_trait("Size")).collect::<Vec<_>>();
quote! {
#ident::#variant_id { #(#members: #bindings,)* } => 0 #(+ #prefixes::tls_serialized_len(#bindings))*,
}
})
.collect::<Vec<_>>();
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
quote! {
impl #impl_generics tls_codec::Size for #ident #ty_generics #where_clause {
#[inline]
fn tls_serialized_len(&self) -> usize {
let field_len = match self {
#(#field_arms)*
};
core::mem::size_of::<#repr>() + field_len
}
#[inline]
fn tls_serialized_len_checked(&self) -> Option<usize> {
let field_len = match self {
#(#field_arms)*
};
core::mem::size_of::<#repr>().checked_add(field_len)
}
}
impl #impl_generics tls_codec::Size for &#ident #ty_generics #where_clause {
#[inline]
fn tls_serialized_len(&self) -> usize {
tls_codec::Size::tls_serialized_len(*self)
}
#[inline]
fn tls_serialized_len_checked(&self) -> Option<usize> {
tls_codec::Size::tls_serialized_len_checked(*self)
}
}
}
}
}
}
#[allow(unused_variables)]
fn impl_serialize(parsed_ast: TlsStruct, svariant: SerializeVariant) -> TokenStream2 {
match parsed_ast {
TlsStruct::Struct(Struct {
call_site,
ident,
generics,
members,
member_prefixes,
member_skips,
}) => {
let ((members, member_prefixes), _) =
partition_skipped(members, member_prefixes, member_skips);
let prefixes = member_prefixes
.iter()
.map(|p| match svariant {
SerializeVariant::Write => p.for_trait("Serialize"),
SerializeVariant::Bytes => p.for_trait("SerializeBytes"),
})
.collect::<Vec<_>>();
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
match svariant {
SerializeVariant::Write => {
if cfg!(feature = "std") {
quote! {
impl #impl_generics tls_codec::Serialize for #ident #ty_generics #where_clause {
fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> core::result::Result<usize, tls_codec::Error> {
let mut written = 0usize;
#(
written += #prefixes::tls_serialize(&self.#members, writer)?;
)*
if cfg!(debug_assertions) {
let expected_written = tls_codec::Size::tls_serialized_len(&self);
debug_assert_eq!(written, expected_written, "Expected to serialize {} bytes but only {} were generated.", expected_written, written);
if written != expected_written {
Err(tls_codec::Error::EncodingError(format!("Expected to serialize {} bytes but only {} were generated.", expected_written, written)))
} else {
Ok(written)
}
} else {
Ok(written)
}
}
}
impl #impl_generics tls_codec::Serialize for &#ident #ty_generics #where_clause {
fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> core::result::Result<usize, tls_codec::Error> {
tls_codec::Serialize::tls_serialize(*self, writer)
}
}
}
} else {
quote! {
impl #impl_generics tls_codec::Serialize for #ident #ty_generics #where_clause {}
impl #impl_generics tls_codec::Serialize for &#ident #ty_generics #where_clause {}
}
}
}
SerializeVariant::Bytes => {
quote! {
impl #impl_generics tls_codec::SerializeBytes for #ident #ty_generics #where_clause {
fn tls_serialize(&self) -> core::result::Result<Vec<u8>, tls_codec::Error> {
let expected_out = tls_codec::Size::tls_serialized_len(&self);
let mut out = Vec::with_capacity(expected_out);
#(
out.append(&mut #prefixes::tls_serialize(&self.#members)?);
)*
if cfg!(debug_assertions) {
debug_assert_eq!(out.len(), expected_out, "Expected to serialize {} bytes but only {} were generated.", expected_out, out.len());
if out.len() != expected_out {
Err(tls_codec::Error::EncodingError(format!("Expected to serialize {} bytes but only {} were generated.", expected_out, out.len())))
} else {
Ok(out)
}
} else {
Ok(out)
}
}
}
impl #impl_generics tls_codec::SerializeBytes for &#ident #ty_generics #where_clause {
fn tls_serialize(&self) -> core::result::Result<Vec<u8>, tls_codec::Error> {
tls_codec::SerializeBytes::tls_serialize(*self)
}
}
}
}
}
}
TlsStruct::Enum(Enum {
call_site,
ident,
generics,
repr,
variants,
discriminant_constants,
}) => {
let arms: Vec<TokenStream2> = variants
.iter()
.map(|variant| {
let variant_id = &variant.ident;
let discriminant = discriminant_id(variant_id);
let members = &variant.members;
let bindings = make_n_ids(members.len());
match svariant {
SerializeVariant::Write => {
let prefixes = variant
.member_prefixes
.iter()
.map(|p| p.for_trait("Serialize"))
.collect::<Vec<_>>();
quote! {
#ident::#variant_id { #(#members: #bindings,)* } => Ok(
tls_codec::Serialize::tls_serialize(&#discriminant, writer)?
#(+ #prefixes::tls_serialize(#bindings, writer)?)*
),
}
}
SerializeVariant::Bytes => {
let prefixes = variant
.member_prefixes
.iter()
.map(|p| p.for_trait("SerializeBytes"))
.collect::<Vec<_>>();
quote! {
#ident::#variant_id { #(#members: #bindings,)* } => {
let mut discriminant_out = tls_codec::SerializeBytes::tls_serialize(&#discriminant)?;
#(discriminant_out.append(&mut #prefixes::tls_serialize(#bindings)?);)*
Ok(discriminant_out)
},
}