Skip to main content

rustbinary_derive/
lib.rs

1#![forbid(unsafe_code)]
2#![warn(missing_docs)]
3
4//! Procedural derives used by `rustbinary`.
5//!
6//! Applications normally enable the matching `rustbinary` feature and use the
7//! derives re-exported by the main crate. Generated paths intentionally refer
8//! to `::rustbinary`, keeping the runtime traits and wire implementation owned
9//! by one crate.
10//! The procedural macro runs on the host with `std`, but generated code uses
11//! only core syntax and the selected RustBinary runtime traits, so consumers
12//! may expand these derives in `no_std` crates.
13//!
14//! # Macro selection
15//!
16//! - [`Fingerprint`](derive@Fingerprint) generates a compatibility identifier
17//!   for type structure and codec configuration.
18//! - [`StaticSize`](derive@StaticSize) generates finite normal and bit-packed
19//!   size bounds for statically sized values.
20//! - [`Reflect`](derive@Reflect) generates allocation-free structural metadata.
21//! - [`BitPacked`](derive@BitPacked) generates a checked bit-level codec for
22//!   bounded fields and nested `BitPack` values.
23//! - [`CompactBinary`](derive@CompactBinary) generates the schema-guided
24//!   compact profile codec (`CompactEncode` + `CompactDecode`).
25//!
26//! The generated implementations are not a replacement for the nextjson
27//! derives. Add `NsonSerialize` and `NsonDeserialize` when the value also
28//! crosses a normal `rustbinary` or CBOR wire profile. For the complete syntax
29//! and production constraints, see the package README and the re-exported
30//! runtime traits.
31
32use proc_macro::TokenStream;
33use quote::{quote, ToTokens};
34use syn::spanned::Spanned;
35use syn::{
36    parse_macro_input, parse_quote, Data, DataEnum, DataStruct, DeriveInput, Expr, Fields,
37    Generics, Lit, Meta, Type,
38};
39
40#[proc_macro_derive(Fingerprint)]
41/// Derives `rustbinary::Fingerprint` from structural type metadata.
42///
43/// Struct field names/types and enum variant names/order participate in the
44/// identifier. Unions are rejected. Generic type parameters receive the
45/// corresponding `Fingerprint` bound.
46pub fn derive_fingerprint(input: TokenStream) -> TokenStream {
47    let input = parse_macro_input!(input as DeriveInput);
48    fingerprint_impl(&input)
49        .unwrap_or_else(syn::Error::into_compile_error)
50        .into()
51}
52
53#[proc_macro_derive(StaticSize, attributes(bits))]
54/// Derives compile-time normal and bit-packed size bounds.
55///
56/// Fields must implement `rustbinary::StaticSize`. An optional `#[bits = N]`
57/// attribute contributes the explicit packed width. Dynamic collections do not
58/// provide a finite `StaticSize` implementation.
59pub fn derive_static_size(input: TokenStream) -> TokenStream {
60    let input = parse_macro_input!(input as DeriveInput);
61    static_size_impl(&input)
62        .unwrap_or_else(syn::Error::into_compile_error)
63        .into()
64}
65
66#[proc_macro_derive(DecodeBounded)]
67/// Derives `rustbinary::DecodeBounded`, the schema-derived resource cost
68/// algebra `(B, A, D, W)` = (max input bytes, max allocation, max nesting
69/// depth, max work) that mirrors the parser structure.
70///
71/// Fields must implement `rustbinary::DecodeBounded`. Named fields contribute
72/// their object-key bytes, containers contribute a nesting level, and dynamic
73/// collections/strings report `usize::MAX` for content-dependent resources.
74/// Unions are rejected.
75pub fn derive_decode_bounded(input: TokenStream) -> TokenStream {
76    let input = parse_macro_input!(input as DeriveInput);
77    decode_bounded_impl(&input)
78        .unwrap_or_else(syn::Error::into_compile_error)
79        .into()
80}
81
82#[proc_macro_derive(Reflect, attributes(bits, entropy))]
83/// Derives allocation-free structural reflection metadata.
84///
85/// Generated metadata contains the declared type name, fields, field type
86/// tokens, declaration indexes, and enum variants. No registry or runtime
87/// initialization is generated.
88///
89/// Field alphabet sizes feed the static-model entropy coder. The derive
90/// records `symbols` from an explicit `#[entropy(symbols = N)]` (1..=32768),
91/// from a `#[bits = N]` range, or from primitive alphabets (`bool` → 2,
92/// `u8`/`i8` → 256); otherwise the field reports `0` and is coded
93/// byte-by-byte.
94pub fn derive_reflect(input: TokenStream) -> TokenStream {
95    let input = parse_macro_input!(input as DeriveInput);
96    reflect_impl(&input)
97        .unwrap_or_else(syn::Error::into_compile_error)
98        .into()
99}
100
101#[proc_macro_derive(BitPacked, attributes(bits))]
102/// Derives `rustbinary::BitPack` for structs and enums.
103///
104/// Fields with `#[bits = N]` use `BitValue` range validation. Other fields
105/// recursively use `BitPack`. Enum tags use the minimum bit width and unknown
106/// decoded tags are rejected.
107pub fn derive_bit_packed(input: TokenStream) -> TokenStream {
108    let input = parse_macro_input!(input as DeriveInput);
109    bit_packed_impl(&input)
110        .unwrap_or_else(syn::Error::into_compile_error)
111        .into()
112}
113
114#[proc_macro_derive(Archive, attributes(archive))]
115/// Derives the zero-copy archived mirror used by
116/// `rustbinary::archive::build` / `OwnedArchive` / `MappedArchive`.
117///
118/// For a named struct, `Archive` generates:
119///
120/// - the `Archived{Name}` mirror (`#[repr(C)]`, derived `Clone` + `Copy`)
121///   whose fields are the archived forms of the source fields,
122/// - the `rustbinary::archive_codec::Archive` impl,
123/// - the `rustbinary::archive_codec::ArchivedValue` marker,
124/// - the `rustbinary::archive_codec::CheckBytes` structural validator that
125///   bounds-checks every relative offset, length, and range in one pass.
126///
127/// Supported field types: scalar primitives (`u8`…`f64`, no `bool`),
128/// `String`, `Vec<T>` of a scalar or of a nested archived struct, and a
129/// nested archived struct field. `bool` is rejected: it has no
130/// `ArchivedValue` (not every byte pattern is a valid `bool`) and would make
131/// zero-copy element slices unsound. Generic type parameters, enums, unions,
132/// `Vec<String>`, and nested `Vec<Vec<…>>` are rejected with a compile
133/// error rather than generating subtly wrong code.
134pub fn derive_archive(input: TokenStream) -> TokenStream {
135    let input = parse_macro_input!(input as DeriveInput);
136    archive_impl(&input)
137        .unwrap_or_else(syn::Error::into_compile_error)
138        .into()
139}
140
141#[proc_macro_derive(Serialize)]
142/// Derives `rustbinary::archive_codec::ArchiveWrite`, the two-phase archive
143/// serializer (skeleton pass then bodies pass).
144///
145/// Apply together with `#[derive(Archive)]` on the same named struct. The
146/// supported field types and rejections match the `Archive` derive.
147pub fn derive_serialize(input: TokenStream) -> TokenStream {
148    let input = parse_macro_input!(input as DeriveInput);
149    serialize_impl(&input)
150        .unwrap_or_else(syn::Error::into_compile_error)
151        .into()
152}
153
154/// `Archive` and `Serialize` shared field-type guards.
155fn reject_unsupported_archive_fields(fields: &Fields, what: &str) -> syn::Result<()> {
156    for field in fields {
157        let ty = &field.ty;
158        if is_bool(ty) {
159            return Err(syn::Error::new_spanned(
160                ty,
161                format!("{what} does not support `bool` fields (no ArchivedValue; use `u8` with 0/1 or a manual archive implementation)"),
162            ));
163        }
164        if let Some(inner) = vec_element(ty) {
165            if is_bool(inner) {
166                return Err(syn::Error::new_spanned(
167                    ty,
168                    format!(
169                        "{what} does not support `Vec<bool>` fields (bool has no ArchivedValue)"
170                    ),
171                ));
172            }
173            if is_string(inner) {
174                return Err(syn::Error::new_spanned(
175                    ty,
176                    format!("{what} does not support `Vec<String>` fields yet"),
177                ));
178            }
179        }
180        if is_string(ty) || is_bool(ty) {
181            continue;
182        }
183        if vec_element(ty).is_some() {
184            continue;
185        }
186        if is_scalar(ty) {
187            continue;
188        }
189    }
190    Ok(())
191}
192
193/// Whether the type names the `bool` primitive.
194fn is_bool(ty: &syn::Type) -> bool {
195    match ty {
196        syn::Type::Path(type_path) if type_path.qself.is_none() => type_path
197            .path
198            .segments
199            .last()
200            .map(|segment| segment.ident == "bool")
201            .unwrap_or(false),
202        _ => false,
203    }
204}
205
206/// Whether the type is a scalar primitive supported by the archive codec.
207fn is_scalar(ty: &syn::Type) -> bool {
208    scalar_write_method(ty).is_some()
209}
210
211/// The serializer write method for a scalar primitive, if supported.
212fn scalar_write_method(ty: &syn::Type) -> Option<&'static str> {
213    let path = match ty {
214        syn::Type::Path(type_path) if type_path.qself.is_none() => &type_path.path,
215        _ => return None,
216    };
217    let ident = path.segments.last()?.ident.to_string();
218    match ident.as_str() {
219        "u8" => Some("write_u8"),
220        "u16" => Some("write_u16"),
221        "u32" => Some("write_u32"),
222        "u64" => Some("write_u64"),
223        "i8" => Some("write_i8"),
224        "i16" => Some("write_i16"),
225        "i32" => Some("write_i32"),
226        "i64" => Some("write_i64"),
227        "f32" => Some("write_f32"),
228        "f64" => Some("write_f64"),
229        _ => None,
230    }
231}
232
233/// Whether the type is `String` under any leading path.
234fn is_string(ty: &syn::Type) -> bool {
235    match ty {
236        syn::Type::Path(type_path) if type_path.qself.is_none() => type_path
237            .path
238            .segments
239            .last()
240            .map(|segment| segment.ident == "String")
241            .unwrap_or(false),
242        _ => false,
243    }
244}
245
246/// If the type is `Vec<T>`, returns the element type.
247fn vec_element(ty: &syn::Type) -> Option<&syn::Type> {
248    let path = match ty {
249        syn::Type::Path(type_path) if type_path.qself.is_none() => &type_path.path,
250        _ => return None,
251    };
252    if path.segments.len() != 1 || path.segments[0].ident != "Vec" {
253        return None;
254    }
255    match &path.segments[0].arguments {
256        syn::PathArguments::AngleBracketed(args) if args.args.len() == 1 => match &args.args[0] {
257            syn::GenericArgument::Type(inner) => Some(inner),
258            _ => None,
259        },
260        _ => None,
261    }
262}
263
264/// The archived mirror field type for a source field type.
265fn archived_field_type(ty: &syn::Type) -> syn::Result<proc_macro2::TokenStream> {
266    if is_scalar(ty) {
267        Ok(quote!(#ty))
268    } else if is_string(ty) {
269        Ok(quote!(::rustbinary::archive_codec::ArchivedString))
270    } else if let Some(inner) = vec_element(ty) {
271        if is_scalar(inner) {
272            Ok(quote!(::rustbinary::archive_codec::ArchivedVec<#inner>))
273        } else {
274            let archived_inner = quote!(<#inner as ::rustbinary::archive_codec::Archive>::Archived);
275            Ok(quote!(::rustbinary::archive_codec::ArchivedVec<#archived_inner>))
276        }
277    } else {
278        Ok(quote!(<#ty as ::rustbinary::archive_codec::Archive>::Archived))
279    }
280}
281
282/// Alignment of the archived mirror field for a source field type. This is
283/// the alignment the `#[repr(C)]` mirror assigns to the field, which the
284/// serializer and validator replicate with `align_to` / `align_up`.
285fn archived_field_align(ty: &syn::Type) -> proc_macro2::TokenStream {
286    if is_scalar(ty) {
287        quote!(::core::mem::align_of::<#ty>())
288    } else if is_string(ty) {
289        quote!(::core::mem::align_of::<
290            ::rustbinary::archive_codec::ArchivedString,
291        >())
292    } else if let Some(inner) = vec_element(ty) {
293        let archived_inner = if is_scalar(inner) {
294            quote!(#inner)
295        } else {
296            quote!(<#inner as ::rustbinary::archive_codec::Archive>::Archived)
297        };
298        quote!(
299            ::core::mem::align_of::<::rustbinary::archive_codec::ArchivedVec<#archived_inner>>()
300        )
301    } else {
302        let archived_ty = quote!(<#ty as ::rustbinary::archive_codec::Archive>::Archived);
303        quote!(::core::mem::align_of::<#archived_ty>())
304    }
305}
306
307/// Size of the archived mirror field for a source field type.
308fn archived_field_size(ty: &syn::Type) -> proc_macro2::TokenStream {
309    if is_scalar(ty) {
310        quote!(::core::mem::size_of::<#ty>())
311    } else if is_string(ty) {
312        quote!(::core::mem::size_of::<
313            ::rustbinary::archive_codec::ArchivedString,
314        >())
315    } else if let Some(inner) = vec_element(ty) {
316        let archived_inner = if is_scalar(inner) {
317            quote!(#inner)
318        } else {
319            quote!(<#inner as ::rustbinary::archive_codec::Archive>::Archived)
320        };
321        quote!(
322            ::core::mem::size_of::<::rustbinary::archive_codec::ArchivedVec<#archived_inner>>()
323        )
324    } else {
325        let archived_ty = quote!(<#ty as ::rustbinary::archive_codec::Archive>::Archived);
326        quote!(::core::mem::size_of::<#archived_ty>())
327    }
328}
329
330fn archive_impl(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
331    let name = &input.ident;
332    let archived_name = syn::Ident::new(&format!("Archived{name}"), name.span());
333
334    if !input.generics.params.is_empty() {
335        return Err(syn::Error::new_spanned(
336            &input.generics,
337            "the Archive derive does not support generic type parameters",
338        ));
339    }
340    let fields = match &input.data {
341        Data::Struct(data) => &data.fields,
342        _ => {
343            return Err(syn::Error::new_spanned(
344                input,
345                "the Archive derive only supports structs (enums and unions are rejected)",
346            ))
347        }
348    };
349    reject_unsupported_archive_fields(fields, "the Archive derive")?;
350
351    let archived_fields: Vec<proc_macro2::TokenStream> = fields
352        .iter()
353        .map(|field| {
354            let ident = field.ident.as_ref().expect("named archive field");
355            let ty = &field.ty;
356            let archived = archived_field_type(ty)?;
357            Ok(quote!(#ident: #archived))
358        })
359        .collect::<syn::Result<_>>()?;
360    let check_body = archive_check_body(fields)?;
361
362    Ok(quote! {
363        #[doc = "Archived mirror of `"]
364        #[doc = stringify!(#name)]
365        #[doc = "`, generated by the `Archive` derive."]
366        #[derive(Clone, Copy)]
367        #[repr(C)]
368        pub struct #archived_name {
369            #(#archived_fields,)*
370        }
371
372        impl ::rustbinary::archive_codec::Archive for #name {
373            type Archived = #archived_name;
374        }
375
376        unsafe impl ::rustbinary::archive_codec::ArchivedValue for #archived_name {}
377
378        impl ::rustbinary::archive_codec::CheckBytes for #archived_name {
379            fn check_at(
380                bytes: &[u8],
381                base: usize,
382            ) -> ::core::result::Result<(), ::std::string::String> {
383                #check_body
384            }
385        }
386    })
387}
388
389/// Structural validator body for the archived mirror of `fields`.
390///
391/// The archived mirror is `#[repr(C)]`, so every field sits at the C-ABI
392/// offset: the size of the previous fields rounded up to the field's
393/// alignment. The generated code reproduces that exact algorithm with
394/// `align_up(offset, align)` and advances by `size_of`, then validates
395/// variable-width fields. Because both sides run the same algorithm, the
396/// validator always walks the same offsets the mirror uses for access.
397fn archive_check_body(fields: &Fields) -> syn::Result<proc_macro2::TokenStream> {
398    let mut statements = Vec::new();
399    for field in fields {
400        let ty = &field.ty;
401        let align = archived_field_align(ty);
402        let size = archived_field_size(ty);
403        if is_scalar(ty) {
404            statements.push(quote! {
405                offset = (offset + ((#align) - (offset % (#align))) % (#align));
406                offset += #size;
407            });
408        } else if is_string(ty) {
409            statements.push(quote! {
410                offset = (offset + ((#align) - (offset % (#align))) % (#align));
411                ::rustbinary::archive_codec::check_string_field(bytes, offset)?;
412                offset += #size;
413            });
414        } else if let Some(inner) = vec_element(ty) {
415            if is_scalar(inner) {
416                statements.push(quote! {
417                    offset = (offset + ((#align) - (offset % (#align))) % (#align));
418                    ::rustbinary::archive_codec::check_vec_field(
419                        bytes,
420                        offset,
421                        ::core::mem::size_of::<#inner>(),
422                        ::core::mem::align_of::<#inner>(),
423                    )?;
424                    offset += #size;
425                });
426            } else {
427                let archived_inner =
428                    quote!(<#inner as ::rustbinary::archive_codec::Archive>::Archived);
429                statements.push(quote! {
430                    offset = (offset + ((#align) - (offset % (#align))) % (#align));
431                    ::rustbinary::archive_codec::check_vec_nested::<#archived_inner>(
432                        bytes,
433                        offset,
434                        ::core::mem::size_of::<#archived_inner>(),
435                        ::core::mem::align_of::<#archived_inner>(),
436                    )?;
437                    offset += #size;
438                });
439            }
440        } else {
441            let archived_ty = quote!(<#ty as ::rustbinary::archive_codec::Archive>::Archived);
442            statements.push(quote! {
443                offset = (offset + ((#align) - (offset % (#align))) % (#align));
444                <#archived_ty as ::rustbinary::archive_codec::CheckBytes>::check_at(
445                    bytes,
446                    offset,
447                )?;
448                offset += #size;
449            });
450        }
451    }
452    Ok(quote! {
453        let mut offset = base;
454        #(#statements)*
455        Ok(())
456    })
457}
458
459fn serialize_impl(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
460    let name = &input.ident;
461
462    if !input.generics.params.is_empty() {
463        return Err(syn::Error::new_spanned(
464            &input.generics,
465            "the Serialize derive does not support generic type parameters",
466        ));
467    }
468    let fields = match &input.data {
469        Data::Struct(data) => &data.fields,
470        _ => {
471            return Err(syn::Error::new_spanned(
472                input,
473                "the Serialize derive only supports structs (enums and unions are rejected)",
474            ))
475        }
476    };
477    reject_unsupported_archive_fields(fields, "the Serialize derive")?;
478
479    let skeleton = serialize_skeleton_body(fields)?;
480    let bodies = serialize_bodies_body(fields)?;
481
482    Ok(quote! {
483        impl ::rustbinary::archive_codec::ArchiveWrite for #name {
484            fn write_skeleton(
485                &self,
486                serializer: &mut ::rustbinary::archive_codec::ArchiveSerializer,
487                positions: &mut ::std::collections::VecDeque<usize>,
488            ) {
489                #skeleton
490            }
491
492            fn write_bodies(
493                &self,
494                serializer: &mut ::rustbinary::archive_codec::ArchiveSerializer,
495                positions: &mut ::std::collections::VecDeque<usize>,
496            ) -> ::core::result::Result<(), ::std::string::String> {
497                #bodies
498                Ok(())
499            }
500        }
501    })
502}
503
504/// Skeleton phase: write inline scalars (C-aligned), reserve a `RelPtr`
505/// placeholder for every variable-width field, and recurse into direct nested
506/// structs. Every field is preceded by `align_to` so the buffer matches the
507/// `#[repr(C)]` mirror byte for byte.
508fn serialize_skeleton_body(fields: &Fields) -> syn::Result<proc_macro2::TokenStream> {
509    let mut statements = Vec::new();
510    for field in fields {
511        let member = field.ident.as_ref().expect("named archive field");
512        let ty = &field.ty;
513        let align = archived_field_align(ty);
514        if let Some(method) = scalar_write_method(ty) {
515            let method = syn::Ident::new(method, ty.span());
516            statements.push(quote! {
517                serializer.align_to(#align);
518                serializer.#method(self.#member);
519            });
520        } else if is_string(ty) || vec_element(ty).is_some() {
521            statements.push(quote! {
522                serializer.align_to(#align);
523                positions.push_back(serializer.reserve_ptr());
524            });
525        } else {
526            statements.push(quote! {
527                serializer.align_to(#align);
528                ::rustbinary::archive_codec::ArchiveWrite::write_skeleton(
529                    &self.#member,
530                    serializer,
531                    positions,
532                );
533            });
534        }
535    }
536    Ok(quote!(#(#statements)*))
537}
538
539/// Bodies phase: write string/vec data and patch placeholders, or recurse
540/// into direct nested structs. `Vec<T>` of a scalar uses the Pod fast path;
541/// `Vec<T>` of a nested struct writes all element skeletons contiguously
542/// first (so the element array is a run of fixed-size mirrors) and then all
543/// element bodies.
544fn serialize_bodies_body(fields: &Fields) -> syn::Result<proc_macro2::TokenStream> {
545    let mut statements = Vec::new();
546    for field in fields {
547        let member = field.ident.as_ref().expect("named archive field");
548        let ty = &field.ty;
549        if is_scalar(ty) {
550            // Inline scalar: nothing to do in the bodies phase.
551        } else if is_string(ty) {
552            statements.push(quote! {
553                {
554                    let field_pos = positions
555                        .pop_front()
556                        .ok_or("archive: missing string body position")?;
557                    serializer.write_string_at(field_pos, &self.#member);
558                }
559            });
560        } else if let Some(inner) = vec_element(ty) {
561            if is_scalar(inner) {
562                statements.push(quote! {
563                    {
564                        let field_pos = positions
565                            .pop_front()
566                            .ok_or("archive: missing vec body position")?;
567                        serializer.write_vec_at(field_pos, &self.#member);
568                    }
569                });
570            } else {
571                let archived_inner =
572                    quote!(<#inner as ::rustbinary::archive_codec::Archive>::Archived);
573                statements.push(quote! {
574                    {
575                        let field_pos = positions
576                            .pop_front()
577                            .ok_or("archive: missing vec body position")?;
578                        let data_pos = serializer.len();
579                        serializer.write_u32(
580                            ::core::convert::TryInto::try_into(self.#member.len())
581                                .unwrap_or(::core::u32::MAX),
582                        );
583                        serializer.align_to(::core::mem::align_of::<#archived_inner>());
584                        for element in &self.#member {
585                            ::rustbinary::archive_codec::ArchiveWrite::write_skeleton(
586                                element,
587                                serializer,
588                                positions,
589                            );
590                        }
591                        for element in &self.#member {
592                            ::rustbinary::archive_codec::ArchiveWrite::write_bodies(
593                                element,
594                                serializer,
595                                positions,
596                            )?;
597                        }
598                        serializer.patch_ptr(field_pos, data_pos);
599                    }
600                });
601            }
602        } else {
603            statements.push(quote! {
604                ::rustbinary::archive_codec::ArchiveWrite::write_bodies(
605                    &self.#member,
606                    serializer,
607                    positions,
608                )?;
609            });
610        }
611    }
612    Ok(quote!(#(#statements)*))
613}
614
615#[proc_macro_derive(CompactBinary, attributes(njson))]
616/// Derives `rustbinary::compact::CompactEncode` and
617/// `rustbinary::compact::CompactDecode` — the schema-guided compact binary
618/// profile.
619///
620/// Struct fields encode in declaration order with **no field names**; enums
621/// write only a compact variant discriminant; containers are length-prefixed.
622/// The generated codec bypasses the generic nextjson event path entirely, so
623/// the hot loop carries no type tags, no field-name handling and no dynamic
624/// dispatch. `#[njson(borrow)]` is accepted for nextjson compatibility and is
625/// otherwise ignored: borrowing follows the field type, so `&'a str` and
626/// `&'a [u8]` fields decode as zero-copy references into the input when
627/// `'de: 'a` holds. Unions are rejected.
628pub fn derive_compact_binary(input: TokenStream) -> TokenStream {
629    let input = parse_macro_input!(input as DeriveInput);
630    compact_binary_impl(&input)
631        .unwrap_or_else(syn::Error::into_compile_error)
632        .into()
633}
634
635fn compact_binary_impl(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
636    let encode = compact_encode_impl(input)?;
637    let decode = compact_decode_impl(input)?;
638    Ok(quote!(#encode #decode))
639}
640
641fn compact_encode_impl(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
642    let name = &input.ident;
643    let generics = add_bound(
644        input.generics.clone(),
645        parse_quote!(::rustbinary::compact::CompactEncode),
646    );
647    let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
648    let body = match &input.data {
649        Data::Struct(data) => compact_encode_struct(data),
650        Data::Enum(data) => compact_encode_enum(data),
651        Data::Union(_) => {
652            return Err(syn::Error::new_spanned(
653                input,
654                "CompactBinary cannot be derived for unions",
655            ))
656        }
657    }?;
658    Ok(quote! {
659        impl #impl_generics ::rustbinary::compact::CompactEncode for #name #type_generics #where_clause {
660            fn encode_compact<W: ::rustbinary::writer::EncodeWriter + ?Sized>(
661                &self,
662                writer: &mut W,
663            ) -> ::rustbinary::Result<()> {
664                #body
665                Ok(())
666            }
667        }
668    })
669}
670
671fn compact_encode_struct(data: &DataStruct) -> syn::Result<proc_macro2::TokenStream> {
672    let statements = data.fields.iter().enumerate().map(|(index, field)| {
673        let member = field
674            .ident
675            .clone()
676            .map(syn::Member::Named)
677            .unwrap_or_else(|| syn::Member::Unnamed(syn::Index::from(index)));
678        let ty = &field.ty;
679        quote! {
680            <#ty as ::rustbinary::compact::CompactEncode>::encode_compact(&self.#member, writer)?;
681        }
682    });
683    Ok(quote!(#(#statements)*))
684}
685
686fn compact_encode_enum(data: &DataEnum) -> syn::Result<proc_macro2::TokenStream> {
687    let mut arms = Vec::new();
688    for (index, variant) in data.variants.iter().enumerate() {
689        let variant_name = &variant.ident;
690        let discriminant = proc_macro2::Literal::u32_suffixed(index as u32);
691        let pattern = match &variant.fields {
692            Fields::Named(fields) => {
693                let names = fields
694                    .named
695                    .iter()
696                    .map(|field| field.ident.as_ref().expect("named"));
697                quote!(Self::#variant_name { #(#names),* })
698            }
699            Fields::Unnamed(_) => {
700                let bindings = (0..variant.fields.len())
701                    .map(|i| syn::Ident::new(&format!("field_{i}"), variant.ident.span()))
702                    .collect::<Vec<_>>();
703                quote!(Self::#variant_name(#(#bindings),*))
704            }
705            Fields::Unit => quote!(Self::#variant_name),
706        };
707        let payload = compact_variant_encode(&variant.fields)?;
708        arms.push(quote! {
709            #pattern => {
710                ::rustbinary::compact::encode_variant_index(writer, #discriminant)?;
711                #payload
712            }
713        });
714    }
715    Ok(quote!(match self { #(#arms),* }))
716}
717
718fn compact_variant_encode(fields: &Fields) -> syn::Result<proc_macro2::TokenStream> {
719    let statements = fields.iter().enumerate().map(|(index, field)| {
720        let binding: syn::Ident = match fields {
721            Fields::Named(_) => field.ident.clone().expect("named"),
722            _ => syn::Ident::new(&format!("field_{index}"), field.ty.span()),
723        };
724        let ty = &field.ty;
725        quote! {
726            <#ty as ::rustbinary::compact::CompactEncode>::encode_compact(#binding, writer)?;
727        }
728    });
729    Ok(quote!(#(#statements)*))
730}
731
732fn compact_decode_impl(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
733    let name = &input.ident;
734    let mut impl_generics = input.generics.clone();
735    impl_generics.params.insert(0, parse_quote!('de));
736    for parameter in impl_generics.type_params_mut() {
737        parameter
738            .bounds
739            .push(parse_quote!(::rustbinary::compact::CompactDecode<'de>));
740    }
741    let original_lifetimes: Vec<syn::Lifetime> = input
742        .generics
743        .lifetimes()
744        .map(|param| param.lifetime.clone())
745        .collect();
746    if !original_lifetimes.is_empty() {
747        let where_clause = impl_generics.make_where_clause();
748        for lifetime in &original_lifetimes {
749            where_clause.predicates.push(parse_quote!('de: #lifetime));
750        }
751    }
752
753    // Type generics come from the *original* generics: the type itself has no
754    // `'de` parameter.
755    let (_, type_generics, _) = input.generics.split_for_impl();
756    let (impl_generics, _, where_clause) = impl_generics.split_for_impl();
757
758    let body = match &input.data {
759        Data::Struct(data) => compact_decode_struct(name, data)?,
760        Data::Enum(data) => compact_decode_enum(data)?,
761        Data::Union(_) => unreachable!(),
762    };
763    Ok(quote! {
764        impl #impl_generics ::rustbinary::compact::CompactDecode<'de> for #name #type_generics #where_clause {
765            fn decode_compact(
766                cursor: &mut ::rustbinary::compact::CompactCursor<'de>,
767            ) -> ::rustbinary::Result<Self> {
768                #body
769            }
770        }
771    })
772}
773
774fn compact_decode_struct(
775    name: &syn::Ident,
776    data: &DataStruct,
777) -> syn::Result<proc_macro2::TokenStream> {
778    match &data.fields {
779        Fields::Unit => Ok(quote!(Ok(#name))),
780        Fields::Named(fields) => {
781            let decodes = fields.named.iter().map(|field| {
782                let ident = field.ident.as_ref().expect("named");
783                let ty = &field.ty;
784                quote! {
785                    let #ident = <#ty as ::rustbinary::compact::CompactDecode<'de>>::decode_compact(cursor)?;
786                }
787            });
788            let names = fields
789                .named
790                .iter()
791                .map(|field| field.ident.as_ref().expect("named"));
792            Ok(quote! {
793                #(#decodes)*
794                Ok(#name { #(#names),* })
795            })
796        }
797        Fields::Unnamed(fields) => {
798            let names = (0..fields.unnamed.len())
799                .map(|i| syn::Ident::new(&format!("field_{i}"), name.span()))
800                .collect::<Vec<_>>();
801            let decodes = fields.unnamed.iter().zip(&names).map(|(field, ident)| {
802                let ty = &field.ty;
803                quote! {
804                    let #ident = <#ty as ::rustbinary::compact::CompactDecode<'de>>::decode_compact(cursor)?;
805                }
806            });
807            Ok(quote! {
808                #(#decodes)*
809                Ok(#name(#(#names),*))
810            })
811        }
812    }
813}
814
815fn compact_decode_enum(data: &DataEnum) -> syn::Result<proc_macro2::TokenStream> {
816    let arms = data
817        .variants
818        .iter()
819        .enumerate()
820        .map(|(index, variant)| {
821            let variant_name = &variant.ident;
822            let discriminant = proc_macro2::Literal::u32_suffixed(index as u32);
823            match &variant.fields {
824                Fields::Unit => quote!(#discriminant => Ok(Self::#variant_name)),
825                Fields::Unnamed(fields) => {
826                    let names = (0..fields.unnamed.len())
827                        .map(|i| syn::Ident::new(&format!("field_{i}"), variant.ident.span()))
828                        .collect::<Vec<_>>();
829                    let decodes = fields.unnamed.iter().zip(&names).map(|(field, ident)| {
830                        let ty = &field.ty;
831                        quote! {
832                            let #ident = <#ty as ::rustbinary::compact::CompactDecode<'de>>::decode_compact(cursor)?;
833                        }
834                    });
835                    quote! {
836                        #discriminant => {
837                            #(#decodes)*
838                            Ok(Self::#variant_name(#(#names),*))
839                        }
840                    }
841                }
842                Fields::Named(fields) => {
843                    let names = fields
844                        .named
845                        .iter()
846                        .map(|field| field.ident.as_ref().expect("named"))
847                        .collect::<Vec<_>>();
848                    let decodes = fields.named.iter().map(|field| {
849                        let ident = field.ident.as_ref().expect("named");
850                        let ty = &field.ty;
851                        quote! {
852                            let #ident = <#ty as ::rustbinary::compact::CompactDecode<'de>>::decode_compact(cursor)?;
853                        }
854                    });
855                    quote! {
856                        #discriminant => {
857                            #(#decodes)*
858                            Ok(Self::#variant_name { #(#names),* })
859                        }
860                    }
861                }
862            }
863        });
864    Ok(quote! {
865        match ::rustbinary::compact::decode_variant_index(cursor)? {
866            #(#arms,)*
867            _ => Err(::rustbinary::compact::__err_static("unknown compact enum variant")),
868        }
869    })
870}
871
872fn add_bound(mut generics: Generics, bound: syn::Path) -> Generics {
873    for parameter in generics.type_params_mut() {
874        parameter.bounds.push(parse_quote!(#bound));
875    }
876    generics
877}
878
879fn field_name(index: usize, field: &syn::Field) -> String {
880    field
881        .ident
882        .as_ref()
883        .map_or_else(|| index.to_string(), ToString::to_string)
884}
885
886fn hash_field(index: usize, field: &syn::Field) -> proc_macro2::TokenStream {
887    let name = field_name(index, field);
888    let ty = &field.ty;
889    quote! {
890        hash = ::rustbinary::schema::hash_bytes(hash, #name.as_bytes());
891        hash = ::rustbinary::schema::hash_u64(hash, <#ty as ::rustbinary::Fingerprint>::TYPE_FINGERPRINT);
892    }
893}
894
895fn fingerprint_impl(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
896    let name = &input.ident;
897    let generics = add_bound(
898        input.generics.clone(),
899        parse_quote!(::rustbinary::Fingerprint),
900    );
901    let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
902    let body = match &input.data {
903        Data::Struct(data) => {
904            let fields = data
905                .fields
906                .iter()
907                .enumerate()
908                .map(|(index, field)| hash_field(index, field));
909            quote! {
910                let mut hash = ::rustbinary::schema::hash_bytes(
911                    ::rustbinary::schema::FNV_OFFSET,
912                    concat!(module_path!(), "::", stringify!(#name), "|struct").as_bytes(),
913                );
914                #(#fields)*
915                hash
916            }
917        }
918        Data::Enum(data) => fingerprint_enum(name, data),
919        Data::Union(_) => {
920            return Err(syn::Error::new_spanned(
921                input,
922                "Fingerprint cannot be derived for unions",
923            ))
924        }
925    };
926    Ok(quote! {
927        impl #impl_generics ::rustbinary::Fingerprint for #name #type_generics #where_clause {
928            const TYPE_FINGERPRINT: u64 = { #body };
929        }
930    })
931}
932
933fn fingerprint_enum(name: &syn::Ident, data: &DataEnum) -> proc_macro2::TokenStream {
934    let variants = data
935        .variants
936        .iter()
937        .enumerate()
938        .map(|(variant_index, variant)| {
939            let variant_name = variant.ident.to_string();
940            let index = variant_index as u64;
941            let fields = variant
942                .fields
943                .iter()
944                .enumerate()
945                .map(|(field_index, field)| hash_field(field_index, field));
946            quote! {
947                hash = ::rustbinary::schema::hash_u64(hash, #index);
948                hash = ::rustbinary::schema::hash_bytes(hash, #variant_name.as_bytes());
949                #(#fields)*
950            }
951        });
952    quote! {
953        let mut hash = ::rustbinary::schema::hash_bytes(
954            ::rustbinary::schema::FNV_OFFSET,
955            concat!(module_path!(), "::", stringify!(#name), "|enum").as_bytes(),
956        );
957        #(#variants)*
958        hash
959    }
960}
961
962fn static_field_size(field: &syn::Field, packed: bool) -> proc_macro2::TokenStream {
963    let ty = &field.ty;
964    if packed {
965        quote!(<#ty as ::rustbinary::StaticSize>::PACKED_MAX_SIZE)
966    } else {
967        quote!(<#ty as ::rustbinary::StaticSize>::MAX_SIZE)
968    }
969}
970
971fn static_field_bits(field: &syn::Field) -> syn::Result<proc_macro2::TokenStream> {
972    let ty = &field.ty;
973    Ok(match declared_bits(field)? {
974        Some(width) => quote!(#width),
975        None => quote!(<#ty as ::rustbinary::StaticSize>::PACKED_MAX_BITS),
976    })
977}
978
979fn sum_field_bits(fields: &Fields) -> syn::Result<proc_macro2::TokenStream> {
980    let mut sum = quote!(0usize);
981    for field in fields {
982        let bits = static_field_bits(field)?;
983        sum = quote!(::rustbinary::static_size::saturating_add(#sum, #bits));
984    }
985    Ok(sum)
986}
987
988/// Worst-case serialized bytes of one named object key. Length prefixes are
989/// fixed-u64 in the fixed-width profile (9 + len) and marker-varint elsewhere
990/// (2 + len), so the worst case is the fixed-width form.
991fn key_size(name: &str) -> proc_macro2::TokenStream {
992    let len = name.len();
993    quote!(9usize + #len)
994}
995
996/// Sum of field sizes; named fields additionally contribute their key bytes.
997fn sum_fields(fields: &Fields, packed: bool) -> proc_macro2::TokenStream {
998    fields
999        .iter()
1000        .enumerate()
1001        .fold(quote!(0usize), |sum, (index, field)| {
1002            let size = static_field_size(field, packed);
1003            if field.ident.is_some() {
1004                let key = key_size(&field_name(index, field));
1005                quote!(::rustbinary::static_size::saturating_add(
1006                    #sum,
1007                    ::rustbinary::static_size::saturating_add(#size, #key),
1008                ))
1009            } else {
1010                quote!(::rustbinary::static_size::saturating_add(#sum, #size))
1011            }
1012        })
1013}
1014
1015/// Container overhead (tag + terminator, or a single null for unit shapes).
1016fn shape_overhead(fields: &Fields) -> proc_macro2::TokenStream {
1017    match fields {
1018        Fields::Unit => quote!(1usize),
1019        Fields::Unnamed(_) | Fields::Named(_) => quote!(2usize),
1020    }
1021}
1022
1023/// Worst-case serialized content of one enum variant (excluding the variant
1024/// key, which is added by [`max_variants`]).
1025fn variant_content_size(fields: &Fields, packed: bool) -> proc_macro2::TokenStream {
1026    match fields {
1027        // A newtype variant writes its payload directly.
1028        Fields::Unnamed(f) if f.unnamed.len() == 1 => static_field_size(&f.unnamed[0], packed),
1029        other => {
1030            let payload = sum_fields(fields, packed);
1031            let overhead = shape_overhead(other);
1032            quote!(::rustbinary::static_size::saturating_add(#payload, #overhead))
1033        }
1034    }
1035}
1036
1037fn max_variants(data: &DataEnum, packed: bool) -> proc_macro2::TokenStream {
1038    data.variants
1039        .iter()
1040        .fold(quote!(0usize), |maximum, variant| {
1041            let key = key_size(&variant.ident.to_string());
1042            let content = variant_content_size(&variant.fields, packed);
1043            let size = quote!(::rustbinary::static_size::saturating_add(#key, #content));
1044            quote!(::rustbinary::static_size::max(#maximum, #size))
1045        })
1046}
1047
1048fn static_size_impl(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
1049    let name = &input.ident;
1050    let generics = add_bound(
1051        input.generics.clone(),
1052        parse_quote!(::rustbinary::StaticSize),
1053    );
1054    let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
1055    let (maximum, packed_bits) = match &input.data {
1056        Data::Struct(data) => {
1057            let payload = sum_fields(&data.fields, false);
1058            let overhead = shape_overhead(&data.fields);
1059            (
1060                quote!(::rustbinary::static_size::saturating_add(#payload, #overhead)),
1061                sum_field_bits(&data.fields)?,
1062            )
1063        }
1064        Data::Enum(data) => {
1065            // External nextjson enums encode as an object with one variant key.
1066            let variants = max_variants(data, false);
1067            let maximum = quote!(::rustbinary::static_size::saturating_add(
1068                ::rustbinary::static_size::saturating_add(1usize, #variants),
1069                1usize,
1070            ));
1071            let tag_bits = if data.variants.len() <= 1 {
1072                0usize
1073            } else {
1074                (usize::BITS - (data.variants.len() - 1).leading_zeros()) as usize
1075            };
1076            let mut packed_payload = quote!(0usize);
1077            for variant in &data.variants {
1078                let bits = sum_field_bits(&variant.fields)?;
1079                packed_payload = quote!(::rustbinary::static_size::max(#packed_payload, #bits));
1080            }
1081            (
1082                maximum,
1083                quote!(::rustbinary::static_size::saturating_add(#tag_bits, #packed_payload)),
1084            )
1085        }
1086        Data::Union(_) => {
1087            return Err(syn::Error::new_spanned(
1088                input,
1089                "StaticSize cannot be derived for unions",
1090            ))
1091        }
1092    };
1093    Ok(quote! {
1094        impl #impl_generics ::rustbinary::StaticSize for #name #type_generics #where_clause {
1095            const MAX_SIZE: usize = #maximum;
1096            const PACKED_MAX_BITS: usize = #packed_bits;
1097            const PACKED_MAX_SIZE: usize = ::rustbinary::static_size::bytes_for_bits(#packed_bits);
1098        }
1099    })
1100}
1101
1102fn type_name(ty: &Type) -> String {
1103    ty.to_token_stream().to_string().replace(' ', "")
1104}
1105
1106// ---------------------------------------------------------------------------
1107// DecodeBounded: schema-derived resource cost algebra (B/A/D/W).
1108// ---------------------------------------------------------------------------
1109
1110fn bounded_field_input(field: &syn::Field) -> proc_macro2::TokenStream {
1111    let ty = &field.ty;
1112    quote!(<#ty as ::rustbinary::DecodeBounded>::MAX_INPUT)
1113}
1114
1115fn bounded_field_alloc(field: &syn::Field) -> proc_macro2::TokenStream {
1116    let ty = &field.ty;
1117    quote!(<#ty as ::rustbinary::DecodeBounded>::MAX_ALLOC)
1118}
1119
1120fn bounded_field_depth(field: &syn::Field) -> proc_macro2::TokenStream {
1121    let ty = &field.ty;
1122    quote!(<#ty as ::rustbinary::DecodeBounded>::MAX_DEPTH)
1123}
1124
1125fn bounded_field_work(field: &syn::Field) -> proc_macro2::TokenStream {
1126    let ty = &field.ty;
1127    quote!(<#ty as ::rustbinary::DecodeBounded>::MAX_WORK)
1128}
1129
1130fn bounded_field_structural(field: &syn::Field) -> proc_macro2::TokenStream {
1131    let ty = &field.ty;
1132    quote!(<#ty as ::rustbinary::DecodeBounded>::MAX_STRUCTURAL_ELEMENT)
1133}
1134
1135/// Maximum per-element structural allocation across a field list.
1136fn max_bounded_structural(fields: &Fields) -> proc_macro2::TokenStream {
1137    fields.iter().fold(quote!(0usize), |maximum, field| {
1138        let structural = bounded_field_structural(field);
1139        quote!(::rustbinary::bounded::max(#maximum, #structural))
1140    })
1141}
1142
1143/// Sum of field input bounds; named fields additionally contribute their key
1144/// bytes (mirroring the encoder's object-key cost).
1145fn sum_bounded_input(fields: &Fields) -> proc_macro2::TokenStream {
1146    fields
1147        .iter()
1148        .enumerate()
1149        .fold(quote!(0usize), |sum, (index, field)| {
1150            let input = bounded_field_input(field);
1151            if field.ident.is_some() {
1152                let key = key_size(&field_name(index, field));
1153                quote!(::rustbinary::bounded::saturating_add(
1154                    #sum,
1155                    ::rustbinary::bounded::saturating_add(#input, #key),
1156                ))
1157            } else {
1158                quote!(::rustbinary::bounded::saturating_add(#sum, #input))
1159            }
1160        })
1161}
1162
1163/// Sum of field allocation bounds.
1164fn sum_bounded_alloc(fields: &Fields) -> proc_macro2::TokenStream {
1165    fields.iter().fold(quote!(0usize), |sum, field| {
1166        let alloc = bounded_field_alloc(field);
1167        quote!(::rustbinary::bounded::saturating_add(#sum, #alloc))
1168    })
1169}
1170
1171/// One container level over the maximum field depth.
1172fn max_bounded_depth(fields: &Fields) -> proc_macro2::TokenStream {
1173    let maximum = fields.iter().fold(quote!(0usize), |maximum, field| {
1174        let depth = bounded_field_depth(field);
1175        quote!(::rustbinary::bounded::max(#maximum, #depth))
1176    });
1177    quote!(::rustbinary::bounded::depth_plus_one(#maximum))
1178}
1179
1180/// Sum of field work bounds; named fields additionally contribute their key
1181/// bytes.
1182fn sum_bounded_work(fields: &Fields) -> proc_macro2::TokenStream {
1183    fields
1184        .iter()
1185        .enumerate()
1186        .fold(quote!(0usize), |sum, (index, field)| {
1187            let work = bounded_field_work(field);
1188            if field.ident.is_some() {
1189                let key = key_size(&field_name(index, field));
1190                quote!(::rustbinary::bounded::saturating_add(
1191                    #sum,
1192                    ::rustbinary::bounded::saturating_add(#work, #key),
1193                ))
1194            } else {
1195                quote!(::rustbinary::bounded::saturating_add(#sum, #work))
1196            }
1197        })
1198}
1199
1200/// Variant content bounds, excluding the variant key added by the enum
1201/// wrapper.
1202fn variant_bounded_input(variant: &syn::Variant) -> proc_macro2::TokenStream {
1203    match &variant.fields {
1204        Fields::Unit => quote!(1usize),
1205        Fields::Unnamed(f) if f.unnamed.len() == 1 => bounded_field_input(&f.unnamed[0]),
1206        other => {
1207            let payload = sum_bounded_input(other);
1208            quote!(::rustbinary::bounded::saturating_add(#payload, 2usize))
1209        }
1210    }
1211}
1212
1213fn variant_bounded_alloc(variant: &syn::Variant) -> proc_macro2::TokenStream {
1214    match &variant.fields {
1215        Fields::Unit => quote!(0usize),
1216        Fields::Unnamed(f) if f.unnamed.len() == 1 => bounded_field_alloc(&f.unnamed[0]),
1217        other => sum_bounded_alloc(other),
1218    }
1219}
1220
1221fn variant_bounded_depth(variant: &syn::Variant) -> proc_macro2::TokenStream {
1222    match &variant.fields {
1223        Fields::Unit => quote!(0usize),
1224        Fields::Unnamed(f) if f.unnamed.len() == 1 => bounded_field_depth(&f.unnamed[0]),
1225        other => max_bounded_depth(other),
1226    }
1227}
1228
1229fn variant_bounded_work(variant: &syn::Variant) -> proc_macro2::TokenStream {
1230    match &variant.fields {
1231        Fields::Unit => quote!(1usize),
1232        Fields::Unnamed(f) if f.unnamed.len() == 1 => bounded_field_work(&f.unnamed[0]),
1233        other => {
1234            let payload = sum_bounded_work(other);
1235            quote!(::rustbinary::bounded::saturating_add(#payload, 2usize))
1236        }
1237    }
1238}
1239
1240fn variant_bounded_structural(variant: &syn::Variant) -> proc_macro2::TokenStream {
1241    match &variant.fields {
1242        Fields::Unit => quote!(0usize),
1243        Fields::Unnamed(f) if f.unnamed.len() == 1 => bounded_field_structural(&f.unnamed[0]),
1244        other => max_bounded_structural(other),
1245    }
1246}
1247
1248fn decode_bounded_impl(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
1249    let name = &input.ident;
1250    let generics = add_bound(
1251        input.generics.clone(),
1252        parse_quote!(::rustbinary::DecodeBounded),
1253    );
1254    let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
1255    let (max_input, max_alloc, max_depth, max_work, max_structural) = match &input.data {
1256        Data::Struct(data) => match &data.fields {
1257            Fields::Unit => (
1258                quote!(1usize),
1259                quote!(0usize),
1260                quote!(0usize),
1261                quote!(1usize),
1262                quote!(0usize),
1263            ),
1264            Fields::Unnamed(_) | Fields::Named(_) => {
1265                let input = sum_bounded_input(&data.fields);
1266                let alloc = sum_bounded_alloc(&data.fields);
1267                let depth = max_bounded_depth(&data.fields);
1268                let work = sum_bounded_work(&data.fields);
1269                let structural = max_bounded_structural(&data.fields);
1270                (
1271                    quote!(::rustbinary::bounded::saturating_add(#input, 2usize)),
1272                    alloc,
1273                    depth,
1274                    quote!(::rustbinary::bounded::saturating_add(#work, 2usize)),
1275                    structural,
1276                )
1277            }
1278        },
1279        Data::Enum(data) => {
1280            // External nextjson enums encode as an object with one variant key.
1281            let mut input = quote!(0usize);
1282            let mut alloc = quote!(0usize);
1283            let mut depth = quote!(0usize);
1284            let mut work = quote!(0usize);
1285            let mut structural = quote!(0usize);
1286            for variant in &data.variants {
1287                let key = key_size(&variant.ident.to_string());
1288                let vinput = variant_bounded_input(variant);
1289                let valloc = variant_bounded_alloc(variant);
1290                let vdepth = variant_bounded_depth(variant);
1291                let vwork = variant_bounded_work(variant);
1292                let vstructural = variant_bounded_structural(variant);
1293                input = quote!(::rustbinary::bounded::max(
1294                    #input,
1295                    ::rustbinary::bounded::saturating_add(#key, #vinput),
1296                ));
1297                alloc = quote!(::rustbinary::bounded::max(#alloc, #valloc));
1298                depth = quote!(::rustbinary::bounded::max(#depth, #vdepth));
1299                work = quote!(::rustbinary::bounded::max(
1300                    #work,
1301                    ::rustbinary::bounded::saturating_add(#key, #vwork),
1302                ));
1303                structural = quote!(::rustbinary::bounded::max(#structural, #vstructural));
1304            }
1305            (
1306                quote!(::rustbinary::bounded::saturating_add(
1307                    ::rustbinary::bounded::saturating_add(1usize, #input),
1308                    1usize,
1309                )),
1310                alloc,
1311                quote!(::rustbinary::bounded::depth_plus_one(#depth)),
1312                quote!(::rustbinary::bounded::saturating_add(
1313                    ::rustbinary::bounded::saturating_add(1usize, #work),
1314                    1usize,
1315                )),
1316                structural,
1317            )
1318        }
1319        Data::Union(_) => {
1320            return Err(syn::Error::new_spanned(
1321                input,
1322                "DecodeBounded cannot be derived for unions",
1323            ))
1324        }
1325    };
1326    Ok(quote! {
1327        impl #impl_generics ::rustbinary::DecodeBounded for #name #type_generics #where_clause {
1328            const MAX_INPUT: usize = #max_input;
1329            const MAX_ALLOC: usize = #max_alloc;
1330            const MAX_DEPTH: usize = #max_depth;
1331            const MAX_WORK: usize = #max_work;
1332            const MAX_STRUCTURAL_ELEMENT: usize = #max_structural;
1333        }
1334    })
1335}
1336
1337/// Explicit `#[entropy(symbols = N)]` alphabet declaration, if present.
1338fn declared_symbols(field: &syn::Field) -> syn::Result<Option<u32>> {
1339    let mut attributes = field
1340        .attrs
1341        .iter()
1342        .filter(|attribute| attribute.path().is_ident("entropy"));
1343    let Some(attribute) = attributes.next() else {
1344        return Ok(None);
1345    };
1346    if let Some(duplicate) = attributes.next() {
1347        return Err(syn::Error::new_spanned(
1348            duplicate,
1349            "duplicate #[entropy] attribute",
1350        ));
1351    }
1352    let Meta::List(list) = &attribute.meta else {
1353        return Err(syn::Error::new_spanned(
1354            attribute,
1355            "use #[entropy(symbols = N)]",
1356        ));
1357    };
1358
1359    let mut count = None;
1360    list.parse_nested_meta(|meta| {
1361        if meta.path.is_ident("symbols") {
1362            let value: syn::LitInt = meta.value()?.parse()?;
1363            let parsed: u32 = value.base10_parse()?;
1364            if parsed == 0 || parsed > 1 << 15 {
1365                return Err(meta.error("symbols must be in 1..=32768"));
1366            }
1367            count = Some(parsed);
1368            Ok(())
1369        } else {
1370            Err(meta.error("unsupported entropy option"))
1371        }
1372    })?;
1373    Ok(count)
1374}
1375
1376/// Symbol alphabet for a field's declared `#[bits = N]` range, when it fits
1377/// the rANS alphabet cap.
1378fn bits_symbols(field: &syn::Field) -> syn::Result<Option<u32>> {
1379    match declared_bits(field)? {
1380        Some(bits) if bits <= 15 => Ok(Some(1u32 << bits)),
1381        _ => Ok(None),
1382    }
1383}
1384
1385/// Symbol alphabet for known primitive field types, when single-symbol
1386/// encodable. Wide integers are not single-symbol encodable in rANS
1387/// (alphabet is capped at `2^15`), so they report `0` and the caller codes
1388/// their bytes individually.
1389fn primitive_symbols(ty: &Type) -> u32 {
1390    match ty {
1391        Type::Path(path) => {
1392            let last = path
1393                .path
1394                .segments
1395                .last()
1396                .map(|segment| segment.ident.to_string())
1397                .unwrap_or_default();
1398            match last.as_str() {
1399                "bool" => 2,
1400                "u8" | "i8" => 1 << 8,
1401                _ => 0,
1402            }
1403        }
1404        _ => 0,
1405    }
1406}
1407
1408/// Deterministic schema-derived symbol count for one field.
1409fn field_symbols(field: &syn::Field) -> syn::Result<u32> {
1410    if let Some(count) = declared_symbols(field)? {
1411        return Ok(count);
1412    }
1413    if let Some(count) = bits_symbols(field)? {
1414        return Ok(count);
1415    }
1416    Ok(primitive_symbols(&field.ty))
1417}
1418
1419fn reflect_fields(fields: &Fields) -> syn::Result<proc_macro2::TokenStream> {
1420    let descriptors: Vec<syn::Result<proc_macro2::TokenStream>> = fields
1421        .iter()
1422        .enumerate()
1423        .map(|(index, field)| {
1424            let name = field_name(index, field);
1425            let ty = type_name(&field.ty);
1426            let symbols = field_symbols(field)?;
1427            Ok(quote!(::rustbinary::FieldInfo {
1428                name: #name,
1429                type_name: #ty,
1430                index: #index,
1431                symbols: #symbols,
1432            }))
1433        })
1434        .collect();
1435    let mut items = Vec::new();
1436    for descriptor in descriptors {
1437        items.push(descriptor?);
1438    }
1439    Ok(quote!(&[#(#items),*]))
1440}
1441
1442fn reflect_impl(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
1443    let name = &input.ident;
1444    let generics = input.generics.clone();
1445    let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
1446    let shape = match &input.data {
1447        Data::Struct(DataStruct { fields, .. }) => {
1448            let fields = reflect_fields(fields)?;
1449            quote!(::rustbinary::TypeShape::Struct(#fields))
1450        }
1451        Data::Enum(data) => {
1452            let variants = data.variants.iter().enumerate().map(|(index, variant)| {
1453                let variant_name = variant.ident.to_string();
1454                let fields = reflect_fields(&variant.fields);
1455                match fields {
1456                    Ok(fields) => quote!(::rustbinary::VariantInfo {
1457                        name: #variant_name,
1458                        index: #index,
1459                        fields: #fields,
1460                    }),
1461                    Err(error) => error.to_compile_error(),
1462                }
1463            });
1464            quote!(::rustbinary::TypeShape::Enum(&[#(#variants),*]))
1465        }
1466        Data::Union(_) => {
1467            return Err(syn::Error::new_spanned(
1468                input,
1469                "Reflect cannot be derived for unions",
1470            ))
1471        }
1472    };
1473    Ok(quote! {
1474        impl #impl_generics ::rustbinary::Reflect for #name #type_generics #where_clause {
1475            const TYPE_NAME: &'static str = concat!(module_path!(), "::", stringify!(#name));
1476            const SHAPE: ::rustbinary::TypeShape = #shape;
1477        }
1478    })
1479}
1480
1481fn declared_bits(field: &syn::Field) -> syn::Result<Option<usize>> {
1482    let mut attributes = field
1483        .attrs
1484        .iter()
1485        .filter(|attribute| attribute.path().is_ident("bits"));
1486    let Some(attribute) = attributes.next() else {
1487        return Ok(None);
1488    };
1489    if let Some(duplicate) = attributes.next() {
1490        return Err(syn::Error::new_spanned(
1491            duplicate,
1492            "duplicate #[bits] attribute",
1493        ));
1494    }
1495    let value = match &attribute.meta {
1496        Meta::NameValue(name_value) => match &name_value.value {
1497            Expr::Lit(expression) => match &expression.lit {
1498                Lit::Int(value) => value.base10_parse()?,
1499                _ => {
1500                    return Err(syn::Error::new_spanned(
1501                        expression,
1502                        "bits must be an integer",
1503                    ))
1504                }
1505            },
1506            expression => {
1507                return Err(syn::Error::new_spanned(
1508                    expression,
1509                    "bits must be an integer",
1510                ))
1511            }
1512        },
1513        Meta::List(_) => attribute.parse_args::<syn::LitInt>()?.base10_parse()?,
1514        Meta::Path(_) => return Err(syn::Error::new_spanned(attribute, "use #[bits = N]")),
1515    };
1516    if value == 0 || value > 128 {
1517        return Err(syn::Error::new_spanned(
1518            attribute,
1519            "bit width must be between 1 and 128",
1520        ));
1521    }
1522    Ok(Some(value))
1523}
1524
1525fn add_bit_bounds(
1526    mut generics: Generics,
1527    fields: impl Iterator<Item = syn::Field>,
1528) -> syn::Result<Generics> {
1529    let where_clause = generics.make_where_clause();
1530    for field in fields {
1531        let has_declared_bits = declared_bits(&field)?.is_some();
1532        let ty = field.ty;
1533        if has_declared_bits {
1534            where_clause
1535                .predicates
1536                .push(parse_quote!(#ty: ::rustbinary::BitValue));
1537        } else {
1538            where_clause
1539                .predicates
1540                .push(parse_quote!(#ty: ::rustbinary::BitPack));
1541        }
1542    }
1543    Ok(generics)
1544}
1545
1546fn bit_count(fields: &Fields) -> syn::Result<proc_macro2::TokenStream> {
1547    let mut total = quote!(0usize);
1548    for field in fields {
1549        let ty = &field.ty;
1550        let bits = match declared_bits(field)? {
1551            Some(width) => quote!(#width),
1552            None => quote!(<#ty as ::rustbinary::BitPack>::MAX_BITS),
1553        };
1554        total = quote!(#total.saturating_add(#bits));
1555    }
1556    Ok(total)
1557}
1558
1559fn pack_statement(
1560    field: &syn::Field,
1561    value: proc_macro2::TokenStream,
1562    borrowed: bool,
1563) -> syn::Result<proc_macro2::TokenStream> {
1564    let ty = &field.ty;
1565    Ok(match declared_bits(field)? {
1566        Some(width) => {
1567            let value = if borrowed { quote!(*#value) } else { value };
1568            quote! {
1569                writer.write(<#ty as ::rustbinary::BitValue>::encode_bits(#value, #width)?, #width)?;
1570            }
1571        }
1572        None => quote! {
1573            <#ty as ::rustbinary::BitPack>::pack(#value, writer)?;
1574        },
1575    })
1576}
1577
1578fn unpack_expression(field: &syn::Field) -> syn::Result<proc_macro2::TokenStream> {
1579    let ty = &field.ty;
1580    Ok(match declared_bits(field)? {
1581        Some(width) => quote! {
1582            <#ty as ::rustbinary::BitValue>::decode_bits(reader.read(#width)?, #width)?
1583        },
1584        None => quote! {
1585            <#ty as ::rustbinary::BitPack>::unpack(reader)?
1586        },
1587    })
1588}
1589
1590fn bit_packed_impl(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
1591    let name = &input.ident;
1592    let fields = match &input.data {
1593        Data::Struct(data) => data.fields.iter().cloned().collect::<Vec<_>>(),
1594        Data::Enum(data) => data
1595            .variants
1596            .iter()
1597            .flat_map(|variant| variant.fields.iter().cloned())
1598            .collect(),
1599        Data::Union(_) => {
1600            return Err(syn::Error::new_spanned(
1601                input,
1602                "BitPacked cannot be derived for unions",
1603            ))
1604        }
1605    };
1606    let generics = add_bit_bounds(input.generics.clone(), fields.into_iter())?;
1607    let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
1608    let (maximum, pack, unpack) = match &input.data {
1609        Data::Struct(data) => bit_packed_struct(name, data)?,
1610        Data::Enum(data) => bit_packed_enum(name, data)?,
1611        Data::Union(_) => unreachable!(),
1612    };
1613    Ok(quote! {
1614        impl #impl_generics ::rustbinary::BitPack for #name #type_generics #where_clause {
1615            const MAX_BITS: usize = #maximum;
1616            fn pack(&self, writer: &mut ::rustbinary::BitWriter<'_>) -> ::rustbinary::Result<()> {
1617                #pack
1618                Ok(())
1619            }
1620            fn unpack(reader: &mut ::rustbinary::BitReader<'_>) -> ::rustbinary::Result<Self> {
1621                #unpack
1622            }
1623        }
1624    })
1625}
1626
1627fn bit_packed_struct(
1628    name: &syn::Ident,
1629    data: &DataStruct,
1630) -> syn::Result<(
1631    proc_macro2::TokenStream,
1632    proc_macro2::TokenStream,
1633    proc_macro2::TokenStream,
1634)> {
1635    let maximum = bit_count(&data.fields)?;
1636    let mut packs = Vec::new();
1637    let mut values = Vec::new();
1638    for (index, field) in data.fields.iter().enumerate() {
1639        let member = field
1640            .ident
1641            .clone()
1642            .map(syn::Member::Named)
1643            .unwrap_or_else(|| syn::Member::Unnamed(syn::Index::from(index)));
1644        packs.push(pack_statement(field, quote!(&self.#member), true)?);
1645        values.push(unpack_expression(field)?);
1646    }
1647    let construct = match &data.fields {
1648        Fields::Named(fields) => {
1649            let names = fields
1650                .named
1651                .iter()
1652                .map(|field| field.ident.as_ref().expect("named"));
1653            quote!(#name { #(#names: #values),* })
1654        }
1655        Fields::Unnamed(_) => quote!(#name(#(#values),*)),
1656        Fields::Unit => quote!(#name),
1657    };
1658    Ok((maximum, quote!(#(#packs)*), quote!(Ok(#construct))))
1659}
1660
1661fn bit_packed_enum(
1662    name: &syn::Ident,
1663    data: &DataEnum,
1664) -> syn::Result<(
1665    proc_macro2::TokenStream,
1666    proc_macro2::TokenStream,
1667    proc_macro2::TokenStream,
1668)> {
1669    if data.variants.is_empty() {
1670        return Err(syn::Error::new_spanned(
1671            name,
1672            "empty enums cannot be bit-packed",
1673        ));
1674    }
1675    let tag_bits = if data.variants.len() <= 1 {
1676        0usize
1677    } else {
1678        (usize::BITS - (data.variants.len() - 1).leading_zeros()) as usize
1679    };
1680    let mut maximum = quote!(0usize);
1681    let mut pack_arms = Vec::new();
1682    let mut unpack_arms = Vec::new();
1683    for (variant_index, variant) in data.variants.iter().enumerate() {
1684        let variant_name = &variant.ident;
1685        let payload_bits = bit_count(&variant.fields)?;
1686        maximum = quote!(::rustbinary::__bitpack_max(#maximum, #payload_bits));
1687        let bindings = (0..variant.fields.len())
1688            .map(|index| syn::Ident::new(&format!("field_{index}"), variant.ident.span()))
1689            .collect::<Vec<_>>();
1690        let pattern = match &variant.fields {
1691            Fields::Named(fields) => {
1692                let names = fields
1693                    .named
1694                    .iter()
1695                    .map(|field| field.ident.as_ref().expect("named"));
1696                quote!(Self::#variant_name { #(#names: #bindings),* })
1697            }
1698            Fields::Unnamed(_) => quote!(Self::#variant_name(#(#bindings),*)),
1699            Fields::Unit => quote!(Self::#variant_name),
1700        };
1701        let packs = variant
1702            .fields
1703            .iter()
1704            .zip(&bindings)
1705            .map(|(field, binding)| pack_statement(field, quote!(#binding), true))
1706            .collect::<syn::Result<Vec<_>>>()?;
1707        pack_arms.push(quote! {
1708            #pattern => {
1709                writer.write(#variant_index as u128, #tag_bits)?;
1710                #(#packs)*
1711            }
1712        });
1713        let values = variant
1714            .fields
1715            .iter()
1716            .map(unpack_expression)
1717            .collect::<syn::Result<Vec<_>>>()?;
1718        let construct = match &variant.fields {
1719            Fields::Named(fields) => {
1720                let names = fields
1721                    .named
1722                    .iter()
1723                    .map(|field| field.ident.as_ref().expect("named"));
1724                quote!(Self::#variant_name { #(#names: #values),* })
1725            }
1726            Fields::Unnamed(_) => quote!(Self::#variant_name(#(#values),*)),
1727            Fields::Unit => quote!(Self::#variant_name),
1728        };
1729        unpack_arms.push(quote!(#variant_index => Ok(#construct)));
1730    }
1731    Ok((
1732        quote!((#tag_bits).saturating_add(#maximum)),
1733        quote!(match self { #(#pack_arms),* }),
1734        quote! {
1735            match reader.read(#tag_bits)? as usize {
1736                #(#unpack_arms,)*
1737                _ => Err(::rustbinary::Error::BitPacking("unknown packed enum variant")),
1738            }
1739        },
1740    ))
1741}
1742
1743#[cfg(test)]
1744mod tests {
1745    use super::declared_bits;
1746    use syn::parse_quote;
1747
1748    #[test]
1749    fn bits_attribute_accepts_supported_forms() {
1750        let named: syn::Field = parse_quote!(#[bits = 7] value: u8);
1751        let listed: syn::Field = parse_quote!(#[bits(9)] value: u16);
1752        assert_eq!(declared_bits(&named).unwrap(), Some(7));
1753        assert_eq!(declared_bits(&listed).unwrap(), Some(9));
1754    }
1755
1756    #[test]
1757    fn bits_attribute_rejects_duplicates() {
1758        let field: syn::Field = parse_quote!(#[bits = 3] #[bits = 4] value: u8);
1759        let error = declared_bits(&field).unwrap_err();
1760        assert!(error.to_string().contains("duplicate #[bits] attribute"));
1761    }
1762}