compactly-derive 0.1.8

Derive macros for compactly crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
use std::collections::{BTreeSet, HashMap};

use proc_macro2::{Ident, Span};
use proc_macro_warning::Warning;
use quote::{quote, ToTokens};
use syn::{spanned::Spanned, Attribute, GenericParam, TraitBound};
use synstructure::{BindingInfo, VariantInfo};

/// Does `ty` name `LowCardinality` (ignoring any leading path qualifier)?
fn is_low_cardinality(ty: &syn::Type) -> bool {
    matches!(ty, syn::Type::Path(p)
        if p.path.segments.last().is_some_and(|s| s.ident == "LowCardinality"))
}

/// Does `ty` mention `String` anywhere (e.g. `String`, `Option<String>`,
/// `Vec<String>`, `Option<Vec<String>>`)? Used to flag the
/// `LowCardinality<String>` antipattern, which clones the String on every
/// repeated value; users should prefer `LowCardinality<Arc<str>>` instead.
fn type_mentions_string(ty: &syn::Type) -> bool {
    match ty {
        syn::Type::Path(p) => p.path.segments.iter().any(|seg| {
            seg.ident == "String"
                || match &seg.arguments {
                    syn::PathArguments::AngleBracketed(args) => args.args.iter().any(
                        |a| matches!(a, syn::GenericArgument::Type(t) if type_mentions_string(t)),
                    ),
                    _ => false,
                }
        }),
        _ => false,
    }
}

#[derive(Debug, Clone)]
struct EncodingStrategy(syn::Type);
impl EncodingStrategy {
    fn parse_attrs(attrs: &[Attribute]) -> Vec<EncodingStrategy> {
        attrs
            .iter()
            .filter_map(|a| {
                if a.path().is_ident("compactly") {
                    let strategy: syn::Type = a.parse_args().expect("Unrecognize strategy");
                    Some(EncodingStrategy(strategy))
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
    }
    fn parse(binding: &BindingInfo) -> Option<EncodingStrategy> {
        match Self::parse_attrs(&binding.ast().attrs).as_slice() {
            [] => None,
            [s] => Some(s.clone()),
            _ => panic!("Cannot support multiple encoding strategies: {binding:?}"),
        }
    }
}

pub(crate) fn derive_compactly(mut s: synstructure::Structure) -> proc_macro2::TokenStream {
    let mut bound_names = BTreeSet::new();
    bound_names.insert(Ident::new("discriminant", Span::call_site()));
    s.binding_name(|field, i| {
        if let Some(name) = &field.ident {
            if bound_names.contains(name) {
                for i in 0..10_000 {
                    let ident = Ident::new(&format!("{name}_{i}"), Span::call_site());
                    if !bound_names.contains(&ident) {
                        bound_names.insert(ident.clone());
                        return ident;
                    }
                }
                panic!("compactly does not currently support types with more than 10k identical field names");
            } else {
                bound_names.insert(name.clone());
                name.clone()
            }
        } else {
            let ident = {
                let ident = Ident::new(&format!("__binding_{i}"), Span::call_site());
            if bound_names.contains(&ident){
                crate::get_unique_name(&bound_names, "__binding_", 10000)
            }
            else {
                ident
            }
        };
            assert!(!bound_names.contains(&ident));
            bound_names.insert(ident.clone());
            ident
        }
    });

    let encode_trait = syn::parse_str::<TraitBound>("Encode").unwrap();
    let (_impl_generics, _ty_generics, where_clause) = s.ast().generics.split_for_impl();
    let mut where_clause = where_clause.cloned();
    s.add_trait_bounds(
        &encode_trait,
        &mut where_clause,
        synstructure::AddBounds::Generics,
    );

    let context_type_params = s
        .ast()
        .generics
        .params
        .iter()
        .filter_map(|param| {
            if let GenericParam::Type(ty) = param {
                Some(ty.ident.clone())
            } else {
                None
            }
        })
        .collect::<Vec<_>>();
    let context_const_params = s
        .ast()
        .generics
        .params
        .iter()
        .filter_map(|param| {
            if let GenericParam::Const(c) = param {
                Some((c.ident.clone(), c.ty.clone()))
            } else {
                None
            }
        })
        .collect::<Vec<_>>();
    let context_generics = {
        let type_bounds = context_type_params.iter().map(|t| quote! { #t: Encode });
        let const_defs = context_const_params
            .iter()
            .map(|(name, ty)| quote! { const #name: #ty });
        let items = type_bounds.chain(const_defs).collect::<Vec<_>>();
        if items.is_empty() {
            quote! {}
        } else {
            quote! { <#(#items),*> }
        }
    };
    let context_generics_without_bound = {
        let type_names = context_type_params.iter().map(|t| quote! { #t });
        let const_names = context_const_params
            .iter()
            .map(|(name, _)| quote! { #name });
        let items = type_names.chain(const_names).collect::<Vec<_>>();
        if items.is_empty() {
            quote! {}
        } else {
            quote! { <#(#items),*> }
        }
    };
    let mut binding_strategies: HashMap<Ident, Option<EncodingStrategy>> = HashMap::new();
    let mut strategies = Vec::new();
    for binding in s
        .variants()
        .iter()
        .flat_map(|variant| variant.bindings().iter())
    {
        let strategy = EncodingStrategy::parse(binding);
        strategies.push(strategy.clone());
        binding_strategies.insert(binding.binding.clone(), strategy);
    }

    // Emit a deprecation-style compiler warning for the `LowCardinality<String>`
    // antipattern: on a repeated value, the String variant clones (reallocates)
    // the cached String, whereas `LowCardinality<Arc<str>>` turns a cache hit into
    // a cheap refcount bump and uses less memory after deserialization.
    let antipattern_warnings = s
        .variants()
        .iter()
        .flat_map(|variant| variant.bindings().iter())
        .filter_map(|binding| {
            let strategy = binding_strategies.get(&binding.binding)?.as_ref()?;
            let ty = &binding.ast().ty;
            if is_low_cardinality(&strategy.0) && type_mentions_string(ty) {
                Some(ty.span())
            } else {
                None
            }
        })
        .enumerate()
        .map(|(i, span)| {
            Warning::new_deprecated("LowCardinalityString")
                .old("encode a String field with `#[compactly(LowCardinality)]`, which clones (reallocates) the String on every repeated value")
                .new("use `Arc<str>` (i.e. `#[compactly(LowCardinality)] field: Arc<str>`), so a cache hit is a cheap refcount bump and deserialization shares buffers")
                .index(i)
                .span(span)
                .build_or_panic()
        })
        .collect::<Vec<_>>();
    let context = s
        .variants()
        .iter()
        .flat_map(|variant| variant.bindings().iter())
        .zip(strategies.iter().cloned())
        .map(|(binding, strategy)| {
            let ty = &binding.ast().ty;
            let name = &binding.binding;
            if let Some(strategy) = strategy {
                let strategy = strategy.0;
                quote! {
                    #name: <#strategy as EncodingStrategy<#ty>>::Context
                }
            } else {
                quote! {
                    #name: <#ty as Encode>::Context
                }
            }
        })
        .collect::<Vec<_>>();
    let bindings = s
        .variants()
        .iter()
        .flat_map(|variant| variant.bindings().iter().map(|binding| &binding.binding))
        .collect::<Vec<_>>();

    let encode_fields = s.each(|binding| {
        let ty = &binding.ast().ty;
        let binding = &binding.binding;
        if let Some(Some(strategy)) = binding_strategies.get(binding) {
            let strategy = &strategy.0;
            quote! {
                <#strategy as EncodingStrategy<#ty>>::encode(&#binding, writer, &mut ctx.#binding);
            }
        } else {
            quote! {
                #binding.encode(writer, &mut ctx.#binding);
            }
        }
    });
    let num_variants = s.variants().len();
    let max_discriminant = num_variants - 1;
    let discriminant_type = quote! { compactly::v2::AtMost<#max_discriminant> };
    let get_discriminant = |variant: &VariantInfo| -> usize {
        s.variants()
            .iter()
            .enumerate()
            .find(|(_, v)| v.ast().ident == variant.ast().ident)
            .map(|x| x.0)
            .expect("bug: invalid variant")
    };
    let encode_discriminant = s.each_variant(|variant| {
        let discriminant = get_discriminant(variant);
        quote! {
            compactly::v2::AtMost::<#max_discriminant>::new(#discriminant).encode(writer, &mut ctx.discriminant);
        }
    });

    let decode_variants = s
        .variants()
        .iter()
        .map(|variant| {
            let decoding = variant
                .bindings()
                .iter()
                .map(|binding| {
                    if let Some(Some(strategy)) = binding_strategies.get(&binding.binding) {
                        let strategy = &strategy.0;
                        let ty = &binding.ast().ty;
                        quote! {
                            <#strategy as EncodingStrategy<#ty>>::decode(reader, &mut ctx.#binding)?
                        }
                    } else {
                        quote! {
                            Encode::decode(reader, &mut ctx.#binding)?
                        }
                    }
                })
                .collect::<Vec<_>>();
            variant.construct(|_, i| decoding[i].clone())
        })
        .collect::<Vec<_>>();
    let discriminants = 0..s.variants().len();
    let decode = quote! {
        Ok(match usize::from(discriminant) {
            #(#discriminants => #decode_variants,)*
            _ => return Err(std::io::Error::other("This discriminant should be impossible"))
        })
    };

    let strategies_to_impl = EncodingStrategy::parse_attrs(&s.ast().attrs);
    let impl_strategies = if strategies_to_impl.is_empty() {
        Vec::new()
    } else {
        let typename = s.ast().ident.clone();
        assert_eq!(num_variants, 1, "Cannot derive strategy for an enum");
        let bindings = s.variants()[0].bindings();
        assert_eq!(
            bindings.len(),
            1,
            "Can only derive strategy for newtype structs"
        );
        let binding = &bindings[0];
        strategies_to_impl
        .into_iter()
        .map(|EncodingStrategy(strategy)| {
            let ty = binding.ast().ty.clone();
            let field_name = binding.ast().ident.as_ref().map(|i| i.to_token_stream()).unwrap_or(quote! {0});
            let decoded = s.variants()[0].construct(|_, _| quote! { <#strategy as EncodingStrategy<#ty>>::decode(reader, ctx)? });
            quote! {
                impl EncodingStrategy<#typename> for #strategy {
                    type Context = <#strategy as EncodingStrategy<#ty>>::Context;
                    fn encode<E: EntropyCoder>(value: &#typename, writer: &mut E, ctx: &mut Self::Context) {
                        <#strategy as EncodingStrategy<#ty>>::encode(&value.#field_name, writer, ctx)
                    }
                    fn decode<D: EntropyDecoder>(reader: &mut D, ctx: &mut Self::Context) -> Result<#typename, std::io::Error> {
                        Ok(#decoded)
                    }
                }
            }
        })
        .collect::<Vec<_>>()
    };

    s.gen_impl(quote! {
        extern crate compactly;
        use compactly::v2::{Encode, EncodingStrategy, EntropyCoder, EntropyDecoder};
        use compactly::{Small, LowCardinality, Decimal, Compressible, Incompressible, Mapping, Normal, Sorted, Values};

        #(#antipattern_warnings)*

        pub struct DerivedContext #context_generics {
            discriminant: <#discriminant_type as Encode>::Context,
            #(#context,)*
        }
        impl #context_generics Default for DerivedContext #context_generics_without_bound {
            fn default() -> Self {
                Self {
                    discriminant: Default::default(),
                    #(#bindings: Default::default(),)*
                }
            }
        }
        impl #context_generics Clone for DerivedContext #context_generics_without_bound {
            fn clone(&self) -> Self {
                Self {
                    discriminant: self.discriminant.clone(),
                    #(#bindings: self.#bindings.clone(),)*
                }
            }
        }

        #(#impl_strategies)*

        gen impl Encode for @Self {
            #![allow(unused_variables,non_shorthand_field_patterns)]
            type Context = DerivedContext #context_generics_without_bound;
            fn encode<E: EntropyCoder>(&self, writer: &mut E, ctx: &mut Self::Context) {
                match self { #encode_discriminant }
                match self { #encode_fields }
            }
            fn decode<D: EntropyDecoder>(
                reader: &mut D,
                ctx: &mut Self::Context,
            ) -> Result<Self, std::io::Error> {
                let discriminant: #discriminant_type = Encode::decode(reader, &mut ctx.discriminant)?;
                #decode
            }
        }
    })
}

#[cfg(test)]
fn pretty(tokens: proc_macro2::TokenStream) -> String {
    if let Ok(syntax_tree) = syn::parse2::<syn::File>(tokens.clone()) {
        prettyplease::unparse(&syntax_tree)
    } else {
        tokens.to_string()
    }
}

#[test]
fn const_generic_in_field_type_forwarded_to_context() {
    // Const generic params that appear in field types must be forwarded to
    // DerivedContext so that references like `<[u8; N] as Encode>::Context`
    // are valid inside the struct body.
    let di: syn::DeriveInput = syn::parse_quote! {
        pub struct Buffer<const N: usize> {
            data: [u8; N],
        }
    };
    let s = synstructure::Structure::new(&di);
    let output = pretty(derive_compactly(s));
    assert!(
        output.contains("pub struct DerivedContext<const N: usize> {"),
        "expected DerivedContext to carry `const N: usize`:\n{output}"
    );
    assert!(
        output.contains("<[u8; N] as Encode>::Context"),
        "expected field to reference N:\n{output}"
    );
}

#[test]
fn field_named_discriminant_is_renamed() {
    // A user field named `discriminant` used to collide with the hardcoded
    // `discriminant` field in DerivedContext. After pre-seeding bound_names with
    // "discriminant", the user field is automatically renamed to `discriminant_0`.
    let di: syn::DeriveInput = syn::parse_quote! {
        pub struct HasDiscriminant {
            discriminant: u32,
            value: bool,
        }
    };
    let s = synstructure::Structure::new(&di);
    let output = pretty(derive_compactly(s));
    assert!(
        output.contains("discriminant: <compactly::v2::AtMost<0usize> as Encode>::Context,"),
        "expected hardcoded discriminant field:\n{output}"
    );
    assert!(
        output.contains("discriminant_0: <u32 as Encode>::Context,"),
        "expected user field renamed to discriminant_0:\n{output}"
    );
    assert!(
        !output.contains(
            "discriminant: <compactly::v2::AtMost<0usize> as Encode>::Context,\n        discriminant: <u32 as Encode>::Context,"
        ),
        "must not have duplicate discriminant fields:\n{output}"
    );
}

#[test]
fn low_cardinality_string_warns() {
    // A `LowCardinality<String>` field should expand to a deprecation warning
    // steering the user toward `Arc<str>`; non-String LowCardinality fields and
    // `Arc<str>` fields should not.
    let di: syn::DeriveInput = syn::parse_quote! {
        pub struct Record {
            #[compactly(LowCardinality)]
            recclass: String,
            #[compactly(LowCardinality)]
            tags: Option<Vec<String>>,
            #[compactly(LowCardinality)]
            shared: std::sync::Arc<str>,
            #[compactly(LowCardinality)]
            count: u32,
        }
    };
    let s = synstructure::Structure::new(&di);
    let output = pretty(derive_compactly(s));
    // Two String-bearing fields → two warnings.
    assert_eq!(
        output.matches("#[deprecated").count(),
        2,
        "expected exactly two deprecation warnings (String + Option<Vec<String>>):\n{output}"
    );
    assert!(
        output.contains("fn LowCardinalityString_0()")
            && output.contains("fn LowCardinalityString_1()"),
        "expected indexed warning fns:\n{output}"
    );
}

#[test]
fn impl_two_strategies() {
    let di: syn::DeriveInput = syn::parse_quote! {
        #[compactly(Small)]
        #[compactly(Sorted)]
        pub struct NewType(u32);
    };
    let s = synstructure::Structure::new(&di);

    expect_test::expect![[r#"
        const _: () = {
            extern crate compactly;
            use compactly::v2::{Encode, EncodingStrategy, EntropyCoder, EntropyDecoder};
            use compactly::{
                Small, LowCardinality, Decimal, Compressible, Incompressible, Mapping, Normal,
                Sorted, Values,
            };
            pub struct DerivedContext {
                discriminant: <compactly::v2::AtMost<0usize> as Encode>::Context,
                __binding_0: <u32 as Encode>::Context,
            }
            impl Default for DerivedContext {
                fn default() -> Self {
                    Self {
                        discriminant: Default::default(),
                        __binding_0: Default::default(),
                    }
                }
            }
            impl Clone for DerivedContext {
                fn clone(&self) -> Self {
                    Self {
                        discriminant: self.discriminant.clone(),
                        __binding_0: self.__binding_0.clone(),
                    }
                }
            }
            impl EncodingStrategy<NewType> for Small {
                type Context = <Small as EncodingStrategy<u32>>::Context;
                fn encode<E: EntropyCoder>(
                    value: &NewType,
                    writer: &mut E,
                    ctx: &mut Self::Context,
                ) {
                    <Small as EncodingStrategy<u32>>::encode(&value.0, writer, ctx)
                }
                fn decode<D: EntropyDecoder>(
                    reader: &mut D,
                    ctx: &mut Self::Context,
                ) -> Result<NewType, std::io::Error> {
                    Ok(NewType(<Small as EncodingStrategy<u32>>::decode(reader, ctx)?))
                }
            }
            impl EncodingStrategy<NewType> for Sorted {
                type Context = <Sorted as EncodingStrategy<u32>>::Context;
                fn encode<E: EntropyCoder>(
                    value: &NewType,
                    writer: &mut E,
                    ctx: &mut Self::Context,
                ) {
                    <Sorted as EncodingStrategy<u32>>::encode(&value.0, writer, ctx)
                }
                fn decode<D: EntropyDecoder>(
                    reader: &mut D,
                    ctx: &mut Self::Context,
                ) -> Result<NewType, std::io::Error> {
                    Ok(NewType(<Sorted as EncodingStrategy<u32>>::decode(reader, ctx)?))
                }
            }
            impl Encode for NewType {
                #![allow(unused_variables, non_shorthand_field_patterns)]
                type Context = DerivedContext;
                fn encode<E: EntropyCoder>(&self, writer: &mut E, ctx: &mut Self::Context) {
                    match self {
                        NewType(ref __binding_0) => {
                            compactly::v2::AtMost::<0usize>::new(0usize)
                                .encode(writer, &mut ctx.discriminant);
                        }
                    }
                    match self {
                        NewType(ref __binding_0) => {
                            __binding_0.encode(writer, &mut ctx.__binding_0);
                        }
                    }
                }
                fn decode<D: EntropyDecoder>(
                    reader: &mut D,
                    ctx: &mut Self::Context,
                ) -> Result<Self, std::io::Error> {
                    let discriminant: compactly::v2::AtMost<0usize> = Encode::decode(
                        reader,
                        &mut ctx.discriminant,
                    )?;
                    Ok(
                        match usize::from(discriminant) {
                            0usize => NewType(Encode::decode(reader, &mut ctx.__binding_0)?),
                            _ => {
                                return Err(
                                    std::io::Error::other(
                                        "This discriminant should be impossible",
                                    ),
                                );
                            }
                        },
                    )
                }
            }
        };
    "#]]
    .assert_eq(&pretty(derive_compactly(s)));
}

#[test]
fn impl_strategies() {
    let di: syn::DeriveInput = syn::parse_quote! {
        #[compactly(Sorted)]
        pub struct NewType(u32);
    };
    let s = synstructure::Structure::new(&di);

    expect_test::expect![[r#"
        const _: () = {
            extern crate compactly;
            use compactly::v2::{Encode, EncodingStrategy, EntropyCoder, EntropyDecoder};
            use compactly::{
                Small, LowCardinality, Decimal, Compressible, Incompressible, Mapping, Normal,
                Sorted, Values,
            };
            pub struct DerivedContext {
                discriminant: <compactly::v2::AtMost<0usize> as Encode>::Context,
                __binding_0: <u32 as Encode>::Context,
            }
            impl Default for DerivedContext {
                fn default() -> Self {
                    Self {
                        discriminant: Default::default(),
                        __binding_0: Default::default(),
                    }
                }
            }
            impl Clone for DerivedContext {
                fn clone(&self) -> Self {
                    Self {
                        discriminant: self.discriminant.clone(),
                        __binding_0: self.__binding_0.clone(),
                    }
                }
            }
            impl EncodingStrategy<NewType> for Sorted {
                type Context = <Sorted as EncodingStrategy<u32>>::Context;
                fn encode<E: EntropyCoder>(
                    value: &NewType,
                    writer: &mut E,
                    ctx: &mut Self::Context,
                ) {
                    <Sorted as EncodingStrategy<u32>>::encode(&value.0, writer, ctx)
                }
                fn decode<D: EntropyDecoder>(
                    reader: &mut D,
                    ctx: &mut Self::Context,
                ) -> Result<NewType, std::io::Error> {
                    Ok(NewType(<Sorted as EncodingStrategy<u32>>::decode(reader, ctx)?))
                }
            }
            impl Encode for NewType {
                #![allow(unused_variables, non_shorthand_field_patterns)]
                type Context = DerivedContext;
                fn encode<E: EntropyCoder>(&self, writer: &mut E, ctx: &mut Self::Context) {
                    match self {
                        NewType(ref __binding_0) => {
                            compactly::v2::AtMost::<0usize>::new(0usize)
                                .encode(writer, &mut ctx.discriminant);
                        }
                    }
                    match self {
                        NewType(ref __binding_0) => {
                            __binding_0.encode(writer, &mut ctx.__binding_0);
                        }
                    }
                }
                fn decode<D: EntropyDecoder>(
                    reader: &mut D,
                    ctx: &mut Self::Context,
                ) -> Result<Self, std::io::Error> {
                    let discriminant: compactly::v2::AtMost<0usize> = Encode::decode(
                        reader,
                        &mut ctx.discriminant,
                    )?;
                    Ok(
                        match usize::from(discriminant) {
                            0usize => NewType(Encode::decode(reader, &mut ctx.__binding_0)?),
                            _ => {
                                return Err(
                                    std::io::Error::other(
                                        "This discriminant should be impossible",
                                    ),
                                );
                            }
                        },
                    )
                }
            }
        };
    "#]]
    .assert_eq(&pretty(derive_compactly(s)));
}

#[test]
fn impl_newtype() {
    let di: syn::DeriveInput = syn::parse_quote! {
        pub struct NewType(u32);
    };
    let s = synstructure::Structure::new(&di);

    expect_test::expect![[r#"
        const _: () = {
            extern crate compactly;
            use compactly::v2::{Encode, EncodingStrategy, EntropyCoder, EntropyDecoder};
            use compactly::{
                Small, LowCardinality, Decimal, Compressible, Incompressible, Mapping, Normal,
                Sorted, Values,
            };
            pub struct DerivedContext {
                discriminant: <compactly::v2::AtMost<0usize> as Encode>::Context,
                __binding_0: <u32 as Encode>::Context,
            }
            impl Default for DerivedContext {
                fn default() -> Self {
                    Self {
                        discriminant: Default::default(),
                        __binding_0: Default::default(),
                    }
                }
            }
            impl Clone for DerivedContext {
                fn clone(&self) -> Self {
                    Self {
                        discriminant: self.discriminant.clone(),
                        __binding_0: self.__binding_0.clone(),
                    }
                }
            }
            impl Encode for NewType {
                #![allow(unused_variables, non_shorthand_field_patterns)]
                type Context = DerivedContext;
                fn encode<E: EntropyCoder>(&self, writer: &mut E, ctx: &mut Self::Context) {
                    match self {
                        NewType(ref __binding_0) => {
                            compactly::v2::AtMost::<0usize>::new(0usize)
                                .encode(writer, &mut ctx.discriminant);
                        }
                    }
                    match self {
                        NewType(ref __binding_0) => {
                            __binding_0.encode(writer, &mut ctx.__binding_0);
                        }
                    }
                }
                fn decode<D: EntropyDecoder>(
                    reader: &mut D,
                    ctx: &mut Self::Context,
                ) -> Result<Self, std::io::Error> {
                    let discriminant: compactly::v2::AtMost<0usize> = Encode::decode(
                        reader,
                        &mut ctx.discriminant,
                    )?;
                    Ok(
                        match usize::from(discriminant) {
                            0usize => NewType(Encode::decode(reader, &mut ctx.__binding_0)?),
                            _ => {
                                return Err(
                                    std::io::Error::other(
                                        "This discriminant should be impossible",
                                    ),
                                );
                            }
                        },
                    )
                }
            }
        };
    "#]]
    .assert_eq(&pretty(derive_compactly(s)));
}