multiio 0.2.3

A unified I/O orchestration library for CLI/server applications
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
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
//! Format abstraction for serialization and deserialization.
//!
//! This module provides:
//! - `FormatKind`: Enum representing different data formats
//! - `FormatError`: Errors that can occur during format operations
//! - `FormatRegistry`: Registry managing formats by kind
//! - `CustomFormat`: Support for user-defined custom formats

use std::io::Read;

use paste::paste;

#[cfg(feature = "custom")]
mod custom;
#[cfg(feature = "custom")]
pub use custom::CustomFormat;

// Per-format implementations
#[cfg(feature = "csv")]
mod csv;
#[cfg(feature = "ini")]
mod ini;
#[cfg(feature = "json")]
mod json;
#[cfg(feature = "plaintext")]
mod plaintext;
#[cfg(feature = "toml")]
mod toml;
#[cfg(feature = "xml")]
mod xml;
#[cfg(feature = "yaml")]
mod yaml;

use serde::{Serialize, de::DeserializeOwned};
use thiserror::Error;

/// Define `FormatKind` and the central `format_spec!` from a single source.
///
/// Syntax:
/// ```rust,ignore
/// define_formats!(
///     #[derive(...)]
///     pub enum FormatKind {
///         // Compact builtin form: aliases are also used as extensions.
///         Json => (Structured, json,   "json",     ["json"]),
///         Compact:(Category,   module, canonical, [aliases])`
///                  - feature = canonical
///                  - display = canonical
///                  - extensions = aliases
///
///         // Full builtin form: extensions and aliases can differ.
///         Plaintext => (Other,    plaintext, "plaintext", ["txt", "text"], ["plaintext", "text", "txt"]),
///         Full:    `=> (Category, module,    canonical,   [extensions],    [aliases])`
///
///         /// Custom format with a unique name
///         Custom(&'static str),
///     }
/// );
/// ```
///
/// Builtin variants use:
/// - Compact: `=> (Category, module, canonical, [aliases])`
///     - feature = canonical
///     - display = canonical
///     - extensions = aliases
/// - Full: `=> (Category, module, canonical, [extensions], [aliases])`
///
/// Variants without `=>` are excluded from `format_spec!` (e.g. `Custom`).
macro_rules! define_formats {
    (
        $(#[$enum_meta:meta])*
        $vis:vis enum $name:ident {
            $($body:tt)*
        }
    ) => {
        define_formats!(@parse
            [$($enum_meta)*]
            $vis
            $name
            []
            []
            $($body)*
        );
    };

    // Finish parsing and emit items.
    (@parse
        [$($enum_meta:meta)*]
        $vis:vis
        $name:ident
        [$($enum_variants:tt)*]
        [$($spec_entries:tt)*]
    ) => {
        define_formats!(@emit
            [$($enum_meta)*]
            $vis
            $name
            [$($enum_variants)*]
            [$($spec_entries)*]
            $
        );
    };

    // Emit the enum and the inner `format_spec!` macro on stable Rust.
    (@emit
        [$($enum_meta:meta)*]
        $vis:vis
        $name:ident
        [$($enum_variants:tt)*]
        [$($spec_entries:tt)*]
        $d:tt
    ) => {
        $(#[$enum_meta])*
        $vis enum $name {
            $($enum_variants)*
        }

        impl Copy for $name {}

        /// Central spec for all builtin (non-custom) formats.
        ///
        /// Fields: (Category, Variant, feature, module, display, extensions, aliases)
        macro_rules! format_spec {
            // Allow passing extra arguments through to the projection macro.
            ($d mac:ident ( $d($d args:tt)* )) => {
                $d mac! {
                    $d($d args)*
                    $($spec_entries)*
                }
            };

            ($d mac:ident) => {
                $d mac! {
                    $($spec_entries)*
                }
            };
        }
    };

    // Builtin unit variant with explicit extensions and aliases, followed by more tokens.
    (@parse
        [$($enum_meta:meta)*]
        $vis:vis
        $name:ident
        [$($enum_variants:tt)*]
        [$($spec_entries:tt)*]
        $(#[$var_meta:meta])*
        $variant:ident => (
            $cat:ident,
            $module:ident,
            $canonical:literal,
            [$($ext:literal),* $(,)?],
            [$($alias:literal),* $(,)?]
        )
        , $($tail:tt)*
    ) => {
        define_formats!(@parse
            [$($enum_meta)*]
            $vis
            $name
            [
                $($enum_variants)*
                $(#[$var_meta])*
                $variant,
            ]
            [
                $($spec_entries)*
                ($cat, $variant, $canonical, $module, $canonical, [$($ext),*], [$($alias),*])
            ]
            $($tail)*
        );
    };

    // Builtin unit variant with explicit extensions and aliases, last (no trailing comma).
    (@parse
        [$($enum_meta:meta)*]
        $vis:vis
        $name:ident
        [$($enum_variants:tt)*]
        [$($spec_entries:tt)*]
        $(#[$var_meta:meta])*
        $variant:ident => (
            $cat:ident,
            $module:ident,
            $canonical:literal,
            [$($ext:literal),* $(,)?],
            [$($alias:literal),* $(,)?]
        )
    ) => {
        define_formats!(@parse
            [$($enum_meta)*]
            $vis
            $name
            [
                $($enum_variants)*
                $(#[$var_meta])*
                $variant,
            ]
            [
                $($spec_entries)*
                ($cat, $variant, $canonical, $module, $canonical, [$($ext),*], [$($alias),*])
            ]
        );
    };

    // Builtin unit variant where aliases are also used as extensions, followed by more tokens.
    (@parse
        [$($enum_meta:meta)*]
        $vis:vis
        $name:ident
        [$($enum_variants:tt)*]
        [$($spec_entries:tt)*]
        $(#[$var_meta:meta])*
        $variant:ident => (
            $cat:ident,
            $module:ident,
            $canonical:literal,
            [$($alias:literal),* $(,)?]
        )
        , $($tail:tt)*
    ) => {
        define_formats!(@parse
            [$($enum_meta)*]
            $vis
            $name
            [
                $($enum_variants)*
                $(#[$var_meta])*
                $variant,
            ]
            [
                $($spec_entries)*
                ($cat, $variant, $canonical, $module, $canonical, [$($alias),*], [$($alias),*])
            ]
            $($tail)*
        );
    };

    // Builtin unit variant where aliases are also used as extensions, last (no trailing comma).
    (@parse
        [$($enum_meta:meta)*]
        $vis:vis
        $name:ident
        [$($enum_variants:tt)*]
        [$($spec_entries:tt)*]
        $(#[$var_meta:meta])*
        $variant:ident => (
            $cat:ident,
            $module:ident,
            $canonical:literal,
            [$($alias:literal),* $(,)?]
        )
    ) => {
        define_formats!(@parse
            [$($enum_meta)*]
            $vis
            $name
            [
                $($enum_variants)*
                $(#[$var_meta])*
                $variant,
            ]
            [
                $($spec_entries)*
                ($cat, $variant, $canonical, $module, $canonical, [$($alias),*], [$($alias),*])
            ]
        );
    };

    // Legacy builtin syntax: (Category, feature, module, display, [extensions], [aliases])
    (@parse
        [$($enum_meta:meta)*]
        $vis:vis
        $name:ident
        [$($enum_variants:tt)*]
        [$($spec_entries:tt)*]
        $(#[$var_meta:meta])*
        $variant:ident => (
            $cat:ident,
            $feat:literal,
            $module:ident,
            $display:literal,
            [$($ext:literal),* $(,)?],
            [$($alias:literal),* $(,)?]
        )
        , $($tail:tt)*
    ) => {
        define_formats!(@parse
            [$($enum_meta)*]
            $vis
            $name
            [
                $($enum_variants)*
                $(#[$var_meta])*
                $variant,
            ]
            [
                $($spec_entries)*
                ($cat, $variant, $feat, $module, $display, [$($ext),*], [$($alias),*])
            ]
            $($tail)*
        );
    };

    // Legacy builtin syntax, last (no trailing comma).
    (@parse
        [$($enum_meta:meta)*]
        $vis:vis
        $name:ident
        [$($enum_variants:tt)*]
        [$($spec_entries:tt)*]
        $(#[$var_meta:meta])*
        $variant:ident => (
            $cat:ident,
            $feat:literal,
            $module:ident,
            $display:literal,
            [$($ext:literal),* $(,)?],
            [$($alias:literal),* $(,)?]
        )
    ) => {
        define_formats!(@parse
            [$($enum_meta)*]
            $vis
            $name
            [
                $($enum_variants)*
                $(#[$var_meta])*
                $variant,
            ]
            [
                $($spec_entries)*
                ($cat, $variant, $feat, $module, $display, [$($ext),*], [$($alias),*])
            ]
        );
    };

    // Extra unit variant, followed by more tokens.
    (@parse
        [$($enum_meta:meta)*]
        $vis:vis
        $name:ident
        [$($enum_variants:tt)*]
        [$($spec_entries:tt)*]
        $(#[$var_meta:meta])*
        $variant:ident
        , $($tail:tt)*
    ) => {
        define_formats!(@parse
            [$($enum_meta)*]
            $vis
            $name
            [
                $($enum_variants)*
                $(#[$var_meta])*
                $variant,
            ]
            [$($spec_entries)*]
            $($tail)*
        );
    };

    // Extra unit variant, last (no trailing comma).
    (@parse
        [$($enum_meta:meta)*]
        $vis:vis
        $name:ident
        [$($enum_variants:tt)*]
        [$($spec_entries:tt)*]
        $(#[$var_meta:meta])*
        $variant:ident
    ) => {
        define_formats!(@parse
            [$($enum_meta)*]
            $vis
            $name
            [
                $($enum_variants)*
                $(#[$var_meta])*
                $variant,
            ]
            [$($spec_entries)*]
        );
    };

    // Extra tuple/struct-like variant, followed by more tokens.
    (@parse
        [$($enum_meta:meta)*]
        $vis:vis
        $name:ident
        [$($enum_variants:tt)*]
        [$($spec_entries:tt)*]
        $(#[$var_meta:meta])*
        $variant:ident ( $($fields:tt)* )
        , $($tail:tt)*
    ) => {
        define_formats!(@parse
            [$($enum_meta)*]
            $vis
            $name
            [
                $($enum_variants)*
                $(#[$var_meta])*
                $variant ( $($fields)* ),
            ]
            [$($spec_entries)*]
            $($tail)*
        );
    };

    // Extra tuple/struct-like variant, last (no trailing comma).
    (@parse
        [$($enum_meta:meta)*]
        $vis:vis
        $name:ident
        [$($enum_variants:tt)*]
        [$($spec_entries:tt)*]
        $(#[$var_meta:meta])*
        $variant:ident ( $($fields:tt)* )
    ) => {
        define_formats!(@parse
            [$($enum_meta)*]
            $vis
            $name
            [
                $($enum_variants)*
                $(#[$var_meta])*
                $variant ( $($fields)* ),
            ]
            [$($spec_entries)*]
        );
    };
}

define_formats!(
    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
    pub enum FormatKind {
        Json => (Structured, json, "json", ["json"]),
        Yaml => (Structured, yaml, "yaml", ["yaml", "yml"]),
        Toml => (Structured, toml, "toml", ["toml"]),
        Ini => (Structured, ini, "ini", ["ini"]),
        Csv => (Other, csv, "csv", ["csv"]),
        Xml => (Other, xml, "xml", ["xml"]),
        /// Custom format with a unique name
        Custom(&'static str),
        Plaintext => (Other, plaintext, "plaintext", ["plaintext", "text", "txt"]),
    }
);

// Projection: full `Display` implementation for `FormatKind`.
macro_rules! impl_formatkind_display {
    ( $(($cat:ident, $kind:ident, $feat:literal, $module:ident,
        $display:literal, [$($ext:literal),*], [$($alias:literal),*]))* ) => {
        impl std::fmt::Display for FormatKind {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match self {
                    $( FormatKind::$kind => write!(f, $display), )*
                    FormatKind::Custom(name) => write!(f, "{}", name),
                }
            }
        }
    };
}

// Projection: default order = all kinds in declaration order.
macro_rules! define_default_order_from_spec {
    ( $(($cat:ident, $kind:ident, $feat:literal, $module:ident,
        $display:literal, [$($ext:literal),*], [$($alias:literal),*]))* ) => {
        pub(crate) const DEFAULT_FORMAT_ORDER: &[FormatKind] = &[
            $( FormatKind::$kind ),*
        ];
    };
}

// Projection: structured-text formats = only `Structured` entries, same order.
// NOTE: This pattern assumes that all `Structured` entries appear before `Other`
// entries in `format_spec!`. Tests assert that structured formats are a prefix
// of `DEFAULT_FORMAT_ORDER`, so reordering must respect this invariant.
macro_rules! define_structured_text_from_spec {
    (
        $(
            (Structured, $kind:ident, $feat:literal, $module:ident,
             $display:literal, [$($ext:literal),*], [$($alias:literal),*])
        )*
        $(
            (Other, $other_kind:ident, $other_feat:literal, $other_module:ident,
             $other_display:literal, [$($other_ext:literal),*], [$($other_alias:literal),*])
        )*
    ) => {
        #[allow(dead_code)]
        pub(crate) const STRUCTURED_TEXT_FORMATS: &[FormatKind] = &[
            $( FormatKind::$kind, )*
        ];
    };
}

format_spec!(define_default_order_from_spec);
format_spec!(define_structured_text_from_spec);
format_spec!(impl_formatkind_display);

// Helper: iterate over all enabled builtin formats in DEFAULT_FORMAT_ORDER.
macro_rules! impl_for_each_enabled_builtin {
    ( $(($cat:ident, $kind:ident, $feat:literal, $module:ident,
        $display:literal, [$($ext:literal),*], [$($alias:literal),*]))* ) => {
        pub(crate) fn for_each_enabled_builtin<F>(mut f: F)
        where
            F: FnMut(FormatKind),
        {
            // Ensure `f` is considered used even when all format features are disabled.
            let _ = &mut f;
            for kind in DEFAULT_FORMAT_ORDER {
                match kind {
                    $(
                        FormatKind::$kind => {
                            #[cfg(feature = $feat)]
                            f(FormatKind::$kind);
                        }
                    )*
                    FormatKind::Custom(_) => {}
                }
            }
        }
    };
}

format_spec!(impl_for_each_enabled_builtin);

// Projection: body for `FormatKind::extensions`.
macro_rules! impl_formatkind_extensions_body {
    ($self:ident
        $(($cat:ident, $kind:ident, $feat:literal, $module:ident,
           $display:literal, [$($ext:literal),*], [$($alias:literal),*]))*
    ) => {{
        match $self {
            $( FormatKind::$kind => &[$($ext),*], )*
            FormatKind::Custom(_) => &[],
        }
    }};
}

// Projection: body for `FormatKind::is_available`.
macro_rules! impl_formatkind_is_available_body {
    ($self:ident
        $(($cat:ident, $kind:ident, $feat:literal, $module:ident,
           $display:literal, [$($ext:literal),*], [$($alias:literal),*]))*
    ) => {{
        match $self {
            $(
                #[cfg(feature = $feat)]
                FormatKind::$kind => true,
                #[cfg(not(feature = $feat))]
                FormatKind::$kind => false,
            )*
            // Custom formats are always considered available
            // (availability is determined by registration)
            FormatKind::Custom(_) => true,
        }
    }};
}

// Projection: body for `FromStr` implementation.
macro_rules! impl_formatkind_from_str_body {
    ($lower:ident
        $(($cat:ident, $kind:ident, $feat:literal, $module:ident,
           $display:literal, [$($ext:literal),*], [$($alias:literal),*]))*
    ) => {{
        let kind = match $lower.as_str() {
            $(
                $( $alias )|* => FormatKind::$kind,
            )*
            _ => return Err(()),
        };
        Ok(kind)
    }};
}

impl FormatKind {
    pub fn custom(name: &'static str) -> Self {
        FormatKind::Custom(name)
    }

    /// Get file extensions for this format.
    /// Note: For custom formats, this returns an empty slice.
    /// Use FormatRegistry to get extensions for custom formats.
    pub fn extensions(&self) -> &'static [&'static str] {
        format_spec!(impl_formatkind_extensions_body(self))
    }

    /// Check if this format is available (feature enabled).
    pub fn is_available(&self) -> bool {
        format_spec!(impl_formatkind_is_available_body(self))
    }
}

impl std::str::FromStr for FormatKind {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let lower = s.to_ascii_lowercase();

        if let Some(rest) = lower.strip_prefix("custom:") {
            // Leak the custom format name into a 'static str so it can live
            // inside FormatKind::Custom. This is acceptable for configuration-
            // level strings which are created once per process.
            let leaked: &'static str = Box::leak(rest.to_string().into_boxed_str());
            return Ok(FormatKind::Custom(leaked));
        }

        format_spec!(impl_formatkind_from_str_body(lower))
    }
}

#[derive(Debug, Error)]
pub enum FormatError {
    #[error("Unknown format: {0}")]
    UnknownFormat(FormatKind),

    #[error("No format matched the input")]
    NoFormatMatched,

    #[error("Format '{0}' is not enabled. Enable the corresponding feature.")]
    NotEnabled(FormatKind),

    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    #[error("Serde error: {0}")]
    Serde(Box<dyn std::error::Error + Send + Sync>),

    /// Other format-specific error
    #[error("Format error: {0}")]
    Other(Box<dyn std::error::Error + Send + Sync>),
}

// Projection: body for top-level `deserialize` function.
macro_rules! impl_deserialize_body {
    ($bytes:ident, $kind:ident
        $(($cat:ident, $fmt_kind:ident, $feat:literal, $module:ident,
           $display:literal, [$($ext:literal),*], [$($alias:literal),*]))*
    ) => {{
        match $kind {
            $(
                #[cfg(feature = $feat)]
                FormatKind::$fmt_kind => $module::deserialize($bytes),
            )*

            #[allow(unreachable_patterns)]
            _ => Err(FormatError::NotEnabled($kind)),
        }
    }};
}

// Projection: body for top-level `serialize` function.
macro_rules! impl_serialize_body {
    ($value:ident, $kind:ident
        $(($cat:ident, $fmt_kind:ident, $feat:literal, $module:ident,
           $display:literal, [$($ext:literal),*], [$($alias:literal),*]))*
    ) => {{
        match $kind {
            $(
                #[cfg(feature = $feat)]
                FormatKind::$fmt_kind => $module::serialize($value),
            )*

            #[allow(unreachable_patterns)]
            _ => Err(FormatError::NotEnabled($kind)),
        }
    }};
}

pub fn deserialize<T: DeserializeOwned>(kind: FormatKind, bytes: &[u8]) -> Result<T, FormatError> {
    let _ = bytes;
    format_spec!(impl_deserialize_body(bytes, kind))
}

/// Serialize to bytes using the specified format.
pub fn serialize<T: Serialize>(kind: FormatKind, value: &T) -> Result<Vec<u8>, FormatError> {
    let _ = value;
    format_spec!(impl_serialize_body(value, kind))
}

/// Deserialize from a reader using the specified format.
pub fn deserialize_from_reader<T: DeserializeOwned>(
    kind: FormatKind,
    reader: &mut dyn Read,
) -> Result<T, FormatError> {
    let mut bytes = Vec::new();
    reader.read_to_end(&mut bytes)?;
    deserialize(kind, &bytes)
}

macro_rules! define_stream_deserialize_fn_read {
    (
        $(#[$meta:meta])*
        [$cfg_feat:literal]
        $module:ident
    ) => {
        paste! {
            $(#[$meta])*
            #[cfg(feature = $cfg_feat)]
            pub fn [<deserialize_ $module _stream>]<T, R>(
                reader: R,
            ) -> impl Iterator<Item = Result<T, FormatError>>
            where
                T: DeserializeOwned,
                R: Read,
            {
                $module::stream_deserialize(reader)
            }
        }
    };
}

macro_rules! define_stream_deserialize_fn_read_static {
    (
        $(#[$meta:meta])*
        [$cfg_feat:literal]
        $module:ident
    ) => {
        paste! {
            $(#[$meta])*
            #[cfg(feature = $cfg_feat)]
            pub fn [<deserialize_ $module _stream>]<T, R>(
                reader: R,
            ) -> impl Iterator<Item = Result<T, FormatError>>
            where
                T: DeserializeOwned,
                R: Read + 'static,
            {
                $module::stream_deserialize(reader)
            }
        }
    };
}

define_stream_deserialize_fn_read!(
    /// Stream JSON values from a reader as multiple top-level JSON documents.
    ["json"]
    json
);

define_stream_deserialize_fn_read!(
    /// Stream CSV records from a reader.
    ["csv"]
    csv
);

define_stream_deserialize_fn_read_static!(
    /// Stream YAML documents from a reader.
    ["yaml"]
    yaml
);

define_stream_deserialize_fn_read!(
    /// Stream plaintext records (typically lines) from a reader.
    ["plaintext"]
    plaintext
);

/// Format registry.
#[derive(Default)]
pub struct FormatRegistry {
    /// Registered built-in formats.
    formats: Vec<FormatKind>,
    /// Custom format handlers
    #[cfg(feature = "custom")]
    custom_formats: Vec<CustomFormat>,
}

impl FormatRegistry {
    /// Create a new empty registry.
    pub fn new() -> Self {
        Self {
            formats: Vec::new(),
            #[cfg(feature = "custom")]
            custom_formats: Vec::new(),
        }
    }

    /// Register a built-in format.
    pub fn register(&mut self, kind: FormatKind) {
        if !self.formats.contains(&kind) {
            self.formats.push(kind);
        }
    }

    /// Register a built-in format (builder pattern).
    pub fn with_format(mut self, kind: FormatKind) -> Self {
        self.register(kind);
        self
    }

    /// Register a custom format handler.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use multiio::format::{CustomFormat, FormatRegistry, FormatError};
    ///
    /// let mut registry = FormatRegistry::new();
    /// registry.register_custom(
    ///     CustomFormat::new("toml", &["toml"])
    ///         .with_deserialize(|bytes| {
    ///             // Your deserialization logic
    ///             Ok(serde_json::Value::Null)
    ///         })
    ///         .with_serialize(|value| {
    ///             // Your serialization logic
    ///             Ok(Vec::new())
    ///         })
    /// );
    /// ```
    #[cfg(feature = "custom")]
    pub fn register_custom(&mut self, format: CustomFormat) {
        // Also register the FormatKind::Custom variant
        let kind = FormatKind::Custom(format.name);
        if !self.formats.contains(&kind) {
            self.formats.push(kind);
        }
        self.custom_formats.push(format);
    }

    /// Register a custom format handler (builder pattern).
    #[cfg(feature = "custom")]
    pub fn with_custom_format(mut self, format: CustomFormat) -> Self {
        self.register_custom(format);
        self
    }

    /// Check if a format is registered.
    pub fn has_format(&self, kind: &FormatKind) -> bool {
        self.formats.contains(kind)
    }

    /// Get the custom format handler for a format kind.
    #[cfg(feature = "custom")]
    pub fn get_custom(&self, name: &str) -> Option<&CustomFormat> {
        self.custom_formats.iter().find(|f| f.name == name)
    }

    /// Get format kind for a file extension.
    pub fn kind_for_extension(&self, ext: &str) -> Option<FormatKind> {
        let ext_lower = ext.to_ascii_lowercase();

        // Check built-in formats first
        for kind in &self.formats {
            if kind
                .extensions()
                .iter()
                .any(|e| e.eq_ignore_ascii_case(&ext_lower))
            {
                return Some(*kind);
            }
        }

        // Check custom formats (requires `custom` feature)
        #[cfg(feature = "custom")]
        for custom in &self.custom_formats {
            if custom.matches_extension(&ext_lower) {
                return Some(FormatKind::Custom(custom.name));
            }
        }

        None
    }

    /// Resolve a format based on explicit kind or candidates.
    pub fn resolve(
        &self,
        explicit: Option<&FormatKind>,
        candidates: &[FormatKind],
    ) -> Result<FormatKind, FormatError> {
        if let Some(k) = explicit {
            if self.has_format(k) && k.is_available() {
                return Ok(*k);
            }
            return Err(FormatError::UnknownFormat(*k));
        }
        for k in candidates {
            if self.has_format(k) && k.is_available() {
                return Ok(*k);
            }
        }
        Err(FormatError::NoFormatMatched)
    }

    /// Get all registered format kinds.
    pub fn formats(&self) -> &[FormatKind] {
        &self.formats
    }

    /// Get all registered custom formats.
    #[cfg(feature = "custom")]
    pub fn custom_formats(&self) -> &[CustomFormat] {
        &self.custom_formats
    }

    /// Deserialize using this registry.
    ///
    /// Automatically handles both built-in and custom formats.
    pub fn deserialize_value<T: DeserializeOwned>(
        &self,
        explicit: Option<&FormatKind>,
        candidates: &[FormatKind],
        bytes: &[u8],
    ) -> Result<T, FormatError> {
        let kind = self.resolve(explicit, candidates)?;

        // Handle custom formats (requires `custom` feature)
        if let FormatKind::Custom(_name) = &kind {
            #[cfg(feature = "custom")]
            {
                let custom = self
                    .get_custom(_name)
                    .ok_or_else(|| FormatError::UnknownFormat(kind))?;
                return custom.deserialize(bytes);
            }
            #[cfg(not(feature = "custom"))]
            {
                return Err(FormatError::NotEnabled(kind));
            }
        }

        // Handle built-in formats
        deserialize(kind, bytes)
    }

    /// Serialize using this registry.
    ///
    /// Automatically handles both built-in and custom formats.
    pub fn serialize_value<T: Serialize>(
        &self,
        explicit: Option<&FormatKind>,
        candidates: &[FormatKind],
        value: &T,
    ) -> Result<Vec<u8>, FormatError> {
        let kind = self.resolve(explicit, candidates)?;

        // Handle custom formats (requires `custom` feature)
        if let FormatKind::Custom(_name) = &kind {
            #[cfg(feature = "custom")]
            {
                let custom = self
                    .get_custom(_name)
                    .ok_or_else(|| FormatError::UnknownFormat(kind))?;
                return custom.serialize(value);
            }
            #[cfg(not(feature = "custom"))]
            {
                return Err(FormatError::NotEnabled(kind));
            }
        }

        // Handle built-in formats
        serialize(kind, value)
    }

    /// Stream-deserialize values into `T` using this registry.
    ///
    /// For built-in JSON/CSV formats, this uses native streaming decoders.
    /// For custom formats, if a streaming handler is provided it will be used.
    /// Otherwise, falls back to non-streaming deserialization as a single item.
    pub fn stream_deserialize_into<T>(
        &self,
        explicit: Option<&FormatKind>,
        candidates: &[FormatKind],
        reader: Box<dyn Read>,
    ) -> Result<Box<dyn Iterator<Item = Result<T, FormatError>>>, FormatError>
    where
        T: DeserializeOwned + 'static,
    {
        let kind = self.resolve(explicit, candidates)?;

        if let FormatKind::Json = kind {
            #[cfg(feature = "json")]
            {
                let iter = crate::format::deserialize_json_stream::<T, _>(reader);
                return Ok(Box::new(iter));
            }
            #[cfg(not(feature = "json"))]
            {
                return Err(FormatError::NotEnabled(kind));
            }
        }

        if let FormatKind::Csv = kind {
            #[cfg(feature = "csv")]
            {
                let iter = crate::format::deserialize_csv_stream::<T, _>(reader);
                return Ok(Box::new(iter));
            }
            #[cfg(not(feature = "csv"))]
            {
                return Err(FormatError::NotEnabled(kind));
            }
        }

        if let FormatKind::Yaml = kind {
            #[cfg(feature = "yaml")]
            {
                let iter = crate::format::deserialize_yaml_stream::<T, _>(reader);
                return Ok(Box::new(iter));
            }
            #[cfg(not(feature = "yaml"))]
            {
                return Err(FormatError::NotEnabled(kind));
            }
        }

        if let FormatKind::Plaintext = kind {
            #[cfg(feature = "plaintext")]
            {
                let iter = crate::format::deserialize_plaintext_stream::<T, _>(reader);
                return Ok(Box::new(iter));
            }
            #[cfg(not(feature = "plaintext"))]
            {
                return Err(FormatError::NotEnabled(kind));
            }
        }

        if let FormatKind::Custom(name) = kind {
            #[cfg(feature = "custom")]
            {
                let custom = self
                    .get_custom(name)
                    .ok_or_else(|| FormatError::UnknownFormat(FormatKind::Custom(name)))?;

                if custom.stream_deserialize_fn.is_some() {
                    let iter = custom.stream_deserialize_values(reader)?.map(|res| {
                        res.and_then(|value| {
                            serde_json::from_value::<T>(value)
                                .map_err(|e| FormatError::Serde(Box::new(e)))
                        })
                    });
                    return Ok(Box::new(iter));
                } else {
                    // Fallback: non-streaming, single item
                    let mut r = reader;
                    let mut bytes = Vec::new();
                    r.read_to_end(&mut bytes)?;
                    let value = custom.deserialize::<T>(&bytes)?;
                    return Ok(Box::new(std::iter::once(Ok(value))));
                }
            }
            #[cfg(not(feature = "custom"))]
            {
                return Err(FormatError::NotEnabled(FormatKind::Custom(name)));
            }
        }

        // Other built-in formats: fallback to non-streaming, single item
        let mut r = reader;
        let mut bytes = Vec::new();
        r.read_to_end(&mut bytes)?;
        let value = deserialize::<T>(kind, &bytes)?;
        Ok(Box::new(std::iter::once(Ok(value))))
    }
}

/// Create a default registry with all enabled formats.
///
/// default formats with order: [DEFAULT_FORMAT_ORDER]
pub fn default_registry() -> FormatRegistry {
    let mut registry = FormatRegistry::new();
    for_each_enabled_builtin(|k| registry.register(k));

    registry
}

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

    #[test]
    fn default_format_order_is_expected() {
        assert_eq!(
            DEFAULT_FORMAT_ORDER,
            &[
                FormatKind::Json,
                FormatKind::Yaml,
                FormatKind::Toml,
                FormatKind::Ini,
                FormatKind::Csv,
                FormatKind::Xml,
                FormatKind::Plaintext,
            ],
        );
    }

    #[test]
    fn structured_text_formats_are_prefix_of_default_order() {
        assert_eq!(
            STRUCTURED_TEXT_FORMATS,
            &DEFAULT_FORMAT_ORDER[..STRUCTURED_TEXT_FORMATS.len()],
        );
    }
}

// Async format support
#[cfg(feature = "async")]
mod async_format;

#[cfg(feature = "async")]
pub use async_format::*;