copybook-options 0.5.0

Configuration option contracts shared across copybook codec workflows
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
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Configuration option types shared across copybook-rs crates.
//!
//! This crate defines [`DecodeOptions`], [`EncodeOptions`], [`RecordFormat`],
//! [`JsonNumberMode`], [`RawMode`], and [`FloatFormat`] — the common configuration
//! surface used by the codec and CLI layers.
#![allow(clippy::missing_inline_in_public_items)]

// Re-export from copybook-charset for public API
/// Codepage identifier for EBCDIC/ASCII character encoding.
pub use copybook_charset::Codepage;
/// Policy for handling unmappable characters during codepage conversion.
pub use copybook_charset::UnmappablePolicy;
/// Zoned decimal encoding format (ASCII, EBCDIC, or auto-detect).
pub use copybook_zoned_format::ZonedEncodingFormat;
use serde::{Deserialize, Serialize};
use std::fmt;

const DEFAULT_RECORD_FORMAT: RecordFormat = RecordFormat::Fixed;
const DEFAULT_CODEPAGE: Codepage = Codepage::CP037;
const DEFAULT_JSON_NUMBER_MODE: JsonNumberMode = JsonNumberMode::Lossless;
const DEFAULT_UNMAPPABLE_POLICY: UnmappablePolicy = UnmappablePolicy::Error;
const DEFAULT_THREAD_COUNT: usize = 1;
const DEFAULT_ZONED_ENCODING: ZonedEncodingFormat = ZonedEncodingFormat::Auto;
const DEFAULT_FLOAT_FORMAT: FloatFormat = FloatFormat::IeeeBigEndian;

macro_rules! impl_common_option_builders {
    () => {
        /// Set the record format.
        #[must_use]
        #[inline]
        pub fn with_format(mut self, format: RecordFormat) -> Self {
            self.format = format;
            self
        }

        /// Set the codepage.
        #[must_use]
        #[inline]
        pub fn with_codepage(mut self, codepage: Codepage) -> Self {
            self.codepage = codepage;
            self
        }

        /// Enable or disable strict mode.
        #[must_use]
        #[inline]
        pub fn with_strict_mode(mut self, strict_mode: bool) -> Self {
            self.strict_mode = strict_mode;
            self
        }

        /// Set the maximum number of errors before stopping.
        #[must_use]
        #[inline]
        pub fn with_max_errors(mut self, max_errors: Option<u64>) -> Self {
            self.max_errors = max_errors;
            self
        }

        /// Set the number of threads for parallel processing.
        #[must_use]
        #[inline]
        pub fn with_threads(mut self, threads: usize) -> Self {
            self.threads = threads;
            self
        }

        /// Set the JSON number mode.
        #[must_use]
        #[inline]
        pub fn with_json_number_mode(mut self, mode: JsonNumberMode) -> Self {
            self.json_number_mode = mode;
            self
        }

        /// Set the preferred zoned decimal encoding format.
        #[must_use]
        #[inline]
        pub fn with_preferred_zoned_encoding(
            mut self,
            preferred_zoned_encoding: ZonedEncodingFormat,
        ) -> Self {
            self.preferred_zoned_encoding = preferred_zoned_encoding;
            self
        }

        /// Set floating-point representation for COMP-1/COMP-2 fields.
        #[must_use]
        #[inline]
        pub fn with_float_format(mut self, float_format: FloatFormat) -> Self {
            self.float_format = float_format;
            self
        }
    };
}

/// Floating-point binary format for COMP-1/COMP-2 fields.
///
/// Copybooks define field usage but not the compiler's concrete floating-point
/// representation. This option makes the decode/encode interpretation explicit.
///
/// # Examples
///
/// ```
/// use copybook_options::FloatFormat;
///
/// let fmt = FloatFormat::default();
/// assert_eq!(fmt, FloatFormat::IeeeBigEndian);
/// assert_eq!(format!("{fmt}"), "ieee-be");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum, Default)]
pub enum FloatFormat {
    /// IEEE-754 big-endian binary format.
    #[default]
    #[value(name = "ieee-be", alias = "ieee", alias = "ieee-big-endian")]
    IeeeBigEndian,
    /// IBM hexadecimal floating-point format.
    #[value(name = "ibm-hex", alias = "ibm")]
    IbmHex,
}

/// Options for decoding operations
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(clippy::struct_excessive_bools)] // Many boolean options are needed for decode configuration
pub struct DecodeOptions {
    /// Record format
    pub format: RecordFormat,
    /// Character encoding
    pub codepage: Codepage,
    /// JSON number representation
    pub json_number_mode: JsonNumberMode,
    /// Whether to emit FILLER fields
    pub emit_filler: bool,
    /// Whether to emit metadata
    pub emit_meta: bool,
    /// Raw data capture mode
    pub emit_raw: RawMode,
    /// Error handling mode
    pub strict_mode: bool,
    /// Maximum errors before stopping
    pub max_errors: Option<u64>,
    /// Policy for unmappable characters
    pub on_decode_unmappable: UnmappablePolicy,
    /// Number of threads for parallel processing
    pub threads: usize,
    /// Enable zoned decimal encoding preservation for binary round-trip consistency
    ///
    /// When enabled, the decoder captures the original encoding format (ASCII vs EBCDIC)
    /// and includes it in metadata for use during re-encoding to maintain byte-level
    /// fidelity in encode/decode cycles.
    pub preserve_zoned_encoding: bool,
    /// Preferred encoding format when auto-detection is ambiguous
    ///
    /// Used as fallback when `ZonedEncodingFormat::Auto` cannot determine the format
    /// from the data (e.g., all-zero fields, mixed encodings).
    pub preferred_zoned_encoding: ZonedEncodingFormat,
    /// Floating-point representation for COMP-1/COMP-2 fields.
    #[serde(default)]
    pub float_format: FloatFormat,
}

/// Options for encoding operations
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(clippy::struct_excessive_bools)]
pub struct EncodeOptions {
    /// Record format
    pub format: RecordFormat,
    /// Character encoding
    pub codepage: Codepage,
    /// Fallback zoned decimal encoding format when no override or metadata applies
    pub preferred_zoned_encoding: ZonedEncodingFormat,
    /// Whether to use raw data when available
    pub use_raw: bool,
    /// BLANK WHEN ZERO encoding policy
    pub bwz_encode: bool,
    /// Error handling mode
    pub strict_mode: bool,
    /// Maximum errors before stopping
    pub max_errors: Option<u64>,
    /// Number of threads for parallel processing
    pub threads: usize,
    /// Whether to coerce non-string JSON numbers to strings before encoding
    pub coerce_numbers: bool,
    /// Policy for unmappable characters during encoding
    pub on_encode_unmappable: UnmappablePolicy,
    /// JSON number representation mode (used when round-tripping)
    pub json_number_mode: JsonNumberMode,
    /// Explicit zoned decimal encoding format override
    ///
    /// When specified, forces all zoned decimal fields to use this encoding format,
    /// overriding any preserved format from decode operations. This provides the
    /// highest precedence in the format selection hierarchy:
    /// 1. Explicit override (this field)
    /// 2. Preserved format from decode metadata
    /// 3. EBCDIC default for mainframe compatibility
    pub zoned_encoding_override: Option<ZonedEncodingFormat>,
    /// Floating-point representation for COMP-1/COMP-2 fields.
    #[serde(default)]
    pub float_format: FloatFormat,
}

/// Record format specification
///
/// Controls whether records have a fixed byte length (LRECL) or use
/// variable-length RDW (Record Descriptor Word) framing.
///
/// # Examples
///
/// ```
/// use copybook_options::RecordFormat;
///
/// let fmt = RecordFormat::Fixed;
/// assert!(fmt.is_fixed());
/// assert!(!fmt.is_variable());
/// assert_eq!(fmt.description(), "Fixed-length records");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
pub enum RecordFormat {
    /// Fixed-length records
    Fixed,
    /// Variable-length records with RDW
    RDW,
}

impl RecordFormat {
    /// Check if this is a fixed-length record format
    #[must_use]
    pub const fn is_fixed(self) -> bool {
        matches!(self, Self::Fixed)
    }

    /// Check if this is a variable-length record format
    #[must_use]
    pub const fn is_variable(self) -> bool {
        matches!(self, Self::RDW)
    }

    /// Get a human-readable description of the format
    #[must_use]
    pub const fn description(self) -> &'static str {
        match self {
            Self::Fixed => "Fixed-length records",
            Self::RDW => "Variable-length records with Record Descriptor Word",
        }
    }
}

/// JSON number representation mode
///
/// Controls how COBOL numeric fields are represented in JSON output.
/// `Lossless` preserves exact decimal precision as strings; `Native` uses
/// JSON number types where the value fits without precision loss.
///
/// # Examples
///
/// ```
/// use copybook_options::JsonNumberMode;
///
/// let mode = JsonNumberMode::Lossless;
/// assert!(mode.is_lossless());
/// assert_eq!(mode.description(), "Lossless string representation for decimals");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
pub enum JsonNumberMode {
    /// Lossless string representation for decimals
    Lossless,
    /// Native JSON numbers where possible
    Native,
}

impl JsonNumberMode {
    /// Check if this mode uses lossless string representation
    #[must_use]
    #[inline]
    pub const fn is_lossless(self) -> bool {
        matches!(self, Self::Lossless)
    }

    /// Check if this mode uses native JSON numbers
    #[must_use]
    #[inline]
    pub const fn is_native(self) -> bool {
        matches!(self, Self::Native)
    }

    /// Get a human-readable description of the mode
    #[must_use]
    #[inline]
    pub const fn description(self) -> &'static str {
        match self {
            Self::Lossless => "Lossless string representation for decimals",
            Self::Native => "Native JSON numbers where possible",
        }
    }
}

/// Raw data capture mode
///
/// Controls whether and how binary record data is captured in the output:
/// - `Off` — no raw data (default, lowest overhead)
/// - `Record` — full record payload in `__raw_b64`
/// - `RecordRDW` — RDW header + payload in `__raw_b64`
/// - `Field` — per-field raw bytes in `<FIELD_NAME>__raw_b64`
///
/// # Examples
///
/// ```
/// use copybook_options::RawMode;
///
/// let mode = RawMode::Off;
/// assert_eq!(mode, RawMode::Off);
///
/// let field_mode = RawMode::Field;
/// assert_ne!(field_mode, RawMode::Off);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
pub enum RawMode {
    /// No raw data capture
    Off,
    /// Capture record-level raw data
    Record,
    /// Capture field-level raw data
    Field,
    /// Capture record and RDW header
    #[value(name = "record+rdw")]
    RecordRDW,
}

impl Default for DecodeOptions {
    fn default() -> Self {
        Self {
            format: DEFAULT_RECORD_FORMAT,
            codepage: DEFAULT_CODEPAGE,
            json_number_mode: DEFAULT_JSON_NUMBER_MODE,
            emit_filler: false,
            emit_meta: false,
            emit_raw: RawMode::Off,
            strict_mode: false,
            max_errors: None,
            on_decode_unmappable: DEFAULT_UNMAPPABLE_POLICY,
            threads: DEFAULT_THREAD_COUNT,
            preserve_zoned_encoding: false,
            preferred_zoned_encoding: DEFAULT_ZONED_ENCODING,
            float_format: DEFAULT_FLOAT_FORMAT,
        }
    }
}

impl DecodeOptions {
    /// Create new decode options with default values
    ///
    /// Returns options configured for:
    /// - Fixed record format
    /// - CP037 EBCDIC codepage
    /// - Lossless JSON number mode
    /// - Single-threaded processing
    ///
    /// Use the builder methods to customize:
    ///
    /// # Examples
    ///
    /// ```
    /// use copybook_options::{DecodeOptions, Codepage, JsonNumberMode, RecordFormat, RawMode};
    ///
    /// let opts = DecodeOptions::new()
    ///     .with_codepage(Codepage::CP037)
    ///     .with_format(RecordFormat::Fixed)
    ///     .with_json_number_mode(JsonNumberMode::Lossless)
    ///     .with_emit_meta(true)
    ///     .with_threads(4);
    ///
    /// assert_eq!(opts.threads, 4);
    /// assert!(opts.emit_meta);
    /// ```
    #[must_use]
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    impl_common_option_builders!();

    /// Enable or disable FILLER field emission
    #[must_use]
    #[inline]
    pub fn with_emit_filler(mut self, emit_filler: bool) -> Self {
        self.emit_filler = emit_filler;
        self
    }

    /// Enable or disable metadata emission
    #[must_use]
    #[inline]
    pub fn with_emit_meta(mut self, emit_meta: bool) -> Self {
        self.emit_meta = emit_meta;
        self
    }

    /// Set the raw data capture mode
    ///
    /// Controls whether and how raw binary data is included in decode output:
    /// - `RawMode::Off` — no raw data (default)
    /// - `RawMode::Record` — record payload in `__raw_b64`
    /// - `RawMode::RecordRDW` — RDW header + payload in `__raw_b64`
    /// - `RawMode::Field` — per-field raw values in `<FIELD>__raw_b64`
    #[must_use]
    #[inline]
    pub fn with_emit_raw(mut self, emit_raw: RawMode) -> Self {
        self.emit_raw = emit_raw;
        self
    }

    /// Set the policy for unmappable characters
    #[must_use]
    #[inline]
    pub fn with_unmappable_policy(mut self, policy: UnmappablePolicy) -> Self {
        self.on_decode_unmappable = policy;
        self
    }

    // === Zoned Decimal Encoding Configuration ===

    /// Enable zoned decimal encoding preservation for round-trip fidelity
    ///
    /// When enabled, the decoder will detect and preserve the original encoding
    /// format (ASCII vs EBCDIC) for use during subsequent encoding operations.
    /// This ensures byte-level consistency in encode/decode cycles.
    #[must_use]
    #[inline]
    pub fn with_preserve_zoned_encoding(mut self, preserve_zoned_encoding: bool) -> Self {
        self.preserve_zoned_encoding = preserve_zoned_encoding;
        self
    }
}

impl Default for EncodeOptions {
    fn default() -> Self {
        Self {
            format: DEFAULT_RECORD_FORMAT,
            codepage: DEFAULT_CODEPAGE,
            preferred_zoned_encoding: DEFAULT_ZONED_ENCODING,
            use_raw: false,
            bwz_encode: false,
            strict_mode: false,
            max_errors: None,
            threads: DEFAULT_THREAD_COUNT,
            coerce_numbers: false,
            on_encode_unmappable: DEFAULT_UNMAPPABLE_POLICY,
            json_number_mode: DEFAULT_JSON_NUMBER_MODE,
            zoned_encoding_override: None,
            float_format: DEFAULT_FLOAT_FORMAT,
        }
    }
}

impl EncodeOptions {
    /// Create new encode options with default values
    ///
    /// Returns options configured for:
    /// - Fixed record format
    /// - CP037 EBCDIC codepage
    /// - Single-threaded processing
    /// - BLANK WHEN ZERO disabled
    ///
    /// Use the builder methods to customize:
    ///
    /// # Examples
    ///
    /// ```
    /// use copybook_options::{EncodeOptions, Codepage, RecordFormat};
    ///
    /// let opts = EncodeOptions::new()
    ///     .with_codepage(Codepage::CP037)
    ///     .with_format(RecordFormat::Fixed)
    ///     .with_bwz_encode(true)
    ///     .with_coerce_numbers(true)
    ///     .with_threads(4);
    ///
    /// assert_eq!(opts.threads, 4);
    /// assert!(opts.bwz_encode);
    /// assert!(opts.coerce_numbers);
    /// ```
    #[must_use]
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    impl_common_option_builders!();

    /// Enable or disable raw data usage
    #[must_use]
    #[inline]
    pub fn with_use_raw(mut self, use_raw: bool) -> Self {
        self.use_raw = use_raw;
        self
    }

    /// Enable or disable BLANK WHEN ZERO encoding
    #[must_use]
    #[inline]
    pub fn with_bwz_encode(mut self, bwz_encode: bool) -> Self {
        self.bwz_encode = bwz_encode;
        self
    }

    /// Enable or disable number coercion
    #[must_use]
    #[inline]
    pub fn with_coerce_numbers(mut self, coerce_numbers: bool) -> Self {
        self.coerce_numbers = coerce_numbers;
        self
    }

    /// Set the policy for unmappable characters during encoding
    #[must_use]
    #[inline]
    pub fn with_unmappable_policy(mut self, policy: UnmappablePolicy) -> Self {
        self.on_encode_unmappable = policy;
        self
    }

    /// Set explicit zoned decimal encoding format override
    ///
    /// Forces all zoned decimal fields to use the specified encoding format,
    /// overriding any preserved format from decode operations. Use `None` to
    /// disable override and respect preserved formats.
    #[must_use]
    #[inline]
    pub fn with_zoned_encoding_override(
        mut self,
        zoned_encoding_override: Option<ZonedEncodingFormat>,
    ) -> Self {
        self.zoned_encoding_override = zoned_encoding_override;
        self
    }

    /// Convenience method to set explicit zoned encoding format
    ///
    /// Equivalent to `with_zoned_encoding_override(Some(format))`.
    #[must_use]
    #[inline]
    pub fn with_zoned_encoding_format(mut self, format: ZonedEncodingFormat) -> Self {
        self.zoned_encoding_override = Some(format);
        self
    }
}
impl fmt::Display for RecordFormat {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Fixed => write!(f, "fixed"),
            Self::RDW => write!(f, "rdw"),
        }
    }
}

impl fmt::Display for JsonNumberMode {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Lossless => write!(f, "lossless"),
            Self::Native => write!(f, "native"),
        }
    }
}

impl fmt::Display for RawMode {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Off => write!(f, "off"),
            Self::Record => write!(f, "record"),
            Self::Field => write!(f, "field"),
            Self::RecordRDW => write!(f, "record+rdw"),
        }
    }
}

impl fmt::Display for FloatFormat {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IeeeBigEndian => write!(f, "ieee-be"),
            Self::IbmHex => write!(f, "ibm-hex"),
        }
    }
}

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

    #[test]
    fn test_zoned_encoding_format_is_ascii() {
        assert!(ZonedEncodingFormat::Ascii.is_ascii());
        assert!(!ZonedEncodingFormat::Ebcdic.is_ascii());
        assert!(!ZonedEncodingFormat::Auto.is_ascii());
    }

    #[test]
    fn test_zoned_encoding_format_is_ebcdic() {
        assert!(!ZonedEncodingFormat::Ascii.is_ebcdic());
        assert!(ZonedEncodingFormat::Ebcdic.is_ebcdic());
        assert!(!ZonedEncodingFormat::Auto.is_ebcdic());
    }

    #[test]
    fn test_zoned_encoding_format_is_auto() {
        assert!(!ZonedEncodingFormat::Ascii.is_auto());
        assert!(!ZonedEncodingFormat::Ebcdic.is_auto());
        assert!(ZonedEncodingFormat::Auto.is_auto());
    }

    #[test]
    fn test_zoned_encoding_format_description() {
        assert_eq!(
            ZonedEncodingFormat::Ascii.description(),
            "ASCII digit zones (0x30-0x39)"
        );
        assert_eq!(
            ZonedEncodingFormat::Ebcdic.description(),
            "EBCDIC digit zones (0xF0-0xF9)"
        );
        assert_eq!(
            ZonedEncodingFormat::Auto.description(),
            "Automatic detection based on zone nibbles"
        );
    }

    #[test]
    fn test_zoned_encoding_format_detect_from_byte() {
        // ASCII zone nibble (0x30)
        assert_eq!(
            ZonedEncodingFormat::detect_from_byte(0x35),
            Some(ZonedEncodingFormat::Ascii)
        );
        assert_eq!(
            ZonedEncodingFormat::detect_from_byte(0x30),
            Some(ZonedEncodingFormat::Ascii)
        );
        assert_eq!(
            ZonedEncodingFormat::detect_from_byte(0x39),
            Some(ZonedEncodingFormat::Ascii)
        );

        // EBCDIC zone nibble (0xF0)
        assert_eq!(
            ZonedEncodingFormat::detect_from_byte(0xF5),
            Some(ZonedEncodingFormat::Ebcdic)
        );
        assert_eq!(
            ZonedEncodingFormat::detect_from_byte(0xF0),
            Some(ZonedEncodingFormat::Ebcdic)
        );
        assert_eq!(
            ZonedEncodingFormat::detect_from_byte(0xF9),
            Some(ZonedEncodingFormat::Ebcdic)
        );

        // Invalid zone nibbles (0x00, 0x50)
        assert_eq!(ZonedEncodingFormat::detect_from_byte(0x00), None);
        assert_eq!(ZonedEncodingFormat::detect_from_byte(0x50), None);
        // Note: 0xFF matches EBCDIC_ZONE (0x0F), so it returns Some(Ebcdic)
        assert_eq!(
            ZonedEncodingFormat::detect_from_byte(0xFF),
            Some(ZonedEncodingFormat::Ebcdic)
        );
    }

    #[test]
    fn test_zoned_encoding_format_display() {
        assert_eq!(format!("{}", ZonedEncodingFormat::Ascii), "ascii");
        assert_eq!(format!("{}", ZonedEncodingFormat::Ebcdic), "ebcdic");
        assert_eq!(format!("{}", ZonedEncodingFormat::Auto), "auto");
    }

    #[test]
    fn test_decode_options_default() {
        let options = DecodeOptions::default();
        assert_eq!(options.format, RecordFormat::Fixed);
        assert_eq!(options.codepage, Codepage::CP037);
        assert_eq!(options.json_number_mode, JsonNumberMode::Lossless);
        assert!(!options.emit_filler);
        assert!(!options.emit_meta);
        assert_eq!(options.emit_raw, RawMode::Off);
        assert!(!options.strict_mode);
        assert!(options.max_errors.is_none());
        assert_eq!(options.on_decode_unmappable, UnmappablePolicy::Error);
        assert_eq!(options.threads, 1);
        assert!(!options.preserve_zoned_encoding);
        assert_eq!(options.preferred_zoned_encoding, ZonedEncodingFormat::Auto);
        assert_eq!(options.float_format, FloatFormat::IeeeBigEndian);
    }

    #[test]
    fn test_encode_options_default() {
        let options = EncodeOptions::default();
        assert_eq!(options.format, RecordFormat::Fixed);
        assert_eq!(options.codepage, Codepage::CP037);
        assert_eq!(options.preferred_zoned_encoding, ZonedEncodingFormat::Auto);
        assert!(!options.use_raw);
        assert!(!options.bwz_encode);
        assert!(!options.strict_mode);
        assert_eq!(options.on_encode_unmappable, UnmappablePolicy::Error);
        assert_eq!(options.json_number_mode, JsonNumberMode::Lossless);
        assert_eq!(options.float_format, FloatFormat::IeeeBigEndian);
    }

    #[test]
    fn test_record_format_display() {
        assert_eq!(format!("{}", RecordFormat::Fixed), "fixed");
        assert_eq!(format!("{}", RecordFormat::RDW), "rdw");
    }

    #[test]
    fn test_codepage_display() {
        assert_eq!(format!("{}", Codepage::CP037), "cp037");
        assert_eq!(format!("{}", Codepage::CP273), "cp273");
        assert_eq!(format!("{}", Codepage::CP500), "cp500");
        assert_eq!(format!("{}", Codepage::CP1047), "cp1047");
        assert_eq!(format!("{}", Codepage::CP1140), "cp1140");
    }

    #[test]
    fn test_json_number_mode_display() {
        assert_eq!(format!("{}", JsonNumberMode::Lossless), "lossless");
        assert_eq!(format!("{}", JsonNumberMode::Native), "native");
    }

    #[test]
    fn test_raw_mode_display() {
        assert_eq!(format!("{}", RawMode::Off), "off");
        assert_eq!(format!("{}", RawMode::Record), "record");
        assert_eq!(format!("{}", RawMode::Field), "field");
        assert_eq!(format!("{}", RawMode::RecordRDW), "record+rdw");
    }

    #[test]
    fn test_unmappable_policy_display() {
        assert_eq!(format!("{}", UnmappablePolicy::Error), "error");
        assert_eq!(format!("{}", UnmappablePolicy::Replace), "replace");
        assert_eq!(format!("{}", UnmappablePolicy::Skip), "skip");
    }

    #[test]
    fn test_decode_options_serialization() {
        let options = DecodeOptions {
            format: DEFAULT_RECORD_FORMAT,
            codepage: DEFAULT_CODEPAGE,
            json_number_mode: DEFAULT_JSON_NUMBER_MODE,
            emit_filler: true,
            emit_meta: true,
            emit_raw: RawMode::Record,
            strict_mode: true,
            max_errors: Some(100),
            on_decode_unmappable: UnmappablePolicy::Replace,
            threads: 4,
            preserve_zoned_encoding: true,
            preferred_zoned_encoding: ZonedEncodingFormat::Ebcdic,
            float_format: FloatFormat::IbmHex,
        };

        let serialized = serde_json::to_string(&options).unwrap();
        let deserialized: DecodeOptions = serde_json::from_str(&serialized).unwrap();

        assert_eq!(deserialized.format, RecordFormat::Fixed);
        assert_eq!(deserialized.codepage, Codepage::CP037);
        assert!(deserialized.emit_filler);
        assert!(deserialized.emit_meta);
        assert_eq!(deserialized.emit_raw, RawMode::Record);
        assert!(deserialized.strict_mode);
        assert_eq!(deserialized.max_errors, Some(100));
        assert_eq!(deserialized.on_decode_unmappable, UnmappablePolicy::Replace);
        assert_eq!(deserialized.threads, 4);
        assert!(deserialized.preserve_zoned_encoding);
        assert_eq!(
            deserialized.preferred_zoned_encoding,
            ZonedEncodingFormat::Ebcdic
        );
        assert_eq!(deserialized.float_format, FloatFormat::IbmHex);
    }

    #[test]
    fn test_decode_options_deserialize_missing_float_format_defaults() {
        let options = DecodeOptions::default();
        let mut value = serde_json::to_value(options).unwrap();
        value.as_object_mut().unwrap().remove("float_format");
        let deserialized: DecodeOptions = serde_json::from_value(value).unwrap();
        assert_eq!(deserialized.float_format, FloatFormat::IeeeBigEndian);
    }

    #[test]
    fn test_encode_options_deserialize_missing_float_format_defaults() {
        let options = EncodeOptions::default();
        let mut value = serde_json::to_value(options).unwrap();
        value.as_object_mut().unwrap().remove("float_format");
        let deserialized: EncodeOptions = serde_json::from_value(value).unwrap();
        assert_eq!(deserialized.float_format, FloatFormat::IeeeBigEndian);
    }
}