oxicode 0.2.1

A modern binary serialization library - successor to bincode
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
//! Advanced async streaming tests (24th set) for OxiCode.
//!
//! Theme: Financial transactions async streaming.
//!
//! All 22 tests are top-level `#[tokio::test]` functions (no module wrapper).
//! Gated by the `async-tokio` feature at the file level.
//!
//! Types: `TransactionType`, `Transaction`, `AccountSnapshot`.
//!
//! Coverage matrix:
//!   1:  Single Transaction deposit roundtrip
//!   2:  Single Transaction withdrawal roundtrip
//!   3:  Single Transaction transfer roundtrip
//!   4:  Single Transaction fee roundtrip
//!   5:  AccountSnapshot single roundtrip
//!   6:  Multiple Transactions streamed in order (5 items)
//!   7:  Multiple AccountSnapshots streamed in order (3 items)
//!   8:  Mixed Transaction and AccountSnapshot items in separate streams, verify consistency
//!   9:  Large batch of 200 Transactions via write_all, verify read_all
//!  10:  Progress tracking — items_processed > 0 after writing transactions
//!  11:  StreamingConfig with small chunk size forces multiple chunks
//!  12:  flush_per_item config writes each transaction as its own chunk
//!  13:  Empty stream — finish immediately, read_item returns None
//!  14:  Transaction with negative amount_cents (fee debit) roundtrip
//!  15:  AccountSnapshot with zero balance roundtrip
//!  16:  write_all with Vec<Transaction> owned iteration
//!  17:  write_all then read_all full roundtrip consistency
//!  18:  Sync encode / async decode interop for Transaction
//!  19:  Async encode / sync decode interop for AccountSnapshot
//!  20:  Items_processed >= N after writing N transactions
//!  21:  Decoder reports is_finished() after stream exhausted
//!  22:  bytes_processed grows as more transactions are decoded

#![cfg(feature = "async-tokio")]
#![allow(
    clippy::approx_constant,
    clippy::useless_vec,
    clippy::len_zero,
    clippy::unnecessary_cast,
    clippy::redundant_closure,
    clippy::too_many_arguments,
    clippy::type_complexity,
    clippy::needless_borrow,
    clippy::enum_variant_names,
    clippy::upper_case_acronyms,
    clippy::inconsistent_digit_grouping,
    clippy::unit_cmp,
    clippy::assertions_on_constants,
    clippy::iter_on_single_items,
    clippy::expect_fun_call,
    clippy::redundant_pattern_matching,
    variant_size_differences,
    clippy::absurd_extreme_comparisons,
    clippy::nonminimal_bool,
    clippy::for_kv_map,
    clippy::needless_range_loop,
    clippy::single_match,
    clippy::collapsible_if,
    clippy::needless_return,
    clippy::redundant_clone,
    clippy::map_entry,
    clippy::match_single_binding,
    clippy::bool_comparison,
    clippy::derivable_impls,
    clippy::manual_range_contains,
    clippy::needless_borrows_for_generic_args,
    clippy::manual_map,
    clippy::vec_init_then_push,
    clippy::identity_op,
    clippy::manual_flatten,
    clippy::single_char_pattern,
    clippy::search_is_some,
    clippy::option_map_unit_fn,
    clippy::while_let_on_iterator,
    clippy::clone_on_copy,
    clippy::box_collection,
    clippy::redundant_field_names,
    clippy::ptr_arg,
    clippy::large_enum_variant,
    clippy::match_ref_pats,
    clippy::needless_pass_by_value,
    clippy::unused_unit,
    clippy::let_and_return,
    clippy::suspicious_else_formatting,
    clippy::manual_strip,
    clippy::match_like_matches_macro,
    clippy::from_over_into,
    clippy::wrong_self_convention,
    clippy::inherent_to_string,
    clippy::new_without_default,
    clippy::unnecessary_wraps,
    clippy::field_reassign_with_default,
    clippy::manual_find,
    clippy::unnecessary_lazy_evaluations,
    clippy::should_implement_trait,
    clippy::missing_safety_doc,
    clippy::unusual_byte_groupings,
    clippy::bool_assert_comparison,
    clippy::zero_prefixed_literal,
    clippy::await_holding_lock,
    clippy::manual_saturating_arithmetic,
    clippy::explicit_counter_loop,
    clippy::needless_lifetimes,
    clippy::single_component_path_imports,
    clippy::uninlined_format_args,
    clippy::iter_cloned_collect,
    clippy::manual_str_repeat,
    clippy::excessive_precision,
    clippy::precedence,
    clippy::unnecessary_literal_unwrap
)]
use oxicode::async_tokio::{AsyncDecoder, AsyncEncoder, StreamingConfig};
use oxicode::{decode_from_slice, encode_to_vec, Decode, Encode};
use std::io::Cursor;
use tokio::io::BufReader;

// ---------------------------------------------------------------------------
// Domain types for financial transactions
// ---------------------------------------------------------------------------

#[derive(Debug, PartialEq, Clone, Encode, Decode)]
enum TransactionType {
    Deposit,
    Withdrawal,
    Transfer,
    Fee,
}

#[derive(Debug, PartialEq, Clone, Encode, Decode)]
struct Transaction {
    id: u64,
    tx_type: TransactionType,
    amount_cents: i64,
    account_id: u64,
}

#[derive(Debug, PartialEq, Clone, Encode, Decode)]
struct AccountSnapshot {
    account_id: u64,
    balance_cents: i64,
    tx_count: u32,
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

async fn encode_one<T: Encode>(item: &T) -> Vec<u8> {
    let mut buf = Vec::<u8>::new();
    {
        let cursor = Cursor::new(&mut buf);
        let mut enc = AsyncEncoder::new(cursor);
        enc.write_item(item)
            .await
            .expect("encode_one: write_item failed");
        enc.finish().await.expect("encode_one: finish failed");
    }
    buf
}

async fn decode_one<T: Decode>(buf: Vec<u8>) -> Option<T> {
    let cursor = Cursor::new(buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);
    dec.read_item::<T>()
        .await
        .expect("decode_one: read_item failed")
}

fn make_deposit(id: u64) -> Transaction {
    Transaction {
        id,
        tx_type: TransactionType::Deposit,
        amount_cents: 10_000,
        account_id: 1001,
    }
}

fn make_withdrawal(id: u64) -> Transaction {
    Transaction {
        id,
        tx_type: TransactionType::Withdrawal,
        amount_cents: -5_000,
        account_id: 1001,
    }
}

// ---------------------------------------------------------------------------
// Test 1: Single Transaction deposit roundtrip
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_single_deposit_roundtrip() {
    let original = Transaction {
        id: 1,
        tx_type: TransactionType::Deposit,
        amount_cents: 50_000,
        account_id: 2001,
    };
    let buf = encode_one(&original).await;
    let decoded = decode_one::<Transaction>(buf).await;
    assert_eq!(
        decoded,
        Some(original),
        "single deposit Transaction roundtrip failed"
    );
}

// ---------------------------------------------------------------------------
// Test 2: Single Transaction withdrawal roundtrip
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_single_withdrawal_roundtrip() {
    let original = Transaction {
        id: 2,
        tx_type: TransactionType::Withdrawal,
        amount_cents: -20_000,
        account_id: 2002,
    };
    let buf = encode_one(&original).await;
    let decoded = decode_one::<Transaction>(buf).await;
    assert_eq!(
        decoded,
        Some(original),
        "single withdrawal Transaction roundtrip failed"
    );
}

// ---------------------------------------------------------------------------
// Test 3: Single Transaction transfer roundtrip
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_single_transfer_roundtrip() {
    let original = Transaction {
        id: 3,
        tx_type: TransactionType::Transfer,
        amount_cents: 75_000,
        account_id: 3003,
    };
    let buf = encode_one(&original).await;
    let decoded = decode_one::<Transaction>(buf).await;
    assert_eq!(
        decoded,
        Some(original),
        "single transfer Transaction roundtrip failed"
    );
}

// ---------------------------------------------------------------------------
// Test 4: Single Transaction fee roundtrip
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_single_fee_roundtrip() {
    let original = Transaction {
        id: 4,
        tx_type: TransactionType::Fee,
        amount_cents: -250,
        account_id: 4004,
    };
    let buf = encode_one(&original).await;
    let decoded = decode_one::<Transaction>(buf).await;
    assert_eq!(
        decoded,
        Some(original),
        "single fee Transaction roundtrip failed"
    );
}

// ---------------------------------------------------------------------------
// Test 5: AccountSnapshot single roundtrip
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_account_snapshot_single_roundtrip() {
    let original = AccountSnapshot {
        account_id: 9001,
        balance_cents: 1_234_567,
        tx_count: 42,
    };
    let buf = encode_one(&original).await;
    let decoded = decode_one::<AccountSnapshot>(buf).await;
    assert_eq!(
        decoded,
        Some(original),
        "AccountSnapshot single roundtrip failed"
    );
}

// ---------------------------------------------------------------------------
// Test 6: Multiple Transactions streamed in order (5 items)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_five_transactions_in_order() {
    let transactions = vec![
        Transaction {
            id: 10,
            tx_type: TransactionType::Deposit,
            amount_cents: 100_000,
            account_id: 5001,
        },
        Transaction {
            id: 11,
            tx_type: TransactionType::Withdrawal,
            amount_cents: -30_000,
            account_id: 5001,
        },
        Transaction {
            id: 12,
            tx_type: TransactionType::Transfer,
            amount_cents: 20_000,
            account_id: 5001,
        },
        Transaction {
            id: 13,
            tx_type: TransactionType::Fee,
            amount_cents: -100,
            account_id: 5001,
        },
        Transaction {
            id: 14,
            tx_type: TransactionType::Deposit,
            amount_cents: 500_000,
            account_id: 5001,
        },
    ];

    let mut buf = Vec::<u8>::new();
    {
        let cursor = Cursor::new(&mut buf);
        let mut enc = AsyncEncoder::new(cursor);
        for tx in &transactions {
            enc.write_item(tx).await.expect("write Transaction failed");
        }
        enc.finish().await.expect("finish failed");
    }

    let cursor = Cursor::new(buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);

    for expected in &transactions {
        let item: Option<Transaction> = dec.read_item().await.expect("read Transaction failed");
        assert_eq!(
            item.as_ref(),
            Some(expected),
            "Transaction mismatch at id {}",
            expected.id
        );
    }

    let eof: Option<Transaction> = dec.read_item().await.expect("eof read failed");
    assert_eq!(eof, None, "expected None after all transactions");
}

// ---------------------------------------------------------------------------
// Test 7: Multiple AccountSnapshots streamed in order (3 items)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_three_snapshots_in_order() {
    let snapshots = vec![
        AccountSnapshot {
            account_id: 100,
            balance_cents: 500_000,
            tx_count: 10,
        },
        AccountSnapshot {
            account_id: 200,
            balance_cents: 250_000,
            tx_count: 5,
        },
        AccountSnapshot {
            account_id: 300,
            balance_cents: 0,
            tx_count: 0,
        },
    ];

    let mut buf = Vec::<u8>::new();
    {
        let cursor = Cursor::new(&mut buf);
        let mut enc = AsyncEncoder::new(cursor);
        for snap in &snapshots {
            enc.write_item(snap)
                .await
                .expect("write AccountSnapshot failed");
        }
        enc.finish().await.expect("finish failed");
    }

    let cursor = Cursor::new(buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);

    for expected in &snapshots {
        let item: Option<AccountSnapshot> =
            dec.read_item().await.expect("read AccountSnapshot failed");
        assert_eq!(
            item.as_ref(),
            Some(expected),
            "AccountSnapshot mismatch at account_id {}",
            expected.account_id
        );
    }
}

// ---------------------------------------------------------------------------
// Test 8: Mixed types in separate streams, verify consistency via sync encode
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_mixed_types_separate_streams_consistent() {
    let tx = Transaction {
        id: 99,
        tx_type: TransactionType::Transfer,
        amount_cents: 12_345,
        account_id: 7777,
    };
    let snap = AccountSnapshot {
        account_id: 7777,
        balance_cents: 12_345,
        tx_count: 1,
    };

    // Verify async and sync encoding produce decodable equivalents
    let tx_buf = encode_one(&tx).await;
    let snap_buf = encode_one(&snap).await;

    let decoded_tx = decode_one::<Transaction>(tx_buf).await;
    let decoded_snap = decode_one::<AccountSnapshot>(snap_buf).await;

    assert_eq!(
        decoded_tx,
        Some(tx.clone()),
        "Transaction async roundtrip mismatch"
    );
    assert_eq!(
        decoded_snap,
        Some(snap.clone()),
        "AccountSnapshot async roundtrip mismatch"
    );

    // Also verify sync encode/decode are consistent
    let sync_tx_bytes = encode_to_vec(&tx).expect("sync encode Transaction failed");
    let (sync_tx_decoded, _): (Transaction, _) =
        decode_from_slice(&sync_tx_bytes).expect("sync decode Transaction failed");
    assert_eq!(sync_tx_decoded, tx, "sync Transaction roundtrip mismatch");

    let sync_snap_bytes = encode_to_vec(&snap).expect("sync encode AccountSnapshot failed");
    let (sync_snap_decoded, _): (AccountSnapshot, _) =
        decode_from_slice(&sync_snap_bytes).expect("sync decode AccountSnapshot failed");
    assert_eq!(
        sync_snap_decoded, snap,
        "sync AccountSnapshot roundtrip mismatch"
    );
}

// ---------------------------------------------------------------------------
// Test 9: Large batch of 200 Transactions via write_all, verify read_all
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_large_batch_200_transactions_write_all_read_all() {
    let transactions: Vec<Transaction> = (0u64..200)
        .map(|i| Transaction {
            id: i,
            tx_type: if i % 4 == 0 {
                TransactionType::Deposit
            } else if i % 4 == 1 {
                TransactionType::Withdrawal
            } else if i % 4 == 2 {
                TransactionType::Transfer
            } else {
                TransactionType::Fee
            },
            amount_cents: (i as i64) * 100,
            account_id: 8000 + (i % 10),
        })
        .collect();

    let mut buf = Vec::<u8>::new();
    {
        let cursor = Cursor::new(&mut buf);
        let mut enc = AsyncEncoder::new(cursor);
        enc.write_all(transactions.clone())
            .await
            .expect("write_all 200 transactions failed");
        enc.finish().await.expect("finish failed");
    }

    let cursor = Cursor::new(buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);
    let decoded: Vec<Transaction> = dec
        .read_all()
        .await
        .expect("read_all 200 transactions failed");

    assert_eq!(decoded.len(), 200, "expected 200 decoded transactions");
    assert_eq!(decoded, transactions, "large batch roundtrip mismatch");
}

// ---------------------------------------------------------------------------
// Test 10: Progress tracking — items_processed > 0 after writing transactions
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_progress_items_processed_after_transactions() {
    let transactions: Vec<Transaction> = (0u64..8).map(make_deposit).collect();

    let mut buf = Vec::<u8>::new();
    {
        let cursor = Cursor::new(&mut buf);
        let mut enc = AsyncEncoder::new(cursor);
        for tx in transactions.clone() {
            enc.write_item(&tx).await.expect("write_item failed");
        }
        enc.finish().await.expect("finish failed");
    }

    let cursor = Cursor::new(buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);
    let _: Vec<Transaction> = dec.read_all().await.expect("read_all failed");

    assert!(
        dec.progress().items_processed > 0,
        "items_processed must be > 0 after reading transactions"
    );
    assert_eq!(
        dec.progress().items_processed,
        8,
        "items_processed must equal 8"
    );
}

// ---------------------------------------------------------------------------
// Test 11: StreamingConfig with small chunk size forces multiple chunks
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_small_chunk_size_forces_multiple_chunks() {
    // Use minimum chunk size (1024 bytes) with 500 transactions (~10 bytes each)
    // — 500 × ~10 = ~5000 bytes, forcing ~5 chunks of ~1024 bytes.
    let config = StreamingConfig::new().with_chunk_size(1024);
    let transactions: Vec<Transaction> = (0u64..500)
        .map(|i| Transaction {
            id: i,
            tx_type: TransactionType::Deposit,
            amount_cents: (i as i64) * 1000,
            account_id: 1000 + i,
        })
        .collect();

    let mut buf = Vec::<u8>::new();
    {
        let cursor = Cursor::new(&mut buf);
        let mut enc = AsyncEncoder::with_config(cursor, config);
        for tx in &transactions {
            enc.write_item(tx).await.expect("write_item failed");
        }
        enc.finish().await.expect("finish failed");
    }

    let cursor = Cursor::new(buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);
    let decoded: Vec<Transaction> = dec.read_all().await.expect("read_all failed");

    assert_eq!(decoded.len(), 500, "must decode 500 transactions");
    assert_eq!(decoded, transactions, "small-chunk roundtrip mismatch");
    assert!(
        dec.progress().chunks_processed > 1,
        "expected multiple chunks with 1024-byte chunk size and 500 transactions (got {} chunks)",
        dec.progress().chunks_processed
    );
}

// ---------------------------------------------------------------------------
// Test 12: flush_per_item config writes each transaction as its own chunk
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_flush_per_item_config() {
    let config = StreamingConfig::new().with_flush_per_item(true);
    let transactions: Vec<Transaction> = (0u64..5).map(make_deposit).collect();

    let mut buf = Vec::<u8>::new();
    {
        let cursor = Cursor::new(&mut buf);
        let mut enc = AsyncEncoder::with_config(cursor, config);
        for tx in &transactions {
            enc.write_item(tx)
                .await
                .expect("write_item (flush_per_item) failed");
        }
        enc.finish().await.expect("finish failed");
    }

    let cursor = Cursor::new(buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);
    let decoded: Vec<Transaction> = dec.read_all().await.expect("read_all failed");

    assert_eq!(decoded, transactions, "flush_per_item roundtrip mismatch");
    // With flush_per_item, each item is its own chunk — expect 5 chunks
    assert_eq!(
        dec.progress().chunks_processed,
        5,
        "flush_per_item must produce one chunk per transaction"
    );
}

// ---------------------------------------------------------------------------
// Test 13: Empty stream — finish immediately, read_item returns None
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_empty_stream_returns_none() {
    let mut buf = Vec::<u8>::new();
    {
        let cursor = Cursor::new(&mut buf);
        let enc = AsyncEncoder::new(cursor);
        enc.finish().await.expect("finish empty stream failed");
    }

    let cursor = Cursor::new(buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);

    let item: Option<Transaction> = dec
        .read_item()
        .await
        .expect("read_item from empty stream failed");
    assert_eq!(
        item, None,
        "empty stream must return None on first read_item"
    );
    assert!(
        dec.is_finished(),
        "decoder must report finished for empty stream"
    );
}

// ---------------------------------------------------------------------------
// Test 14: Transaction with negative amount_cents (fee debit) roundtrip
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_negative_amount_cents_roundtrip() {
    let original = Transaction {
        id: 500,
        tx_type: TransactionType::Fee,
        amount_cents: i64::MIN / 2,
        account_id: 6006,
    };
    let buf = encode_one(&original).await;
    let decoded = decode_one::<Transaction>(buf).await;
    assert_eq!(
        decoded,
        Some(original),
        "negative amount_cents Transaction roundtrip failed"
    );
}

// ---------------------------------------------------------------------------
// Test 15: AccountSnapshot with zero balance roundtrip
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_zero_balance_snapshot_roundtrip() {
    let original = AccountSnapshot {
        account_id: 0,
        balance_cents: 0,
        tx_count: 0,
    };
    let buf = encode_one(&original).await;
    let decoded = decode_one::<AccountSnapshot>(buf).await;
    assert_eq!(
        decoded,
        Some(original),
        "zero-balance AccountSnapshot roundtrip failed"
    );
}

// ---------------------------------------------------------------------------
// Test 16: write_all with Vec<Transaction> owned iteration
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_write_all_owned_vec_iteration() {
    let transactions: Vec<Transaction> = (0u64..6)
        .map(|i| Transaction {
            id: i,
            tx_type: TransactionType::Transfer,
            amount_cents: (i as i64 + 1) * 999,
            account_id: 2000 + i,
        })
        .collect();

    // Clone before passing to write_all (which consumes the iterator)
    let expected = transactions.clone();

    let mut buf = Vec::<u8>::new();
    {
        let cursor = Cursor::new(&mut buf);
        let mut enc = AsyncEncoder::new(cursor);
        enc.write_all(transactions)
            .await
            .expect("write_all owned Vec failed");
        enc.finish().await.expect("finish failed");
    }

    let cursor = Cursor::new(buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);
    let decoded: Vec<Transaction> = dec.read_all().await.expect("read_all failed");

    assert_eq!(
        decoded, expected,
        "write_all owned iteration roundtrip mismatch"
    );
}

// ---------------------------------------------------------------------------
// Test 17: write_all then read_all full roundtrip consistency
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_write_all_read_all_full_roundtrip() {
    let transactions: Vec<Transaction> = vec![
        make_deposit(1),
        make_withdrawal(2),
        Transaction {
            id: 3,
            tx_type: TransactionType::Fee,
            amount_cents: -50,
            account_id: 1001,
        },
    ];
    let expected = transactions.clone();

    let mut buf = Vec::<u8>::new();
    {
        let cursor = Cursor::new(&mut buf);
        let mut enc = AsyncEncoder::new(cursor);
        enc.write_all(transactions).await.expect("write_all failed");
        enc.finish().await.expect("finish failed");
    }

    let cursor = Cursor::new(buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);
    let decoded: Vec<Transaction> = dec.read_all().await.expect("read_all failed");

    assert_eq!(
        decoded, expected,
        "write_all/read_all full roundtrip mismatch"
    );
    assert!(
        dec.progress().items_processed >= 3,
        "items_processed must be >= 3 after reading 3 transactions"
    );
}

// ---------------------------------------------------------------------------
// Test 18: Sync encode / async decode interop for Transaction
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_sync_encode_async_decode_interop_transaction() {
    let original = Transaction {
        id: 777,
        tx_type: TransactionType::Deposit,
        amount_cents: 999_999,
        account_id: 5555,
    };

    // Async-encode, then async-decode
    let async_buf = encode_one(&original).await;
    let cursor = Cursor::new(async_buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);
    let async_decoded: Option<Transaction> =
        dec.read_item().await.expect("async decode interop failed");
    assert_eq!(
        async_decoded,
        Some(original.clone()),
        "sync-encode/async-decode interop mismatch"
    );

    // Verify sync roundtrip of same value is consistent
    let sync_bytes = encode_to_vec(&original).expect("sync encode Transaction failed");
    let (sync_decoded, _): (Transaction, _) =
        decode_from_slice(&sync_bytes).expect("sync decode Transaction failed");
    assert_eq!(
        sync_decoded, original,
        "sync Transaction roundtrip consistency check failed"
    );
}

// ---------------------------------------------------------------------------
// Test 19: Async encode / sync decode interop for AccountSnapshot
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_async_encode_sync_decode_interop_snapshot() {
    let original = AccountSnapshot {
        account_id: 4321,
        balance_cents: 87_654,
        tx_count: 99,
    };

    // Encode via async, then decode via sync for consistency comparison
    let async_buf = encode_one(&original).await;
    let async_decoded = decode_one::<AccountSnapshot>(async_buf).await;
    assert_eq!(
        async_decoded,
        Some(original.clone()),
        "async encode/decode for AccountSnapshot failed"
    );

    // Sync encode and decode the same value
    let sync_bytes = encode_to_vec(&original).expect("sync encode AccountSnapshot failed");
    let (sync_decoded, _): (AccountSnapshot, _) =
        decode_from_slice(&sync_bytes).expect("sync decode AccountSnapshot failed");
    assert_eq!(
        sync_decoded, original,
        "async/sync interop: AccountSnapshot sync roundtrip mismatch"
    );
}

// ---------------------------------------------------------------------------
// Test 20: items_processed >= N after writing N transactions
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_items_processed_at_least_n_after_n_writes() {
    let n: u64 = 12;
    let transactions: Vec<Transaction> = (0..n).map(make_deposit).collect();

    let mut buf = Vec::<u8>::new();
    {
        let cursor = Cursor::new(&mut buf);
        let mut enc = AsyncEncoder::new(cursor);
        for tx in &transactions {
            enc.write_item(tx).await.expect("write_item failed");
        }
        enc.finish().await.expect("finish failed");
    }

    let cursor = Cursor::new(buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);
    let _: Vec<Transaction> = dec.read_all().await.expect("read_all failed");

    assert!(
        dec.progress().items_processed >= n,
        "items_processed ({}) must be >= {} after writing {} transactions",
        dec.progress().items_processed,
        n,
        n
    );
}

// ---------------------------------------------------------------------------
// Test 21: Decoder reports is_finished() after stream exhausted
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_decoder_is_finished_after_stream_exhausted() {
    let transactions = vec![make_deposit(1), make_withdrawal(2)];

    let mut buf = Vec::<u8>::new();
    {
        let cursor = Cursor::new(&mut buf);
        let mut enc = AsyncEncoder::new(cursor);
        for tx in &transactions {
            enc.write_item(tx).await.expect("write_item failed");
        }
        enc.finish().await.expect("finish failed");
    }

    let cursor = Cursor::new(buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);

    // Not yet finished
    assert!(
        !dec.is_finished(),
        "decoder should not be finished before reading"
    );

    // Read both items
    let _: Option<Transaction> = dec.read_item().await.expect("read item 1 failed");
    let _: Option<Transaction> = dec.read_item().await.expect("read item 2 failed");

    // Read past end
    let eof: Option<Transaction> = dec.read_item().await.expect("eof read failed");
    assert_eq!(eof, None, "expected None at end of stream");
    assert!(
        dec.is_finished(),
        "decoder must report is_finished() after stream exhausted"
    );
}

// ---------------------------------------------------------------------------
// Test 22: bytes_processed grows as more transactions are decoded
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_fin24_bytes_processed_grows_with_more_transactions() {
    let transactions: Vec<Transaction> = (0u64..15)
        .map(|i| Transaction {
            id: i,
            tx_type: TransactionType::Withdrawal,
            amount_cents: -((i as i64 + 1) * 500),
            account_id: 3000 + i,
        })
        .collect();

    let mut buf = Vec::<u8>::new();
    {
        let cursor = Cursor::new(&mut buf);
        let mut enc = AsyncEncoder::new(cursor);
        enc.write_all(transactions.clone())
            .await
            .expect("write_all failed");
        enc.finish().await.expect("finish failed");
    }

    let cursor = Cursor::new(buf);
    let buf_reader = BufReader::new(cursor);
    let mut dec = AsyncDecoder::new(buf_reader);

    // Read first item
    let first: Option<Transaction> = dec
        .read_item()
        .await
        .expect("read first transaction failed");
    assert_eq!(
        first.as_ref(),
        Some(&transactions[0]),
        "first decoded transaction mismatch"
    );

    let bytes_after_one = dec.progress().bytes_processed;
    assert!(
        bytes_after_one > 0,
        "bytes_processed must be > 0 after reading first transaction"
    );

    // Read remaining 14 items
    let rest: Vec<Transaction> = dec
        .read_all()
        .await
        .expect("read_all remaining transactions failed");
    assert_eq!(rest.len(), 14, "must decode 14 remaining transactions");

    let bytes_after_all = dec.progress().bytes_processed;
    assert!(
        bytes_after_all > bytes_after_one,
        "bytes_processed must grow after reading all transactions (was {bytes_after_one}, now {bytes_after_all})"
    );

    assert!(
        dec.progress().items_processed >= 15,
        "items_processed must be >= 15 after reading all transactions"
    );
}