fory-core 1.0.0

Apache Fory: Blazingly fast multi-language serialization framework with trait objects and reference support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

// Re-exports for use in macros - these are needed for macro expansion in user crates
// Even though they appear unused in this file, they are used by the macro-generated code

use crate::context::{ReadContext, WriteContext};
use crate::ensure;
use crate::error::Error;
use crate::resolver::{TypeInfo, TypeResolver};
use crate::serializer::{ForyDefault, Serializer};
use crate::RefFlag;
use crate::RefMode;
use crate::TypeId;
use std::rc::Rc;

/// Helper macro for common type resolution and downcasting pattern
#[macro_export]
macro_rules! downcast_and_serialize {
    ($any_ref:expr, $context:expr, $trait_name:ident, $($impl_type:ty),+) => {{
        $(
            if $any_ref.type_id() == std::any::TypeId::of::<$impl_type>() {
                if let Some(concrete) = $any_ref.downcast_ref::<$impl_type>() {
                    concrete.fory_write_data($context)?;
                    return Ok(());
                }
            }
        )*
        return Err(fory_core::Error::type_error(format!("Failed to downcast to any registered type for trait {}", stringify!($trait_name))));
    }};
}

/// Macro to register trait object conversions for custom traits.
///
/// This macro automatically generates serializers for `Box<dyn Trait>` trait objects.
/// Due to Rust's orphan rules, only `Box<dyn Trait>` is supported for user-defined traits.
/// For `Rc<dyn Trait>` and `Arc<dyn Trait>`, wrapper types are generated (e.g., `TraitRc`, `TraitArc`),
/// either you use the wrapper types or use the `Rc<dyn Any>` or `Arc<dyn Any>` instead if it's not
/// inside struct fields. For struct fields, you can use the `Rc<dyn Trait>`, `Arc<dyn Trait>` directly,
/// fory will generate converters for `Rc<dyn Trait>` and `Arc<dyn Trait>` to convert to wrapper for
///
/// The macro generates:
/// - `Serializer` implementation for `Box<dyn Trait>`
/// - `Default` implementation for `Box<dyn Trait>` (uses first registered type)
///
/// **Note**: Your trait must extend the `Serializer` trait.
/// The `as_any()` method is automatically provided by the `Serializer` trait.
///
/// # Example
///
/// ```rust,ignore
/// use fory_core::{fory::Fory, register_trait_type, serializer::Serializer};
/// use fory_derive::{ForyEnum, ForyStruct, ForyUnion};
///
/// trait Animal: Serializer {
///     fn speak(&self) -> String;
///     fn name(&self) -> &str;
/// }
///
/// #[derive(ForyStruct, Debug)]
/// struct Dog { name: String }
///
/// #[derive(ForyStruct, Debug)]
/// struct Cat { name: String }
///
/// impl Animal for Dog {
///     fn speak(&self) -> String { "Woof!".to_string() }
///     fn name(&self) -> &str { &self.name }
/// }
///
/// impl Animal for Cat {
///     fn speak(&self) -> String { "Meow!".to_string() }
///     fn name(&self) -> &str { &self.name }
/// }
///
/// register_trait_type!(Animal, Dog, Cat);
///
/// # fn main() {
/// let mut fory = Fory::builder().xlang(false).compatible(true).build();
/// fory.register::<Dog>(100).unwrap();
/// fory.register::<Cat>(101).unwrap();
///
/// let dog: Box<dyn Animal> = Box::new(Dog { name: "Rex".to_string() });
/// let bytes = fory.serialize(&dog).unwrap();
/// let decoded: Box<dyn Animal> = fory.deserialize(&bytes).unwrap();
/// assert_eq!(decoded.name(), "Rex");
/// # }
/// ```
#[macro_export]
macro_rules! register_trait_type {
    ($trait_name:ident, $($impl_type:ty),+ $(,)?) => {
        // 1. Generate Box<dyn Trait> serializer (existing functionality)
        // ForyDefault implementation using first registered type
        impl $crate::serializer::ForyDefault for Box<dyn $trait_name> {
            fn fory_default() -> Self {
                Box::new(<register_trait_type!(@first_type $($impl_type),+) as $crate::serializer::ForyDefault>::fory_default())
            }
        }
        $crate::generate_box_trait_codec!($trait_name);

        // 2. Auto-generate Rc wrapper type and conversions
        $crate::generate_smart_pointer_wrapper!(
            std::rc::Rc,
            Rc,
            std::rc::Rc::get_mut,
            $trait_name,
            try_write_rc_ref,
            get_rc_ref,
            store_rc_ref,
            $($impl_type),+
        );
        $crate::generate_smart_pointer_codec!(std::rc::Rc, Rc, $trait_name);

        // 3. Auto-generate Arc wrapper type and conversions
        $crate::generate_smart_pointer_wrapper!(
            std::sync::Arc,
            Arc,
            std::sync::Arc::get_mut,
            $trait_name,
            try_write_arc_ref,
            get_arc_ref,
            store_arc_ref,
            $($impl_type),+
        );
        $crate::generate_smart_pointer_codec!(std::sync::Arc, Arc, $trait_name);

        // 4. Serializer implementation for Box<dyn Trait> (existing functionality)
        impl fory_core::Serializer for Box<dyn $trait_name> {
            #[inline(always)]
            fn fory_write(&self, context: &mut fory_core::WriteContext, ref_mode: fory_core::RefMode, write_type_info: bool, has_generics: bool) -> Result<(), fory_core::Error> {
                let any_ref = <dyn $trait_name as fory_core::Serializer>::as_any(&**self);
                fory_core::serializer::write_box_any(any_ref, context, ref_mode, write_type_info, has_generics)
            }

            #[inline(always)]
            fn fory_write_data(&self, context: &mut fory_core::WriteContext) -> Result<(), fory_core::Error> {
                let any_ref = <dyn $trait_name as fory_core::Serializer>::as_any(&**self);
                fory_core::serializer::write_box_any(any_ref, context, fory_core::RefMode::None, false, false)
            }

            #[inline(always)]
            fn fory_write_data_generic(&self, context: &mut fory_core::WriteContext, has_generics: bool) -> Result<(), fory_core::Error> {
                let any_ref = <dyn $trait_name as fory_core::Serializer>::as_any(&**self);
                fory_core::serializer::write_box_any(any_ref, context, fory_core::RefMode::None, false, has_generics)
            }

            #[inline(always)]
            fn fory_type_id_dyn(&self, type_resolver: &fory_core::resolver::TypeResolver) -> Result<fory_core::TypeId, fory_core::Error> {
                let any_ref = <dyn $trait_name as fory_core::Serializer>::as_any(&**self);
                let concrete_type_id = any_ref.type_id();
                type_resolver
                    .get_fory_type_id(concrete_type_id)
                    .ok_or_else(|| fory_core::Error::type_error("Type not registered for trait object"))
            }

            #[inline(always)]
            fn fory_is_polymorphic() -> bool {
                true
            }

            fn fory_write_type_info(_context: &mut fory_core::WriteContext) -> Result<(), fory_core::Error> {
                $crate::not_allowed!("fory_write_type_info should not be called directly on polymorphic Box<dyn {}> trait object", stringify!($trait_name))
            }

            fn fory_read_type_info(_context: &mut fory_core::ReadContext) -> Result<(), fory_core::Error> {
                $crate::not_allowed!("fory_read_type_info should not be called directly on polymorphic Box<dyn {}> trait object", stringify!($trait_name))
            }

            fn fory_read(context: &mut fory_core::ReadContext, ref_mode: fory_core::RefMode, read_type_info: bool) -> Result<Self, fory_core::Error> {
                let boxed_any = fory_core::serializer::read_box_any(context, ref_mode, read_type_info, None)?;
                $(
                    if boxed_any.is::<$impl_type>() {
                        let concrete = boxed_any.downcast::<$impl_type>()
                            .map_err(|_| fory_core::Error::type_error("Downcast failed"))?;
                        let ptr = Box::new(*concrete);
                        return Ok(Self::from(ptr));
                    }
                )*
                Err(fory_core::Error::type_error(
                    format!("Deserialized type does not implement trait {}", stringify!($trait_name))
                ))
            }

            fn fory_read_with_type_info(
                context: &mut fory_core::ReadContext,
                ref_mode: fory_core::RefMode,
                type_info: std::rc::Rc<fory_core::TypeInfo>,
            ) -> Result<Self, fory_core::Error>
            where
                Self: Sized + fory_core::ForyDefault,
            {
                let boxed_any = fory_core::serializer::read_box_any(context, ref_mode, false, Some(type_info))?;
                $(
                    if boxed_any.is::<$impl_type>() {
                        let concrete = boxed_any.downcast::<$impl_type>()
                            .map_err(|_| fory_core::Error::type_error("Downcast failed"))?;
                        let ptr = Box::new(*concrete);
                        return Ok(Self::from(ptr));
                    }
                )*
                Err(fory_core::Error::type_error(
                    format!("Deserialized type does not implement trait {}", stringify!($trait_name))
                ))
            }

            fn fory_read_data(_context: &mut fory_core::ReadContext) -> Result<Self, fory_core::Error> {
                // This should not be called for polymorphic types like Box<dyn Trait>
                // The fory_read method handles the polymorphic dispatch
                $crate::not_allowed!("fory_read_data should not be called directly on polymorphic Box<dyn {}> trait object", stringify!($trait_name))
            }

            fn fory_get_type_id(_type_resolver: &fory_core::resolver::TypeResolver) -> Result<fory_core::TypeId, fory_core::Error> {
                $crate::not_allowed!("fory_get_type_id should not be called directly on polymorphic Box<dyn {}> trait object", stringify!($trait_name))
            }

            #[inline(always)]
            fn fory_static_type_id() -> fory_core::TypeId {
                fory_core::TypeId::UNKNOWN
            }

            #[inline(always)]
            fn fory_reserved_space() -> usize {
                $crate::type_id::SIZE_OF_REF_AND_TYPE
            }

            #[inline(always)]
            fn fory_concrete_type_id(&self) -> std::any::TypeId {
                <dyn $trait_name as fory_core::Serializer>::as_any(&**self).type_id()
            }

            #[inline(always)]
            fn as_any(&self) -> &dyn std::any::Any {
                <dyn $trait_name as fory_core::Serializer>::as_any(&**self)
            }
        }
    };

    // Helper to get first type for Default impl
    (@first_type $first_type:ty $(, $rest:ty)*) => {
        $first_type
    };
}

/// Unified macro to generate smart pointer wrapper types for traits
/// Supports both Rc and Arc pointer types
#[macro_export]
macro_rules! generate_smart_pointer_wrapper {
    ($ptr_path:path, $ptr_name:ident, $get_mut:path, $trait_name:ident, $try_write_ref:ident, $get_ref:ident, $store_ref:ident, $($impl_type:ty),+ $(,)?) => {
        $crate::paste::paste! {
            #[derive(Clone)]
            pub(crate) struct [<$trait_name $ptr_name>]($ptr_path<dyn $trait_name>);

            impl [<$trait_name $ptr_name>] {
                pub(crate) fn new(inner: $ptr_path<dyn $trait_name>) -> Self {
                    Self(inner)
                }

                pub(crate) fn into_inner(self) -> $ptr_path<dyn $trait_name> {
                    self.0
                }

                pub(crate) fn unwrap(self) -> $ptr_path<dyn $trait_name> {
                    self.0
                }

                pub(crate) fn as_ref(&self) -> &dyn $trait_name {
                    &*self.0
                }
            }

            impl std::ops::Deref for [<$trait_name $ptr_name>] {
                type Target = dyn $trait_name;

                fn deref(&self) -> &Self::Target {
                    &*self.0
                }
            }

            impl std::ops::DerefMut for [<$trait_name $ptr_name>] {
                fn deref_mut(&mut self) -> &mut Self::Target {
                    $get_mut(&mut self.0)
                        .expect(&format!("Cannot get mutable reference to {} with multiple strong references", stringify!($ptr_name)))
                }
            }

            impl From<$ptr_path<dyn $trait_name>> for [<$trait_name $ptr_name>] {
                fn from(ptr: $ptr_path<dyn $trait_name>) -> Self {
                    Self::new(ptr)
                }
            }

            impl From<[<$trait_name $ptr_name>]> for $ptr_path<dyn $trait_name> {
                fn from(wrapper: [<$trait_name $ptr_name>]) -> Self {
                    wrapper.into_inner()
                }
            }

            impl $crate::serializer::ForyDefault for [<$trait_name $ptr_name>] {
                fn fory_default() -> Self {
                    Self($ptr_path::new(<$crate::register_trait_type!(@first_type $($impl_type),+) as $crate::serializer::ForyDefault>::fory_default()))
                }
            }

            impl std::fmt::Debug for [<$trait_name $ptr_name>] {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    let any_obj = <dyn $trait_name as fory_core::Serializer>::as_any(&*self.0);
                    $(
                        if let Some(concrete) = any_obj.downcast_ref::<$impl_type>() {
                            return write!(f, concat!(stringify!($trait_name), stringify!($ptr_name), "({:?})"), concrete);
                        }
                    )*
                    write!(f, concat!(stringify!($trait_name), stringify!($ptr_name), "({:p})"), &*self.0)
                }
            }

            $crate::impl_smart_pointer_serializer!(
                [<$trait_name $ptr_name>],
                $ptr_path<dyn $trait_name>,
                $ptr_path::new,
                $trait_name,
                $try_write_ref,
                $get_ref,
                $store_ref,
                $($impl_type),+
            );
        }
    };
}

#[macro_export]
macro_rules! generate_smart_pointer_codec {
    ($ptr_path:path, $ptr_name:ident, $trait_name:ident) => {
        $crate::paste::paste! {
            pub(crate) struct [<$trait_name $ptr_name Codec>]<const NULLABLE: bool, const TRACK_REF: bool>;

            impl<const NULLABLE: bool, const TRACK_REF: bool>
                fory_core::serializer::codec::Codec<$ptr_path<dyn $trait_name>>
                for [<$trait_name $ptr_name Codec>]<NULLABLE, TRACK_REF>
            {
                #[inline(always)]
                fn field_type(
                    _type_resolver: &fory_core::resolver::TypeResolver,
                ) -> Result<fory_core::meta::FieldType, fory_core::Error> {
                    Ok(fory_core::meta::FieldType::new_with_ref(
                        fory_core::type_id::TypeId::UNKNOWN as u32,
                        NULLABLE,
                        TRACK_REF,
                        Vec::new(),
                    ))
                }

                #[inline(always)]
                fn reserved_space() -> usize {
                    <[<$trait_name $ptr_name>] as fory_core::Serializer>::fory_reserved_space()
                        + fory_core::type_id::SIZE_OF_REF_AND_TYPE
                }

                #[inline(always)]
                fn write_field(
                    value: &$ptr_path<dyn $trait_name>,
                    context: &mut fory_core::WriteContext,
                ) -> Result<(), fory_core::Error> {
                    let wrapper = [<$trait_name $ptr_name>]::from(value.clone());
                    <[<$trait_name $ptr_name>] as fory_core::Serializer>::fory_write(
                        &wrapper,
                        context,
                        if TRACK_REF {
                            fory_core::RefMode::Tracking
                        } else if NULLABLE {
                            fory_core::RefMode::NullOnly
                        } else {
                            fory_core::RefMode::None
                        },
                        true,
                        false,
                    )
                }

                #[inline(always)]
                fn read_field(
                    context: &mut fory_core::ReadContext,
                ) -> Result<$ptr_path<dyn $trait_name>, fory_core::Error> {
                    Self::read_with_mode(
                        context,
                        if TRACK_REF {
                            fory_core::RefMode::Tracking
                        } else if NULLABLE {
                            fory_core::RefMode::NullOnly
                        } else {
                            fory_core::RefMode::None
                        },
                        true,
                    )
                }

                #[inline(always)]
                fn write_data(
                    value: &$ptr_path<dyn $trait_name>,
                    context: &mut fory_core::WriteContext,
                ) -> Result<(), fory_core::Error> {
                    let wrapper = [<$trait_name $ptr_name>]::from(value.clone());
                    <[<$trait_name $ptr_name>] as fory_core::Serializer>::fory_write_data(
                        &wrapper,
                        context,
                    )
                }

                #[inline(always)]
                fn read_data(
                    context: &mut fory_core::ReadContext,
                ) -> Result<$ptr_path<dyn $trait_name>, fory_core::Error> {
                    Self::read_with_mode(context, fory_core::RefMode::None, true)
                }

                #[inline(always)]
                fn read_field_with_type(
                    context: &mut fory_core::ReadContext,
                    remote_field_type: &fory_core::meta::FieldType,
                ) -> Result<$ptr_path<dyn $trait_name>, fory_core::Error> {
                    Self::read_with_mode(
                        context,
                        fory_core::serializer::codec::field_ref_mode(remote_field_type),
                        true,
                    )
                }

                #[inline(always)]
                fn write_with_mode(
                    value: &$ptr_path<dyn $trait_name>,
                    context: &mut fory_core::WriteContext,
                    ref_mode: fory_core::RefMode,
                    write_type_info: bool,
                    has_generics: bool,
                ) -> Result<(), fory_core::Error> {
                    let wrapper = [<$trait_name $ptr_name>]::from(value.clone());
                    <[<$trait_name $ptr_name>] as fory_core::Serializer>::fory_write(
                        &wrapper,
                        context,
                        ref_mode,
                        write_type_info,
                        has_generics,
                    )
                }

                #[inline(always)]
                fn read_with_mode(
                    context: &mut fory_core::ReadContext,
                    ref_mode: fory_core::RefMode,
                    read_type_info: bool,
                ) -> Result<$ptr_path<dyn $trait_name>, fory_core::Error> {
                    let wrapper = <[<$trait_name $ptr_name>] as fory_core::Serializer>::fory_read(
                        context,
                        ref_mode,
                        read_type_info,
                    )?;
                    Ok($ptr_path::<dyn $trait_name>::from(wrapper))
                }

                #[inline(always)]
                fn read_with_type_info(
                    context: &mut fory_core::ReadContext,
                    ref_mode: fory_core::RefMode,
                    type_info: std::rc::Rc<fory_core::TypeInfo>,
                ) -> Result<$ptr_path<dyn $trait_name>, fory_core::Error> {
                    let wrapper =
                        <[<$trait_name $ptr_name>] as fory_core::Serializer>::fory_read_with_type_info(
                            context,
                            ref_mode,
                            type_info,
                        )?;
                    Ok($ptr_path::<dyn $trait_name>::from(wrapper))
                }

                #[inline(always)]
                fn default_value() -> $ptr_path<dyn $trait_name> {
                    $ptr_path::<dyn $trait_name>::from(
                        <[<$trait_name $ptr_name>] as fory_core::ForyDefault>::fory_default(),
                    )
                }

                #[inline(always)]
                fn write_type_info(_context: &mut fory_core::WriteContext) -> Result<(), fory_core::Error> {
                    Ok(())
                }

                #[inline(always)]
                fn read_type_info(_context: &mut fory_core::ReadContext) -> Result<(), fory_core::Error> {
                    Ok(())
                }

                #[inline(always)]
                fn static_type_id() -> fory_core::TypeId {
                    fory_core::TypeId::UNKNOWN
                }

                #[inline(always)]
                fn is_polymorphic() -> bool {
                    true
                }

                #[inline(always)]
                fn is_shared_ref() -> bool {
                    true
                }

                #[inline(always)]
                fn concrete_type_id(value: &$ptr_path<dyn $trait_name>) -> std::any::TypeId {
                    <dyn $trait_name as fory_core::Serializer>::as_any(&**value).type_id()
                }
            }
        }
    };
}

#[macro_export]
macro_rules! generate_box_trait_codec {
    ($trait_name:ident) => {
        $crate::paste::paste! {
            pub(crate) struct [<$trait_name BoxCodec>]<const NULLABLE: bool, const TRACK_REF: bool>;

            impl<const NULLABLE: bool, const TRACK_REF: bool>
                fory_core::serializer::codec::Codec<Box<dyn $trait_name>>
                for [<$trait_name BoxCodec>]<NULLABLE, TRACK_REF>
            {
                #[inline(always)]
                fn field_type(
                    _type_resolver: &fory_core::resolver::TypeResolver,
                ) -> Result<fory_core::meta::FieldType, fory_core::Error> {
                    Ok(fory_core::meta::FieldType::new_with_ref(
                        fory_core::type_id::TypeId::UNKNOWN as u32,
                        NULLABLE,
                        TRACK_REF,
                        Vec::new(),
                    ))
                }

                #[inline(always)]
                fn reserved_space() -> usize {
                    <Box<dyn $trait_name> as fory_core::Serializer>::fory_reserved_space()
                        + fory_core::type_id::SIZE_OF_REF_AND_TYPE
                }

                #[inline(always)]
                fn write_field(
                    value: &Box<dyn $trait_name>,
                    context: &mut fory_core::WriteContext,
                ) -> Result<(), fory_core::Error> {
                    <Box<dyn $trait_name> as fory_core::Serializer>::fory_write(
                        value,
                        context,
                        if TRACK_REF {
                            fory_core::RefMode::Tracking
                        } else if NULLABLE {
                            fory_core::RefMode::NullOnly
                        } else {
                            fory_core::RefMode::None
                        },
                        true,
                        false,
                    )
                }

                #[inline(always)]
                fn read_field(
                    context: &mut fory_core::ReadContext,
                ) -> Result<Box<dyn $trait_name>, fory_core::Error> {
                    Self::read_with_mode(
                        context,
                        if TRACK_REF {
                            fory_core::RefMode::Tracking
                        } else if NULLABLE {
                            fory_core::RefMode::NullOnly
                        } else {
                            fory_core::RefMode::None
                        },
                        true,
                    )
                }

                #[inline(always)]
                fn write_data(
                    value: &Box<dyn $trait_name>,
                    context: &mut fory_core::WriteContext,
                ) -> Result<(), fory_core::Error> {
                    <Box<dyn $trait_name> as fory_core::Serializer>::fory_write_data(
                        value,
                        context,
                    )
                }

                #[inline(always)]
                fn read_data(
                    context: &mut fory_core::ReadContext,
                ) -> Result<Box<dyn $trait_name>, fory_core::Error> {
                    Self::read_with_mode(context, fory_core::RefMode::None, true)
                }

                #[inline(always)]
                fn read_field_with_type(
                    context: &mut fory_core::ReadContext,
                    remote_field_type: &fory_core::meta::FieldType,
                ) -> Result<Box<dyn $trait_name>, fory_core::Error> {
                    Self::read_with_mode(
                        context,
                        fory_core::serializer::codec::field_ref_mode(remote_field_type),
                        true,
                    )
                }

                #[inline(always)]
                fn write_with_mode(
                    value: &Box<dyn $trait_name>,
                    context: &mut fory_core::WriteContext,
                    ref_mode: fory_core::RefMode,
                    write_type_info: bool,
                    has_generics: bool,
                ) -> Result<(), fory_core::Error> {
                    <Box<dyn $trait_name> as fory_core::Serializer>::fory_write(
                        value,
                        context,
                        ref_mode,
                        write_type_info,
                        has_generics,
                    )
                }

                #[inline(always)]
                fn read_with_mode(
                    context: &mut fory_core::ReadContext,
                    ref_mode: fory_core::RefMode,
                    read_type_info: bool,
                ) -> Result<Box<dyn $trait_name>, fory_core::Error> {
                    <Box<dyn $trait_name> as fory_core::Serializer>::fory_read(
                        context,
                        ref_mode,
                        read_type_info,
                    )
                }

                #[inline(always)]
                fn read_with_type_info(
                    context: &mut fory_core::ReadContext,
                    ref_mode: fory_core::RefMode,
                    type_info: std::rc::Rc<fory_core::TypeInfo>,
                ) -> Result<Box<dyn $trait_name>, fory_core::Error> {
                    <Box<dyn $trait_name> as fory_core::Serializer>::fory_read_with_type_info(
                        context,
                        ref_mode,
                        type_info,
                    )
                }

                #[inline(always)]
                fn default_value() -> Box<dyn $trait_name> {
                    <Box<dyn $trait_name> as fory_core::ForyDefault>::fory_default()
                }

                #[inline(always)]
                fn write_type_info(_context: &mut fory_core::WriteContext) -> Result<(), fory_core::Error> {
                    Ok(())
                }

                #[inline(always)]
                fn read_type_info(_context: &mut fory_core::ReadContext) -> Result<(), fory_core::Error> {
                    Ok(())
                }

                #[inline(always)]
                fn static_type_id() -> fory_core::TypeId {
                    fory_core::TypeId::UNKNOWN
                }

                #[inline(always)]
                fn is_polymorphic() -> bool {
                    true
                }

                #[inline(always)]
                fn concrete_type_id(value: &Box<dyn $trait_name>) -> std::any::TypeId {
                    <dyn $trait_name as fory_core::Serializer>::as_any(&**value).type_id()
                }
            }
        }
    };
}

/// Macro to read smart pointer trait objects (`Rc<dyn Trait>,` `Arc<dyn Trait>`)
/// This macro handles ref tracking and directly constructs the trait object from concrete types
#[macro_export]
macro_rules! read_ptr_trait_object {
    ($context:expr, $ref_mode:expr, $read_type_info:expr, $type_info:expr, $pointer_type:ty, $trait_name:ident, $constructor_expr:expr, $get_ref:ident, $store_ref:ident, $($impl_type:ty),+) => {{
        let ref_flag = if $ref_mode != fory_core::RefMode::None {
            $context.ref_reader.read_ref_flag(&mut $context.reader)?
        } else {
            fory_core::RefFlag::NotNullValue
        };
        match ref_flag {
            fory_core::RefFlag::Null => Err(fory_core::Error::invalid_ref(format!("smart pointer to dyn {} cannot be null", stringify!($trait_name)))),
            fory_core::RefFlag::Ref => {
                let ref_id = $context.ref_reader.read_ref_id(&mut $context.reader)?;
                let ptr_ref = $context.ref_reader.$get_ref::<dyn $trait_name>(ref_id)
                    .ok_or_else(|| fory_core::Error::invalid_data(format!("dyn {} reference {} not found", stringify!($trait_name), ref_id)))?;
                Ok(Self::from(ptr_ref))
            }
            fory_core::RefFlag::NotNullValue => {
                $context.inc_depth()?;
                let typeinfo = if $read_type_info {
                    $context.read_any_type_info()?
                } else {
                    $type_info.ok_or_else(|| fory_core::Error::type_error("No type info found for read"))?
                };
                let fory_type_id = typeinfo.get_type_id();
                let user_type_id = typeinfo.get_user_type_id();
                let registered_by_name = typeinfo.is_registered_by_name();
                let namespace = typeinfo.get_namespace();
                let type_name = typeinfo.get_type_name();
                let matches_type = |local_info: &fory_core::TypeInfo| -> bool {
                    if registered_by_name {
                        local_info.is_registered_by_name()
                            && local_info.get_namespace().original == namespace.original
                            && local_info.get_type_name().original == type_name.original
                    } else if user_type_id != u32::MAX {
                        local_info.get_user_type_id() == user_type_id
                    } else {
                        local_info.get_type_id() == fory_type_id
                    }
                };
                $(
                    if let Ok(local_info) = $context.get_type_resolver().get_type_info(&std::any::TypeId::of::<$impl_type>()) {
                        if matches_type(&local_info) {
                            let concrete_obj = <$impl_type as fory_core::Serializer>::fory_read_data($context)?;
                            $context.dec_depth();
                            let ptr = $constructor_expr(concrete_obj) as $pointer_type;
                            return Ok(Self::from(ptr));
                        }
                    }
                )*
                $context.dec_depth();
                Err(fory_core::Error::type_error(format!(
                    "Type ID {} not registered for trait {}",
                    fory_type_id as u32,
                    stringify!($trait_name)
                )))
            }
            fory_core::RefFlag::RefValue => {
                $context.inc_depth()?;
                let typeinfo = if $read_type_info {
                    $context.read_any_type_info()?
                } else {
                    $type_info.ok_or_else(|| fory_core::Error::type_error("No type info found for read"))?
                };
                let fory_type_id = typeinfo.get_type_id();
                let user_type_id = typeinfo.get_user_type_id();
                let registered_by_name = typeinfo.is_registered_by_name();
                let namespace = typeinfo.get_namespace();
                let type_name = typeinfo.get_type_name();
                let matches_type = |local_info: &fory_core::TypeInfo| -> bool {
                    if registered_by_name {
                        local_info.is_registered_by_name()
                            && local_info.get_namespace().original == namespace.original
                            && local_info.get_type_name().original == type_name.original
                    } else if user_type_id != u32::MAX {
                        local_info.get_user_type_id() == user_type_id
                    } else {
                        local_info.get_type_id() == fory_type_id
                    }
                };
                $(
                    if let Ok(local_info) = $context.get_type_resolver().get_type_info(&std::any::TypeId::of::<$impl_type>()) {
                        if matches_type(&local_info) {
                            let concrete_obj = <$impl_type as fory_core::Serializer>::fory_read_data($context)?;
                            $context.dec_depth();
                            let ptr = $constructor_expr(concrete_obj) as $pointer_type;
                            let wrapper = Self::from(ptr.clone());
                            $context.ref_reader.$store_ref(ptr);
                            return Ok(wrapper);
                        }
                    }
                )*
                $context.dec_depth();
                Err(fory_core::Error::type_error(format!(
                    "Type ID {} not registered for trait {}",
                    fory_type_id as u32,
                    stringify!($trait_name)
                )))
            }
        }
    }};
}

/// Shared serializer implementation for smart pointer wrappers
#[macro_export]
macro_rules! impl_smart_pointer_serializer {
    ($wrapper_name:ident, $pointer_type:ty, $constructor_expr:expr, $trait_name:ident, $try_write_ref:ident, $get_ref:ident, $store_ref:ident, $($impl_type:ty),+) => {
        impl fory_core::Serializer for $wrapper_name {
            fn fory_write(&self, context: &mut fory_core::WriteContext, ref_mode: fory_core::RefMode, write_type_info: bool, has_generics: bool) -> Result<(), fory_core::Error> {
                if ref_mode == fory_core::RefMode::None || !context.ref_writer.$try_write_ref(&mut context.writer, &self.0) {
                    let any_obj = <dyn $trait_name as fory_core::Serializer>::as_any(&*self.0);
                    let concrete_type_id = any_obj.type_id();
                    let typeinfo = if write_type_info {
                         context.write_any_type_info(fory_core::TypeId::UNKNOWN as u32, concrete_type_id)?
                    } else {
                        context.get_type_info(&concrete_type_id)?
                    };
                    let serializer_fn = typeinfo.get_harness().get_write_data_fn();
                    serializer_fn(any_obj, context, has_generics)?;
                }
                Ok(())
            }

            fn fory_write_data(&self, context: &mut fory_core::WriteContext) -> Result<(), fory_core::Error> {
                let any_obj = <dyn $trait_name as fory_core::Serializer>::as_any(&*self.0);
                $crate::downcast_and_serialize!(any_obj, context, $trait_name, $($impl_type),+)
            }

            fn fory_read(context: &mut fory_core::ReadContext, ref_mode: fory_core::RefMode, read_type_info: bool) -> Result<Self, fory_core::Error> {
                $crate::read_ptr_trait_object!(
                    context,
                    ref_mode,
                    read_type_info,
                    None,
                    $pointer_type,
                    $trait_name,
                    $constructor_expr,
                    $get_ref,
                    $store_ref,
                    $($impl_type),+
                )
            }

            fn fory_read_with_type_info(context: &mut fory_core::ReadContext, ref_mode: fory_core::RefMode, type_info: std::rc::Rc<fory_core::TypeInfo>) -> Result<Self, fory_core::Error> {
                $crate::read_ptr_trait_object!(
                    context,
                    ref_mode,
                    false,
                    Some(type_info),
                    $pointer_type,
                    $trait_name,
                    $constructor_expr,
                    $get_ref,
                    $store_ref,
                    $($impl_type),+
                )
            }

            fn fory_read_data(context: &mut fory_core::ReadContext) -> Result<Self, fory_core::Error> {
                $crate::not_allowed!("fory_read_data should not be called directly on polymorphic {}<dyn {}> trait object", stringify!($ptr_path), stringify!($trait_name))
            }

            #[inline(always)]
            fn fory_get_type_id(_type_resolver: &fory_core::resolver::TypeResolver) -> Result<fory_core::TypeId, fory_core::Error> {
                Ok(fory_core::TypeId::STRUCT)
            }

            #[inline(always)]
            fn fory_static_type_id() -> fory_core::TypeId {
                fory_core::TypeId::UNKNOWN
            }

            #[inline(always)]
            fn fory_write_type_info(_context: &mut fory_core::WriteContext) -> Result<(), fory_core::Error> {
                Ok(())
            }

            #[inline(always)]
            fn fory_read_type_info(_context: &mut fory_core::ReadContext) -> Result<(), fory_core::Error>  {
                Ok(())
            }

            #[inline(always)]
            fn fory_is_polymorphic() -> bool {
                true
            }

            #[inline(always)]
            fn fory_is_shared_ref() -> bool {
                true
            }

            #[inline(always)]
            fn fory_type_id_dyn(&self, type_resolver: &fory_core::resolver::TypeResolver) -> Result<fory_core::TypeId, fory_core::Error> {
                let any_obj = <dyn $trait_name as fory_core::Serializer>::as_any(&*self.0);
                let concrete_type_id = any_obj.type_id();
                type_resolver
                    .get_fory_type_id(concrete_type_id)
                    .ok_or_else(|| fory_core::Error::type_error("Type not registered for trait object"))
            }

            #[inline(always)]
            fn fory_concrete_type_id(&self) -> std::any::TypeId {
                <dyn $trait_name as fory_core::Serializer>::as_any(&*self.0).type_id()
            }

            #[inline(always)]
            fn as_any(&self) -> &dyn std::any::Any {
                <dyn $trait_name as fory_core::Serializer>::as_any(&*self.0)
            }
        }
    };
}

/// Helper macros for automatic conversions in derive code
/// These are used by fory-derive to generate transparent conversions
///
/// Convert field of type `Rc<dyn Trait>` to wrapper for serialization
#[macro_export]
macro_rules! wrap_rc {
    ($field:expr, $trait_name:ident) => {
        $crate::paste::paste! {
            [<$trait_name Rc>]::from($field)
        }
    };
}

/// Convert wrapper back to `Rc<dyn Trait>` for deserialization
#[macro_export]
macro_rules! unwrap_rc {
    ($wrapper:expr, $trait_name:ident) => {
        std::rc::Rc::<dyn $trait_name>::from($wrapper)
    };
}

/// Convert `Arc<dyn Trait>` to wrapper for serialization
#[macro_export]
macro_rules! wrap_arc {
    ($field:expr, $trait_name:ident) => {
        $crate::paste::paste! {
            [<$trait_name Arc>]::from($field)
        }
    };
}

/// Convert `Vec<Rc<dyn Trait>>` to `Vec<wrapper>` for serialization
#[macro_export]
macro_rules! wrap_vec_rc {
    ($vec:expr, $trait_name:ident) => {
        $crate::paste::paste! {
            $vec.into_iter().map(|item| [<$trait_name Rc>]::from(item)).collect()
        }
    };
}

impl Default for Box<dyn Serializer> {
    fn default() -> Self {
        Box::new(0)
    }
}

impl ForyDefault for Box<dyn Serializer> {
    fn fory_default() -> Self {
        Box::new(0)
    }
}

impl Serializer for Box<dyn Serializer> {
    #[inline(always)]
    fn fory_concrete_type_id(&self) -> std::any::TypeId {
        (**self).fory_concrete_type_id()
    }

    fn fory_write(
        &self,
        context: &mut WriteContext,
        ref_mode: RefMode,
        write_type_info: bool,
        has_generics: bool,
    ) -> Result<(), Error> {
        if ref_mode != RefMode::None {
            context.writer.write_i8(RefFlag::NotNullValue as i8);
        }
        let fory_type_id_dyn = self.fory_type_id_dyn(context.get_type_resolver())?;
        let concrete_type_id = (**self).fory_concrete_type_id();
        if write_type_info {
            context.write_any_type_info(fory_type_id_dyn as u32, concrete_type_id)?;
        };
        self.fory_write_data_generic(context, has_generics)
    }

    #[inline(always)]
    fn fory_write_data(&self, context: &mut WriteContext) -> Result<(), Error> {
        self.fory_write_data_generic(context, false)
    }

    #[inline(always)]
    fn fory_write_data_generic(
        &self,
        context: &mut WriteContext,
        has_generics: bool,
    ) -> Result<(), Error> {
        (**self).fory_write_data_generic(context, has_generics)
    }

    #[inline(always)]
    fn fory_type_id_dyn(&self, type_resolver: &TypeResolver) -> Result<TypeId, Error> {
        (**self).fory_type_id_dyn(type_resolver)
    }

    #[inline(always)]
    fn as_any(&self) -> &dyn std::any::Any {
        (**self).as_any()
    }

    #[inline(always)]
    fn fory_is_polymorphic() -> bool {
        true
    }

    fn fory_write_type_info(_context: &mut WriteContext) -> Result<(), Error> {
        Err(Error::not_allowed(
            "Box<dyn Serializer> is polymorphic - can's write type info statically",
        ))
    }

    #[inline(always)]
    fn fory_read_type_info(context: &mut ReadContext) -> Result<(), Error> {
        context.read_any_type_info()?;
        Ok(())
    }

    #[inline(always)]
    fn fory_read(
        context: &mut ReadContext,
        ref_mode: RefMode,
        read_type_info: bool,
    ) -> Result<Self, Error> {
        read_box_seralizer(context, ref_mode, read_type_info, None)
    }

    #[inline(always)]
    fn fory_read_with_type_info(
        context: &mut ReadContext,
        ref_mode: RefMode,
        type_info: Rc<TypeInfo>,
    ) -> Result<Self, Error>
    where
        Self: Sized + ForyDefault,
    {
        read_box_seralizer(context, ref_mode, false, Some(type_info))
    }

    fn fory_read_data(_context: &mut ReadContext) -> Result<Self, Error> {
        Err(Error::not_allowed(
            "fory_read_data should not be called directly on Box<dyn Serializer>",
        ))
    }
}

fn read_box_seralizer(
    context: &mut ReadContext,
    ref_mode: RefMode,
    read_type_info: bool,
    type_info: Option<Rc<TypeInfo>>,
) -> Result<Box<dyn Serializer>, Error> {
    context.inc_depth()?;
    let ref_flag = if ref_mode != RefMode::None {
        context.reader.read_i8()?
    } else {
        RefFlag::NotNullValue as i8
    };
    if ref_flag != RefFlag::NotNullValue as i8 {
        return Err(Error::invalid_data(
            "Expected NotNullValue for Box<dyn Serializer>",
        ));
    }
    let typeinfo = if let Some(type_info) = type_info {
        type_info
    } else {
        ensure!(
            read_type_info,
            Error::invalid_data("Type info must be read for Box<dyn Serializer>")
        );
        context.read_any_type_info()?
    };
    let harness = typeinfo.get_harness();
    let boxed_any = harness.get_read_data_fn()(context)?;
    let trait_object = harness.get_to_serializer()(boxed_any)?;
    context.dec_depth();
    Ok(trait_object)
}