trash_parallelism 0.1.102

Azzybana Raccoon's comprehensive parallelism library.
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
//! Tests for the io module
use trash_parallelism::io::*;

#[test]
pub fn test_read_file_async() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        let content = "Test content for reading";

        std::fs::write(path, content).unwrap();

        let read_content = read_file_async(path).await.unwrap();
        assert_eq!(read_content, content);
    });
}

#[test]
pub fn test_write_file_async() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        let content = "Hello, async world!";

        write_file_async(path, content).await.unwrap();

        let read_content = std::fs::read_to_string(path).unwrap();
        assert_eq!(read_content, content);
    });
}

#[test]
pub fn test_compress_brotli() {
    let data = b"Hello, this is test data for compression!";
    let compressed = compress_brotli(data, 6).unwrap();
    assert!(!compressed.is_empty());
    // Note: compressed data might be larger than original for small inputs
}

#[test]
pub fn test_decompress_brotli() {
    let data = b"Hello, this is test data for compression!";
    let compressed = compress_brotli(data, 6).unwrap();
    let decompressed = decompress_brotli(&compressed).unwrap();
    assert_eq!(decompressed, data);
}

#[test]
pub fn test_atomic_counter() {
    let counter = AtomicCounter::new();
    assert_eq!(counter.get(), 0);

    assert_eq!(counter.increment(), 1);
    assert_eq!(counter.get(), 1);

    counter.reset();
    assert_eq!(counter.get(), 0);
}

#[test]
pub fn test_lru_cache() {
    let cache = LruCache::new(3);
    assert_eq!(cache.len(), 0);
    assert!(cache.is_empty());

    cache.insert(1, "value1");
    cache.insert(2, "value2");
    cache.insert(3, "value3");

    assert_eq!(cache.len(), 3);
    assert_eq!(cache.get(&1), Some("value1"));
    assert_eq!(cache.get(&2), Some("value2"));
    assert_eq!(cache.get(&3), Some("value3"));

    cache.clear();
    assert_eq!(cache.len(), 0);
    assert!(cache.is_empty());
}

#[test]
pub fn test_string_interner() {
    let interner = StringInterner::new();
    assert_eq!(interner.len(), 0);
    assert!(interner.is_empty());

    let s1 = interner.intern("hello");
    let s2 = interner.intern("hello");
    assert_eq!(interner.len(), 1);
    assert_eq!(s1.as_ptr(), s2.as_ptr()); // Same memory location

    let s3 = interner.intern("world");
    assert_eq!(interner.len(), 2);
    assert_ne!(s1.as_ptr(), s3.as_ptr());

    interner.clear();
    assert_eq!(interner.len(), 0);
    assert!(interner.is_empty());
}

#[test]
pub fn test_global_interner() {
    let interner = global_interner();
    let s1 = interner.intern("global_test");
    let s2 = interner.intern("global_test");
    assert_eq!(s1.as_ptr(), s2.as_ptr());
}

#[test]
pub fn test_parallel_map() {
    let data = vec![1, 2, 3, 4, 5];
    let result = parallelism::parallel_map(data, |x| x * 2);
    assert_eq!(result, vec![2, 4, 6, 8, 10]);
}

#[test]
pub fn test_parallel_filter() {
    let data = vec![1, 2, 3, 4, 5, 6];
    let evens = parallelism::parallel_filter(data, |x| x % 2 == 0);
    assert_eq!(evens, vec![2, 4, 6]);
}

#[test]
pub fn test_process_files_parallel() {
    // Would need temp files, but let's test the structure
    let paths = vec![
        "nonexistent1.txt".to_string(),
        "nonexistent2.txt".to_string(),
    ];
    let results = parallelism::process_files_parallel(paths, |content| Ok(content.len()));
    // Should return errors for nonexistent files
    assert_eq!(results.len(), 2);
    assert!(results[0].is_err());
    assert!(results[1].is_err());
}

#[test]
pub fn test_async_file_writer() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let mut writer = writers::AsyncFileWriter::new(path).await.unwrap();
        writer.write(b"Hello, ").await.unwrap();
        writer.write(b"world!").await.unwrap();
        writer.flush().await.unwrap();

        assert_eq!(writer.bytes_written(), 13);
        assert!(!writer.is_compressed());

        let content = std::fs::read(path).unwrap();
        assert_eq!(content, b"Hello, world!");
    });
}

#[test]
pub fn test_async_file_writer_compressed() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let mut writer = writers::AsyncFileWriter::with_config(path, 1024, true)
            .await
            .unwrap();
        writer
            .write_json(&serde_json::json!({"test": "data"}))
            .await
            .unwrap();
        writer.flush().await.unwrap();

        assert!(writer.is_compressed());
        assert!(writer.bytes_written() > 0);
    });
}

#[test]
pub fn test_streaming_file_writer() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let mut writer = writers::StreamingFileWriter::new(path, 1024, false)
            .await
            .unwrap();
        writer.write_chunk(b"Hello, ").await.unwrap();
        writer.write_chunk(b"world!").await.unwrap();

        assert_eq!(writer.bytes_written(), 13);
        assert_eq!(writer.chunk_size(), 1024);

        let content = std::fs::read(path).unwrap();
        assert_eq!(content, b"Hello, world!");
    });
}

#[test]
pub fn test_advanced_file_writer() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let mut writer = writers::AdvancedFileWriter::new(
            path,
            1024,
            false,
            Some(Box::new(|_| println!("Progress"))),
            false,
        )
        .await
        .unwrap();

        writer.write_with_progress(b"Hello, world!").await.unwrap();
        writer.flush().await.unwrap();

        assert_eq!(writer.bytes_written(), 13);
    });
}

#[test]
pub fn test_async_file_writer_with_config() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let mut writer = writers::AsyncFileWriter::with_config(path, 10, false)
            .await
            .unwrap();
        assert!(!writer.is_compressed());
        assert_eq!(writer.bytes_written(), 0);

        // Write data larger than buffer to trigger auto-flush
        writer
            .write(b"Hello, world! This is a longer message.")
            .await
            .unwrap();
        writer.flush().await.unwrap();

        assert_eq!(writer.bytes_written(), 39);

        let content = std::fs::read(path).unwrap();
        assert_eq!(content, b"Hello, world! This is a longer message.");
    });
}

#[test]
pub fn test_async_file_writer_write_json() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let mut writer = writers::AsyncFileWriter::new(path).await.unwrap();

        #[allow(clippy::items_after_statements)]
        #[derive(serde::Serialize)]
        struct TestData {
            name: String,
            value: i32,
        }

        let data = TestData {
            name: "test".to_string(),
            value: 42,
        };

        writer.write_json(&data).await.unwrap();
        writer.flush().await.unwrap();

        let content = std::fs::read_to_string(path).unwrap();
        assert!(content.contains("\"name\":\"test\""));
        assert!(content.contains("\"value\":42"));
    });
}

#[test]
pub fn test_async_file_writer_multiple_flushes() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let mut writer = writers::AsyncFileWriter::with_config(path, 5, false)
            .await
            .unwrap();

        writer.write(b"Hi").await.unwrap();
        writer.flush().await.unwrap();
        assert_eq!(writer.bytes_written(), 2);

        writer.write(b"Hello").await.unwrap();
        writer.flush().await.unwrap();
        assert_eq!(writer.bytes_written(), 7);

        let content = std::fs::read(path).unwrap();
        assert_eq!(content, b"HiHello");
    });
}

#[test]
pub fn test_streaming_file_writer_compressed() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let mut writer = writers::StreamingFileWriter::new(path, 1024, true)
            .await
            .unwrap();
        assert_eq!(writer.chunk_size(), 1024);

        writer
            .write_chunk(b"{\"data\": \"This is test data for compression\"}")
            .await
            .unwrap();
        assert!(writer.bytes_written() > 0); // Compressed data should be written

        // Since it's compressed, we can't easily check the content, but ensure bytes were written
        let content = std::fs::read(path).unwrap();
        assert!(!content.is_empty());
    });
}

#[test]
pub fn test_streaming_file_writer_large_chunk() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let mut writer = writers::StreamingFileWriter::new(path, 10, false)
            .await
            .unwrap();

        let large_data = b"This is a larger chunk of data that exceeds the chunk size setting.";
        writer.write_chunk(large_data).await.unwrap();

        assert_eq!(writer.bytes_written(), large_data.len() as u64);

        let content = std::fs::read(path).unwrap();
        assert_eq!(content, large_data);
    });
}

#[test]
pub fn test_advanced_file_writer_with_progress() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let progress_count = std::sync::Arc::new(std::sync::Mutex::new(0));
        let progress_clone = progress_count.clone();

        let mut writer = writers::AdvancedFileWriter::new(
            path,
            5, // Small buffer
            false,
            Some(Box::new(move |_| {
                let mut count = progress_clone.lock().unwrap();
                *count += 1;
            })),
            false,
        )
        .await
        .unwrap();

        writer
            .write_with_progress(b"Hello, world! This is longer.")
            .await
            .unwrap();
        writer.flush().await.unwrap();

        assert_eq!(writer.bytes_written(), 29);
        // Progress callback should have been called multiple times due to small buffer
        assert!(*progress_count.lock().unwrap() > 0);

        let content = std::fs::read(path).unwrap();
        assert_eq!(content, b"Hello, world! This is longer.");
    });
}

#[test]
pub fn test_advanced_file_writer_compressed() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let mut writer = writers::AdvancedFileWriter::new(
            path, 1024, true, // compressed
            None, false,
        )
        .await
        .unwrap();

        writer
            .write_with_progress(b"Repeated data for compression: test test test test")
            .await
            .unwrap();
        writer.flush().await.unwrap();

        assert!(writer.bytes_written() > 0);
        let content = std::fs::read(path).unwrap();
        assert!(!content.is_empty());
    });
}

#[test]
pub fn test_process_files_chunked() {
    smol::block_on(async {
        // Create temp file with test data
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap().to_string();
        std::fs::write(
            &path,
            b"Hello, world! This is test data for chunked processing.",
        )
        .unwrap();

        let paths = vec![path];
        let results = parallelism::process_files_chunked(paths, 10, |chunk| Ok(chunk.len())).await;

        assert_eq!(results.len(), 1);
        let chunks = &results[0];
        assert!(chunks.is_ok());
        let chunk_lengths = chunks.as_ref().unwrap();
        let total_len: usize = chunk_lengths.iter().sum();
        assert_eq!(total_len, 55); // Length of test data
    });
}

#[test]
pub fn test_traverse_and_process() {
    // Create temp directory with files
    let temp_dir = tempfile::TempDir::new().unwrap();
    let dir_path = temp_dir.path().to_str().unwrap();

    // Create some test files
    std::fs::write(format!("{dir_path}/file1.txt"), "content1").unwrap();
    std::fs::write(format!("{dir_path}/file2.txt"), "content2").unwrap();
    std::fs::create_dir(format!("{dir_path}/subdir")).unwrap();
    std::fs::write(format!("{dir_path}/subdir/file3.txt"), "content3").unwrap();

    let results =
        parallelism::traverse_and_process(dir_path, |_, content| Ok(content.len()), Some(2))
            .unwrap();

    // Should process 3 files
    assert_eq!(results.len(), 3);
    for result in results {
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 8); // "contentX".len()
    }
}

#[test]
pub fn test_batch_file_operations() {
    let operations = vec![
        || std::fs::write("temp_batch1.txt", "data1"),
        || std::fs::write("temp_batch2.txt", "data2"),
        || std::fs::write("temp_batch3.txt", "data3"),
    ];

    let result = parallelism::batch_file_operations(operations, false);
    assert!(result.is_ok());

    // Cleanup
    let _ = std::fs::remove_file("temp_batch1.txt");
    let _ = std::fs::remove_file("temp_batch2.txt");
    let _ = std::fs::remove_file("temp_batch3.txt");
}

#[test]
pub fn test_async_file_processor_process_file() {
    smol::block_on(async {
        // Create temp file
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        std::fs::write(path, b"Hello, world!").unwrap();

        let processor = streams::AsyncFileProcessor::new();
        let results = processor
            .process_file(path, |chunk| chunk.len())
            .await
            .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0], 13); // "Hello, world!".len()
    });
}

#[test]
pub fn test_async_file_processor_process_file_async() {
    smol::block_on(async {
        // Create temp file
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        std::fs::write(path, b"Hello, world!").unwrap();

        let processor = streams::AsyncFileProcessor::new();
        let results = processor
            .process_file_async(path, |chunk| async move { Ok(chunk.len()) })
            .await
            .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0], 13);
    });
}

#[test]
pub fn test_async_file_processor_with_progress_callback() {
    smol::block_on(async {
        // Create temp file
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        std::fs::write(path, b"Hello, world!").unwrap();

        let progress_called = std::sync::Arc::new(std::sync::Mutex::new(false));
        let progress_clone = progress_called.clone();

        let processor = streams::AsyncFileProcessor::with_config(
            4096,
            Some(Box::new(move |_| {
                *progress_clone.lock().unwrap() = true;
            })),
        );

        let results = processor
            .process_file(path, |chunk| chunk.len())
            .await
            .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0], 13);
        assert!(*progress_called.lock().unwrap());
    });
}

#[test]
pub fn test_async_file_processor_with_progress_callback_async() {
    smol::block_on(async {
        // Create temp file
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        std::fs::write(path, b"Hello, world!").unwrap();

        let progress_called = std::sync::Arc::new(std::sync::Mutex::new(false));
        let progress_clone = progress_called.clone();

        let processor = streams::AsyncFileProcessor::with_config(
            4096,
            Some(Box::new(move |_| {
                *progress_clone.lock().unwrap() = true;
            })),
        );

        let results = processor
            .process_file_async(path, |chunk| async move { Ok(chunk.len()) })
            .await
            .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0], 13);
        assert!(*progress_called.lock().unwrap());
    });
}

#[test]
pub fn test_async_file_processor_default() {
    smol::block_on(async {
        // Create temp file
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        std::fs::write(path, b"Hello, world!").unwrap();

        let processor = streams::AsyncFileProcessor::default();
        let results = processor
            .process_file(path, |chunk| chunk.len())
            .await
            .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0], 13);
    });
}

#[test]
pub fn test_async_file_processor_builder() {
    smol::block_on(async {
        // Create temp file
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        std::fs::write(path, b"Hello, world!").unwrap();

        let progress_called = std::sync::Arc::new(std::sync::Mutex::new(false));
        let progress_clone = progress_called.clone();

        let processor = streams::AsyncFileProcessor::builder()
            .buffer_size(1024)
            .progress_callback(move |_| {
                *progress_clone.lock().unwrap() = true;
            })
            .build();

        let results = processor
            .process_file(path, |chunk| chunk.len())
            .await
            .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0], 13);
        assert!(*progress_called.lock().unwrap());
    });
}

#[test]
pub fn test_process_file_async_function() {
    smol::block_on(async {
        // Create temp file
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        std::fs::write(path, b"Hello, world!").unwrap();

        let content_received = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
        let content_clone = content_received.clone();

        streams::process_file_async(path, move |content| {
            *content_clone.lock().unwrap() = content;
        })
        .await
        .unwrap();

        assert_eq!(*content_received.lock().unwrap(), "Hello, world!");
    });
}

#[test]
pub fn test_channel_stream_processor_start_background_processing() {
    smol::block_on(async {
        let counter = std::sync::Arc::new(std::sync::Mutex::new(0));
        let counter_clone = counter.clone();

        let processor = streams::ChannelStreamProcessor::new(move |x: i32| {
            *counter_clone.lock().unwrap() += x;
            x
        });

        processor.start_background_processing();

        processor.send(5).await.unwrap();
        processor.send(10).await.unwrap();

        // Give some time for background processing
        smol::Timer::after(std::time::Duration::from_millis(100)).await;

        // Since background processing just processes and drops, we can't check the result
        // But we can check that the processor was called by using a side effect
        // Wait a bit more
        smol::Timer::after(std::time::Duration::from_millis(100)).await;

        // The counter should have been incremented
        assert_eq!(*counter.lock().unwrap(), 15);
    });
}

#[test]
pub fn test_buffered_async_reader_eof() {
    smol::block_on(async {
        use futures_lite::io::Cursor;
        let data = b""; // Empty data to simulate EOF
        let cursor = Cursor::new(data.to_vec());
        let mut reader = streams::BufferedAsyncReader::new(cursor, 20);

        let buffer = reader.read_buffer().await.unwrap();
        assert_eq!(buffer.len(), 0);
    });
}

#[test]
pub fn test_buffered_async_reader_buffer_size() {
    smol::block_on(async {
        use futures_lite::io::Cursor;
        let data = b"Hello";
        let cursor = Cursor::new(data.to_vec());
        let reader = streams::BufferedAsyncReader::new(cursor, 42);

        assert_eq!(reader.buffer_size(), 42);
    });
}

#[test]
pub fn test_streaming_file_writer_write_from_stream() {
    smol::block_on(async {
        use bytes::Bytes;
        use futures_lite::stream;

        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let mut writer = writers::StreamingFileWriter::new(path, 1024, false)
            .await
            .unwrap();

        // Create a stream of Bytes
        let data_chunks = vec![
            Ok(Bytes::from("Hello, ")),
            Ok(Bytes::from("world! ")),
            Ok(Bytes::from("This is ")),
            Ok(Bytes::from("a test.")),
        ];
        let stream = stream::iter(data_chunks);

        writer.write_from_stream(stream).await.unwrap();

        let content = std::fs::read(path).unwrap();
        println!("Actual content: {:?}", String::from_utf8_lossy(&content));
        println!("Content length: {}", content.len());
        assert_eq!(writer.bytes_written(), content.len() as u64);

        assert_eq!(content, b"Hello, world! This is a test.");
    });
}

#[test]
pub fn test_advanced_file_writer_write_json_with_progress() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let progress_called = std::sync::Arc::new(std::sync::Mutex::new(false));
        let progress_clone = progress_called.clone();

        let mut writer = writers::AdvancedFileWriter::new(
            path,
            1024,
            false,
            Some(Box::new(move |_| {
                *progress_clone.lock().unwrap() = true;
            })),
            false,
        )
        .await
        .unwrap();

        #[allow(clippy::items_after_statements)]
        #[derive(serde::Serialize)]
        struct TestData {
            name: String,
            value: i32,
            items: Vec<String>,
        }

        let data = TestData {
            name: "test".to_string(),
            value: 42,
            items: vec!["item1".to_string(), "item2".to_string()],
        };

        writer.write_json_with_progress(&data).await.unwrap();
        writer.flush().await.unwrap();

        assert!(*progress_called.lock().unwrap());

        let content = std::fs::read_to_string(path).unwrap();
        assert!(content.contains("\"name\":\"test\""));
        assert!(content.contains("\"value\":42"));
        assert!(content.contains("\"items\":[\"item1\",\"item2\"]"));
    });
}

#[test]
pub fn test_write_stdout_async() {
    // Test that write_stdout_async doesn't panic and returns Ok
    let data = b"Hello, stdout!";
    let result = writers::write_stdout_async(data);
    assert!(result.is_ok());
}

#[test]
pub fn test_write_stderr_async() {
    // Test that write_stderr_async doesn't panic and returns Ok
    let data = b"Hello, stderr!";
    let result = writers::write_stderr_async(data);
    assert!(result.is_ok());
}

#[test]
pub fn test_advanced_file_writer_error_recovery() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let progress_called = std::sync::Arc::new(std::sync::Mutex::new(false));
        let progress_clone = progress_called.clone();

        let mut writer = writers::AdvancedFileWriter::new(
            path,
            1024,
            false,
            Some(Box::new(move |_| {
                *progress_clone.lock().unwrap() = true;
            })),
            true, // error_recovery enabled
        )
        .await
        .unwrap();

        writer.write_with_progress(b"Hello, world!").await.unwrap();
        writer.flush().await.unwrap();

        assert!(*progress_called.lock().unwrap());
        assert_eq!(writer.bytes_written(), 13);
    });
}

#[test]
pub fn test_async_file_writer_invalid_path() {
    smol::block_on(async {
        // Test creating a writer with an invalid path
        let result =
            writers::AsyncFileWriter::new("/invalid/path/that/does/not/exist/file.txt").await;
        assert!(result.is_err());
    });
}

#[test]
pub fn test_async_file_writer_write_json_invalid_data() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();

        let mut writer = writers::AsyncFileWriter::new(path).await.unwrap();

        // Try to serialize data that can't be serialized (this should work since most data can be serialized)
        // Actually, serde_json can serialize most things. Let's use a type that might fail.
        // For now, just test that valid data works and invalid paths fail
        // The serialization error would come from serde, which is tested elsewhere

        // Test with valid data
        #[allow(clippy::items_after_statements)]
        #[derive(serde::Serialize)]
        struct TestData {
            value: i32,
        }

        let data = TestData { value: 42 };
        let result = writer.write_json(&data).await;
        assert!(result.is_ok());
    });
}

#[test]
pub fn test_async_stream_utils() {
    smol::block_on(async {
        use futures_lite::stream;
        let stream = stream::iter(vec![1, 2, 3, 4, 5]);
        let results = streams::AsyncStreamUtils::map_stream(stream, |x| x * 2).await;
        assert_eq!(results, vec![2, 4, 6, 8, 10]);

        let stream2 = stream::iter(vec![1, 2, 3, 4, 5]);
        let filtered = streams::AsyncStreamUtils::filter_stream(stream2, |&x| x % 2 == 0).await;
        assert_eq!(filtered, vec![2, 4]);

        let stream3 = stream::iter(vec![1, 2, 3]);
        let collected = streams::AsyncStreamUtils::collect_stream(stream3).await;
        assert_eq!(collected, vec![1, 2, 3]);
    });
}

#[test]
pub fn test_channel_stream_processor_send_receive() {
    smol::block_on(async {
        let processor = streams::ChannelStreamProcessor::new(|x: i32| x * 2);
        processor.send(5).await.unwrap();
        let result = processor.receive().await.unwrap();
        assert_eq!(result, 10);
    });
}

#[test]
pub fn test_buffered_async_reader_read() {
    smol::block_on(async {
        use futures_lite::io::Cursor;
        let data = b"Hello, world!";
        let cursor = Cursor::new(data.to_vec());
        let mut reader = streams::BufferedAsyncReader::new(cursor, 20);

        let buffer = reader.read_buffer().await.unwrap();
        assert_eq!(buffer, b"Hello, world!");

        reader.consume(7); // consume "Hello, "

        let buffer2 = reader.read_buffer().await.unwrap();
        assert_eq!(buffer2, b"world!");
    });
}

#[test]
pub fn test_copy_file_async() {
    let temp_source = tempfile::NamedTempFile::new().unwrap();
    let temp_dest = tempfile::NamedTempFile::new().unwrap();
    let source_path = temp_source.path().to_str().unwrap();
    let dest_path = temp_dest.path().to_str().unwrap();
    let content = "Content to copy";

    std::fs::write(source_path, content).unwrap();

    let bytes_copied = copy_file_async(source_path, dest_path).unwrap();
    assert_eq!(bytes_copied, content.len() as u64);

    let copied_content = std::fs::read_to_string(dest_path).unwrap();
    assert_eq!(copied_content, content);
}

#[test]
pub fn test_write_file_bytes_async() {
    smol::block_on(async {
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_str().unwrap();
        let data = b"Hello, bytes world!";

        write_file_bytes_async(path, data).await.unwrap();

        let read_data = std::fs::read(path).unwrap();
        assert_eq!(read_data, data);
    });
}

#[test]
pub fn test_create_dir_async() {
    smol::block_on(async {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let base_path = temp_dir.path().to_str().unwrap();
        let new_dir_path = format!("{base_path}/new_test_dir");

        create_dir_async(&new_dir_path).await.unwrap();

        assert!(std::fs::metadata(&new_dir_path).unwrap().is_dir());
    });
}

#[test]
pub fn test_read_dir_async() {
    smol::block_on(async {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let dir_path = temp_dir.path().to_str().unwrap();

        // Create some test files
        std::fs::write(format!("{dir_path}/file1.txt"), "content1").unwrap();
        std::fs::write(format!("{dir_path}/file2.txt"), "content2").unwrap();

        let entries = read_dir_async(dir_path).await.unwrap();

        assert_eq!(entries.len(), 2);
        assert!(entries.contains(&"file1.txt".to_string()));
        assert!(entries.contains(&"file2.txt".to_string()));
    });
}

#[test]
pub fn test_atomic_counter_default() {
    let counter = AtomicCounter::default();
    assert_eq!(counter.get(), 0);
}

#[test]
pub fn test_string_interner_default() {
    let interner = StringInterner::default();
    assert_eq!(interner.len(), 0);
    assert!(interner.is_empty());
}

#[test]
pub fn test_io() {
    test_read_file_async();
    test_write_file_async();
    test_copy_file_async();
    test_write_file_bytes_async();
    test_create_dir_async();
    test_read_dir_async();
    test_atomic_counter_default();
    test_string_interner_default();
    test_compress_brotli();
    test_decompress_brotli();
    test_atomic_counter();
    test_lru_cache();
    test_string_interner();
    test_global_interner();
    test_parallel_map();
    test_parallel_filter();
    test_process_files_parallel();
    test_process_files_chunked();
    test_traverse_and_process();
    test_batch_file_operations();
    test_async_file_processor_process_file();
    test_async_file_processor_process_file_async();
    test_async_stream_utils();
    test_channel_stream_processor_send_receive();
    test_buffered_async_reader_read();
    test_async_file_writer();
    test_async_file_writer_compressed();
    test_streaming_file_writer();
    test_advanced_file_writer();
    test_async_file_writer_with_config();
    test_async_file_writer_write_json();
    test_async_file_writer_multiple_flushes();
    test_streaming_file_writer_compressed();
    test_streaming_file_writer_large_chunk();
    test_advanced_file_writer_with_progress();
    test_advanced_file_writer_compressed();
    test_async_file_processor_with_progress_callback();
    test_async_file_processor_with_progress_callback_async();
    test_async_file_processor_default();
    test_async_file_processor_builder();
    test_process_file_async_function();
    test_channel_stream_processor_start_background_processing();
    test_buffered_async_reader_eof();
    test_buffered_async_reader_buffer_size();
    test_streaming_file_writer_write_from_stream();
}