ipfrs-core 0.2.0

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

use crate::{Block, Cid, CidBuilder, HashAlgorithm, Ipld, Result};
use bytes::Bytes;
use std::collections::BTreeMap;

/// Creates a block from a byte slice using default settings (SHA2-256, CIDv1, raw codec).
///
/// This is a convenience function that combines data conversion and block creation.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::quick_block;
///
/// let block = quick_block(b"Hello, IPFRS!").unwrap();
/// assert_eq!(block.data().as_ref(), b"Hello, IPFRS!");
/// ```
pub fn quick_block(data: &[u8]) -> Result<Block> {
    Block::new(Bytes::copy_from_slice(data))
}

/// Creates a block with a specific hash algorithm.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::{utils::block_with_hash, HashAlgorithm};
///
/// let block = block_with_hash(b"data", HashAlgorithm::Sha3_256).unwrap();
/// ```
pub fn block_with_hash(data: &[u8], algorithm: HashAlgorithm) -> Result<Block> {
    crate::BlockBuilder::new()
        .hash_algorithm(algorithm)
        .build_from_slice(data)
}

/// Parses a CID from a string with automatic multibase detection.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::parse_cid_string;
///
/// // Parse CIDv0 (base58btc)
/// let cid_v0 = parse_cid_string("QmXXX...");
///
/// // Parse CIDv1 (base32)
/// let cid_v1 = parse_cid_string("bafyXXX...");
/// ```
pub fn parse_cid_string(s: &str) -> Result<Cid> {
    crate::cid::parse_cid(s)
}

/// Computes the CID of data using the specified hash algorithm.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::{utils::cid_of, HashAlgorithm};
///
/// let cid = cid_of(b"Hello, World!", HashAlgorithm::Sha256).unwrap();
/// ```
pub fn cid_of(data: &[u8], algorithm: HashAlgorithm) -> Result<Cid> {
    CidBuilder::new().hash_algorithm(algorithm).build(data)
}

/// Computes a SHA2-256 CID (most common).
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::sha256_cid;
///
/// let cid = sha256_cid(b"Hello, World!").unwrap();
/// ```
pub fn sha256_cid(data: &[u8]) -> Result<Cid> {
    cid_of(data, HashAlgorithm::Sha256)
}

/// Computes a SHA3-256 CID.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::sha3_cid;
///
/// let cid = sha3_cid(b"Hello, World!").unwrap();
/// ```
pub fn sha3_cid(data: &[u8]) -> Result<Cid> {
    cid_of(data, HashAlgorithm::Sha3_256)
}

/// Computes a SHA2-512 CID (64-byte hash).
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::sha512_cid;
///
/// let cid = sha512_cid(b"Hello, World!").unwrap();
/// ```
pub fn sha512_cid(data: &[u8]) -> Result<Cid> {
    cid_of(data, HashAlgorithm::Sha512)
}

/// Computes a SHA3-512 CID (64-byte Keccak hash).
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::sha3_512_cid;
///
/// let cid = sha3_512_cid(b"Hello, World!").unwrap();
/// ```
pub fn sha3_512_cid(data: &[u8]) -> Result<Cid> {
    cid_of(data, HashAlgorithm::Sha3_512)
}

/// Computes a BLAKE2b-256 CID (fast, 32-byte hash).
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::blake2b256_cid;
///
/// let cid = blake2b256_cid(b"Hello, World!").unwrap();
/// ```
pub fn blake2b256_cid(data: &[u8]) -> Result<Cid> {
    cid_of(data, HashAlgorithm::Blake2b256)
}

/// Computes a BLAKE2b-512 CID (fast, 64-byte hash).
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::blake2b512_cid;
///
/// let cid = blake2b512_cid(b"Hello, World!").unwrap();
/// ```
pub fn blake2b512_cid(data: &[u8]) -> Result<Cid> {
    cid_of(data, HashAlgorithm::Blake2b512)
}

/// Computes a BLAKE2s-256 CID (fast, optimized for 8-32 bit platforms).
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::blake2s256_cid;
///
/// let cid = blake2s256_cid(b"Hello, World!").unwrap();
/// ```
pub fn blake2s256_cid(data: &[u8]) -> Result<Cid> {
    cid_of(data, HashAlgorithm::Blake2s256)
}

/// Computes a BLAKE3 CID (fastest, modern cryptographic design).
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::blake3_cid;
///
/// let cid = blake3_cid(b"Hello, World!").unwrap();
/// ```
pub fn blake3_cid(data: &[u8]) -> Result<Cid> {
    cid_of(data, HashAlgorithm::Blake3)
}

/// Checks if two blocks have the same CID (content equality).
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::{utils::quick_block, utils::blocks_equal};
///
/// let block1 = quick_block(b"data").unwrap();
/// let block2 = quick_block(b"data").unwrap();
/// assert!(blocks_equal(&block1, &block2));
/// ```
pub fn blocks_equal(a: &Block, b: &Block) -> bool {
    a.cid() == b.cid()
}

/// Verifies that a block's CID matches its content.
///
/// Returns true if the block is valid, false otherwise.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::{quick_block, verify_block};
///
/// let block = quick_block(b"Hello").unwrap();
/// assert!(verify_block(&block).unwrap());
/// ```
pub fn verify_block(block: &Block) -> Result<bool> {
    block.verify()
}

/// Creates an IPLD map from key-value pairs.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::{utils::ipld_map, Ipld};
///
/// let map = ipld_map(vec![
///     ("name", Ipld::String("Alice".to_string())),
///     ("age", Ipld::Integer(30)),
/// ]);
/// ```
pub fn ipld_map<K: Into<String>>(pairs: Vec<(K, Ipld)>) -> Ipld {
    let mut map = BTreeMap::new();
    for (k, v) in pairs {
        map.insert(k.into(), v);
    }
    Ipld::Map(map)
}

/// Creates an IPLD list from values.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::{utils::ipld_list, Ipld};
///
/// let list = ipld_list(vec![
///     Ipld::Integer(1),
///     Ipld::Integer(2),
///     Ipld::Integer(3),
/// ]);
/// ```
pub fn ipld_list(values: Vec<Ipld>) -> Ipld {
    Ipld::List(values)
}

/// Encodes IPLD data to DAG-CBOR bytes.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::{utils::ipld_to_cbor, Ipld};
///
/// let ipld = Ipld::String("hello".to_string());
/// let cbor = ipld_to_cbor(&ipld).unwrap();
/// ```
pub fn ipld_to_cbor(ipld: &Ipld) -> Result<Vec<u8>> {
    ipld.to_dag_cbor()
}

/// Decodes IPLD data from DAG-CBOR bytes.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::{utils::{ipld_to_cbor, ipld_from_cbor}, Ipld};
///
/// let ipld = Ipld::String("hello".to_string());
/// let cbor = ipld_to_cbor(&ipld).unwrap();
/// let decoded = ipld_from_cbor(&cbor).unwrap();
/// assert_eq!(ipld, decoded);
/// ```
pub fn ipld_from_cbor(data: &[u8]) -> Result<Ipld> {
    Ipld::from_dag_cbor(data)
}

/// Encodes IPLD data to DAG-JSON string.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::{utils::ipld_to_json, Ipld};
///
/// let ipld = Ipld::String("hello".to_string());
/// let json = ipld_to_json(&ipld).unwrap();
/// ```
pub fn ipld_to_json(ipld: &Ipld) -> Result<String> {
    ipld.to_dag_json()
}

/// Decodes IPLD data from DAG-JSON string.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::{utils::{ipld_to_json, ipld_from_json}, Ipld};
///
/// let ipld = Ipld::String("hello".to_string());
/// let json = ipld_to_json(&ipld).unwrap();
/// let decoded = ipld_from_json(&json).unwrap();
/// assert_eq!(ipld, decoded);
/// ```
pub fn ipld_from_json(data: &str) -> Result<Ipld> {
    Ipld::from_dag_json(data)
}

/// Formats a block size in human-readable format (KB, MB, GB).
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::format_size;
///
/// assert_eq!(format_size(1024), "1.00 KB");
/// assert_eq!(format_size(1_048_576), "1.00 MB");
/// assert_eq!(format_size(1_073_741_824), "1.00 GB");
/// ```
pub fn format_size(bytes: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    const GB: u64 = MB * 1024;

    if bytes >= GB {
        format!("{:.2} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.2} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.2} KB", bytes as f64 / KB as f64)
    } else {
        format!("{} B", bytes)
    }
}

/// Estimates the number of chunks needed for data of the given size.
///
/// Uses the default chunk size (256 KB).
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::estimate_chunks;
///
/// assert_eq!(estimate_chunks(1_000_000), 4); // ~1 MB → 4 chunks
/// ```
pub fn estimate_chunks(data_size: u64) -> usize {
    const DEFAULT_CHUNK_SIZE: u64 = 256 * 1024; // 256 KB
    data_size.div_ceil(DEFAULT_CHUNK_SIZE) as usize
}

/// Checks if data needs chunking based on the maximum block size.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::needs_chunking;
///
/// assert!(!needs_chunking(100)); // Small data
/// assert!(needs_chunking(3_000_000)); // Large data (> 2 MiB)
/// ```
pub fn needs_chunking(data_size: u64) -> bool {
    data_size > crate::MAX_BLOCK_SIZE as u64
}

//
// Diagnostic and Validation Utilities
//

/// Information about a CID for diagnostic purposes.
#[derive(Debug, Clone)]
pub struct CidInfo {
    /// CID string representation
    pub cid_string: String,
    /// CID version (0 or 1)
    pub version: u8,
    /// Codec identifier
    pub codec: u64,
    /// Hash algorithm code
    pub hash_code: u64,
    /// Hash digest length in bytes
    pub hash_length: usize,
}

impl std::fmt::Display for CidInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "CID: {}\n  Version: {}\n  Codec: 0x{:x}\n  Hash: 0x{:x} ({} bytes)",
            self.cid_string, self.version, self.codec, self.hash_code, self.hash_length
        )
    }
}

/// Inspects a CID and returns detailed diagnostic information.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::{sha256_cid, inspect_cid};
///
/// let cid = sha256_cid(b"Hello").unwrap();
/// let info = inspect_cid(&cid);
/// println!("{}", info);
/// ```
pub fn inspect_cid(cid: &Cid) -> CidInfo {
    CidInfo {
        cid_string: cid.to_string(),
        version: match cid.version() {
            cid::Version::V0 => 0,
            cid::Version::V1 => 1,
        },
        codec: cid.codec(),
        hash_code: cid.hash().code(),
        hash_length: cid.hash().digest().len(),
    }
}

/// Information about a block for diagnostic purposes.
#[derive(Debug, Clone)]
pub struct BlockInfo {
    /// Block's CID
    pub cid: String,
    /// Block size in bytes
    pub size: u64,
    /// Human-readable size
    pub size_formatted: String,
    /// Whether the block is valid (CID matches content)
    pub is_valid: bool,
}

impl std::fmt::Display for BlockInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Block:\n  CID: {}\n  Size: {} ({})\n  Valid: {}",
            self.cid, self.size, self.size_formatted, self.is_valid
        )
    }
}

/// Inspects a block and returns detailed diagnostic information.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::{quick_block, inspect_block};
///
/// let block = quick_block(b"Hello, World!").unwrap();
/// let info = inspect_block(&block).unwrap();
/// println!("{}", info);
/// ```
pub fn inspect_block(block: &Block) -> Result<BlockInfo> {
    let is_valid = block.verify()?;
    Ok(BlockInfo {
        cid: block.cid().to_string(),
        size: block.size(),
        size_formatted: format_size(block.size()),
        is_valid,
    })
}

/// Validates that a string is a valid CID.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::validate_cid_string;
///
/// assert!(validate_cid_string("QmXXX").is_ok() || validate_cid_string("QmXXX").is_err());
/// ```
pub fn validate_cid_string(s: &str) -> Result<Cid> {
    parse_cid_string(s)
}

/// Validates a collection of blocks, returning the number of valid and invalid blocks.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::{quick_block, validate_blocks};
///
/// let blocks = vec![
///     quick_block(b"data1").unwrap(),
///     quick_block(b"data2").unwrap(),
/// ];
/// let (valid, invalid) = validate_blocks(&blocks).unwrap();
/// assert_eq!(valid, 2);
/// assert_eq!(invalid, 0);
/// ```
pub fn validate_blocks(blocks: &[Block]) -> Result<(usize, usize)> {
    let mut valid = 0;
    let mut invalid = 0;

    for block in blocks {
        if block.verify()? {
            valid += 1;
        } else {
            invalid += 1;
        }
    }

    Ok((valid, invalid))
}

/// Finds blocks in a collection that have invalid CIDs (mismatched content).
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::{quick_block, find_invalid_blocks};
///
/// let blocks = vec![
///     quick_block(b"data1").unwrap(),
///     quick_block(b"data2").unwrap(),
/// ];
/// let invalid = find_invalid_blocks(&blocks).unwrap();
/// assert_eq!(invalid.len(), 0);
/// ```
pub fn find_invalid_blocks(blocks: &[Block]) -> Result<Vec<usize>> {
    let mut invalid_indices = Vec::new();

    for (i, block) in blocks.iter().enumerate() {
        if !block.verify()? {
            invalid_indices.push(i);
        }
    }

    Ok(invalid_indices)
}

/// Measures the time taken to generate a CID for the given data.
///
/// Returns the duration in microseconds and the generated CID.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::measure_cid_generation;
/// use ipfrs_core::HashAlgorithm;
///
/// let (duration_us, cid) = measure_cid_generation(b"test data", HashAlgorithm::Sha256).unwrap();
/// assert!(duration_us > 0);
/// ```
pub fn measure_cid_generation(data: &[u8], algorithm: HashAlgorithm) -> Result<(u64, Cid)> {
    let start = std::time::Instant::now();
    let cid = cid_of(data, algorithm)?;
    let duration = start.elapsed();
    Ok((duration.as_micros() as u64, cid))
}

/// Measures the time taken to create a block from the given data.
///
/// Returns the duration in microseconds and the created block.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::measure_block_creation;
///
/// let (duration_us, block) = measure_block_creation(b"test data").unwrap();
/// assert!(duration_us > 0);
/// ```
pub fn measure_block_creation(data: &[u8]) -> Result<(u64, Block)> {
    let start = std::time::Instant::now();
    let block = quick_block(data)?;
    let duration = start.elapsed();
    Ok((duration.as_micros() as u64, block))
}

/// Calculates the deduplication ratio for a collection of blocks.
///
/// Returns a value between 0.0 and 1.0, where:
/// - 1.0 means all blocks are unique (no deduplication)
/// - 0.5 means 50% of blocks are unique (50% deduplication)
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::{quick_block, deduplication_ratio};
///
/// let blocks = vec![
///     quick_block(b"same").unwrap(),
///     quick_block(b"same").unwrap(),
///     quick_block(b"different").unwrap(),
/// ];
/// let ratio = deduplication_ratio(&blocks);
/// assert!((ratio - 0.666).abs() < 0.01); // 2 unique out of 3 = ~0.666
/// ```
pub fn deduplication_ratio(blocks: &[Block]) -> f64 {
    if blocks.is_empty() {
        return 0.0;
    }

    let unique_cids: std::collections::HashSet<_> = blocks.iter().map(|b| b.cid()).collect();
    unique_cids.len() as f64 / blocks.len() as f64
}

/// Counts the number of unique CIDs in a collection of blocks.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::{quick_block, count_unique_blocks};
///
/// let blocks = vec![
///     quick_block(b"same").unwrap(),
///     quick_block(b"same").unwrap(),
///     quick_block(b"different").unwrap(),
/// ];
/// assert_eq!(count_unique_blocks(&blocks), 2);
/// ```
pub fn count_unique_blocks(blocks: &[Block]) -> usize {
    let unique_cids: std::collections::HashSet<_> = blocks.iter().map(|b| b.cid()).collect();
    unique_cids.len()
}

/// Calculates the total size of all blocks in bytes.
///
/// # Examples
///
/// ```rust
/// use ipfrs_core::utils::{quick_block, total_blocks_size};
///
/// let blocks = vec![
///     quick_block(b"data1").unwrap(),
///     quick_block(b"data2").unwrap(),
/// ];
/// assert_eq!(total_blocks_size(&blocks), 10); // "data1" + "data2" = 10 bytes
/// ```
pub fn total_blocks_size(blocks: &[Block]) -> u64 {
    blocks.iter().map(|b| b.size()).sum()
}

// ============================================================================
// Compression Utilities
// ============================================================================

/// Compress a block's data with the specified algorithm and level
///
/// Returns a new compressed `Bytes` buffer.
///
/// # Example
///
/// ```rust
/// use ipfrs_core::utils::{quick_block, compress_block_data, decompress_block_data};
/// use ipfrs_core::CompressionAlgorithm;
///
/// let data = "Hello, World! ".repeat(100); // Use compressible data
/// let block = quick_block(data.as_bytes()).unwrap();
/// let compressed = compress_block_data(block.data(), CompressionAlgorithm::Zstd, 3).unwrap();
/// let decompressed = decompress_block_data(&compressed, CompressionAlgorithm::Zstd).unwrap();
/// assert_eq!(block.data(), &decompressed);
/// ```
pub fn compress_block_data(
    data: &bytes::Bytes,
    algorithm: crate::CompressionAlgorithm,
    level: u8,
) -> crate::Result<bytes::Bytes> {
    crate::compress(data, algorithm, level)
}

/// Decompress block data that was previously compressed
///
/// # Example
///
/// ```rust
/// use ipfrs_core::utils::{compress_block_data, decompress_block_data};
/// use ipfrs_core::CompressionAlgorithm;
/// use bytes::Bytes;
///
/// let data = Bytes::from_static(b"Hello, World!");
/// let compressed = compress_block_data(&data, CompressionAlgorithm::Lz4, 3).unwrap();
/// let decompressed = decompress_block_data(&compressed, CompressionAlgorithm::Lz4).unwrap();
/// assert_eq!(data, decompressed);
/// ```
pub fn decompress_block_data(
    compressed: &bytes::Bytes,
    algorithm: crate::CompressionAlgorithm,
) -> crate::Result<bytes::Bytes> {
    crate::decompress(compressed, algorithm)
}

/// Estimate how much space would be saved by compressing the data
///
/// Returns a ratio between 0.0 and 1.0+ where lower is better.
/// A ratio of 0.5 means the compressed data is 50% of the original size.
///
/// # Example
///
/// ```rust
/// use ipfrs_core::utils::estimate_compression_savings;
/// use ipfrs_core::CompressionAlgorithm;
/// use bytes::Bytes;
///
/// let data = Bytes::from("a".repeat(1000)); // Highly compressible
/// let savings = estimate_compression_savings(&data, CompressionAlgorithm::Zstd, 5).unwrap();
/// assert!(savings < 0.2); // Should compress to less than 20% of original
/// ```
pub fn estimate_compression_savings(
    data: &bytes::Bytes,
    algorithm: crate::CompressionAlgorithm,
    level: u8,
) -> crate::Result<f64> {
    crate::compression_ratio(data, algorithm, level)
}

/// Check if data is worth compressing based on size and estimated ratio
///
/// Returns `true` if compression would likely save significant space.
/// Uses a threshold of 20% savings and minimum size of 1KB.
///
/// # Example
///
/// ```rust
/// use ipfrs_core::utils::should_compress;
/// use ipfrs_core::CompressionAlgorithm;
/// use bytes::Bytes;
///
/// let small_data = Bytes::from_static(b"Hello"); // Too small
/// assert!(!should_compress(&small_data, CompressionAlgorithm::Zstd, 3).unwrap());
///
/// let large_repetitive = Bytes::from("a".repeat(10000)); // Worth compressing
/// assert!(should_compress(&large_repetitive, CompressionAlgorithm::Zstd, 3).unwrap());
/// ```
pub fn should_compress(
    data: &bytes::Bytes,
    algorithm: crate::CompressionAlgorithm,
    level: u8,
) -> crate::Result<bool> {
    // Don't compress small data (overhead not worth it)
    if data.len() < 1024 {
        return Ok(false);
    }

    // Don't compress if algorithm is None
    if algorithm == crate::CompressionAlgorithm::None {
        return Ok(false);
    }

    // Check if we'd save at least 20%
    let ratio = crate::compression_ratio(data, algorithm, level)?;
    Ok(ratio < 0.8)
}

/// Get recommended compression algorithm based on use case
///
/// Returns `Zstd` for archival (best ratio) or `Lz4` for real-time (fastest).
///
/// # Example
///
/// ```rust
/// use ipfrs_core::utils::recommended_compression;
/// use ipfrs_core::CompressionAlgorithm;
///
/// let archival = recommended_compression(true);
/// assert_eq!(archival, CompressionAlgorithm::Zstd);
///
/// let realtime = recommended_compression(false);
/// assert_eq!(realtime, CompressionAlgorithm::Lz4);
/// ```
pub fn recommended_compression(prefer_ratio_over_speed: bool) -> crate::CompressionAlgorithm {
    if prefer_ratio_over_speed {
        crate::CompressionAlgorithm::Zstd // Best compression ratio
    } else {
        crate::CompressionAlgorithm::Lz4 // Fastest
    }
}

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

    #[test]
    fn test_quick_block() {
        let block = quick_block(b"test data").unwrap();
        assert_eq!(block.data().as_ref(), b"test data");
    }

    #[test]
    fn test_block_with_hash() {
        let block1 = block_with_hash(b"data", HashAlgorithm::Sha256).unwrap();
        let block2 = block_with_hash(b"data", HashAlgorithm::Sha3_256).unwrap();
        // Different hash algorithms produce different CIDs
        assert_ne!(block1.cid(), block2.cid());
    }

    #[test]
    fn test_cid_functions() {
        let sha256 = sha256_cid(b"test").unwrap();
        let sha3 = sha3_cid(b"test").unwrap();
        assert_ne!(sha256, sha3);
    }

    #[test]
    fn test_all_hash_algorithm_cid_functions() {
        let data = b"test data for all hash algorithms";

        // Test all 8 hash algorithms
        let sha256 = sha256_cid(data).unwrap();
        let sha512 = sha512_cid(data).unwrap();
        let sha3_256 = sha3_cid(data).unwrap();
        let sha3_512 = sha3_512_cid(data).unwrap();
        let blake2b256 = blake2b256_cid(data).unwrap();
        let blake2b512 = blake2b512_cid(data).unwrap();
        let blake2s256 = blake2s256_cid(data).unwrap();
        let blake3 = blake3_cid(data).unwrap();

        // All should produce different CIDs
        let cids = [
            sha256, sha512, sha3_256, sha3_512, blake2b256, blake2b512, blake2s256, blake3,
        ];

        // Check uniqueness - each hash algorithm should produce different output
        for i in 0..cids.len() {
            for j in (i + 1)..cids.len() {
                assert_ne!(cids[i], cids[j], "CID {} and {} should be different", i, j);
            }
        }
    }

    #[test]
    fn test_hash_algorithm_determinism() {
        let data = b"determinism test";

        // Each algorithm should produce the same CID for the same data
        assert_eq!(sha256_cid(data).unwrap(), sha256_cid(data).unwrap());
        assert_eq!(sha512_cid(data).unwrap(), sha512_cid(data).unwrap());
        assert_eq!(sha3_cid(data).unwrap(), sha3_cid(data).unwrap());
        assert_eq!(sha3_512_cid(data).unwrap(), sha3_512_cid(data).unwrap());
        assert_eq!(blake2b256_cid(data).unwrap(), blake2b256_cid(data).unwrap());
        assert_eq!(blake2b512_cid(data).unwrap(), blake2b512_cid(data).unwrap());
        assert_eq!(blake2s256_cid(data).unwrap(), blake2s256_cid(data).unwrap());
        assert_eq!(blake3_cid(data).unwrap(), blake3_cid(data).unwrap());
    }

    #[test]
    fn test_hash_algorithm_names_and_sizes() {
        use crate::HashAlgorithm;

        // Test name() method
        assert_eq!(HashAlgorithm::Sha256.name(), "SHA2-256");
        assert_eq!(HashAlgorithm::Sha512.name(), "SHA2-512");
        assert_eq!(HashAlgorithm::Sha3_256.name(), "SHA3-256");
        assert_eq!(HashAlgorithm::Sha3_512.name(), "SHA3-512");
        assert_eq!(HashAlgorithm::Blake2b256.name(), "BLAKE2b-256");
        assert_eq!(HashAlgorithm::Blake2b512.name(), "BLAKE2b-512");
        assert_eq!(HashAlgorithm::Blake2s256.name(), "BLAKE2s-256");
        assert_eq!(HashAlgorithm::Blake3.name(), "BLAKE3");

        // Test hash_size() method
        assert_eq!(HashAlgorithm::Sha256.hash_size(), 32);
        assert_eq!(HashAlgorithm::Sha512.hash_size(), 64);
        assert_eq!(HashAlgorithm::Sha3_256.hash_size(), 32);
        assert_eq!(HashAlgorithm::Sha3_512.hash_size(), 64);
        assert_eq!(HashAlgorithm::Blake2b256.hash_size(), 32);
        assert_eq!(HashAlgorithm::Blake2b512.hash_size(), 64);
        assert_eq!(HashAlgorithm::Blake2s256.hash_size(), 32);
        assert_eq!(HashAlgorithm::Blake3.hash_size(), 32);
    }

    #[test]
    fn test_hash_algorithm_all() {
        use crate::HashAlgorithm;

        let all = HashAlgorithm::all();
        assert_eq!(all.len(), 8);

        // Verify all algorithms are present
        assert!(all.contains(&HashAlgorithm::Sha256));
        assert!(all.contains(&HashAlgorithm::Sha512));
        assert!(all.contains(&HashAlgorithm::Sha3_256));
        assert!(all.contains(&HashAlgorithm::Sha3_512));
        assert!(all.contains(&HashAlgorithm::Blake2b256));
        assert!(all.contains(&HashAlgorithm::Blake2b512));
        assert!(all.contains(&HashAlgorithm::Blake2s256));
        assert!(all.contains(&HashAlgorithm::Blake3));
    }

    #[test]
    fn test_blocks_equal() {
        let block1 = quick_block(b"same").unwrap();
        let block2 = quick_block(b"same").unwrap();
        let block3 = quick_block(b"different").unwrap();

        assert!(blocks_equal(&block1, &block2));
        assert!(!blocks_equal(&block1, &block3));
    }

    #[test]
    fn test_verify_block() {
        let block = quick_block(b"verify me").unwrap();
        assert!(verify_block(&block).unwrap());
    }

    #[test]
    fn test_ipld_map() {
        let map = ipld_map(vec![
            ("key1", Ipld::String("value1".to_string())),
            ("key2", Ipld::Integer(42)),
        ]);

        match map {
            Ipld::Map(m) => {
                assert_eq!(m.len(), 2);
                assert!(m.contains_key("key1"));
                assert!(m.contains_key("key2"));
            }
            _ => panic!("Expected map"),
        }
    }

    #[test]
    fn test_ipld_list() {
        let list = ipld_list(vec![Ipld::Integer(1), Ipld::Integer(2), Ipld::Integer(3)]);

        match list {
            Ipld::List(l) => assert_eq!(l.len(), 3),
            _ => panic!("Expected list"),
        }
    }

    #[test]
    fn test_ipld_cbor_roundtrip() {
        let ipld = Ipld::String("test".to_string());
        let cbor = ipld_to_cbor(&ipld).unwrap();
        let decoded = ipld_from_cbor(&cbor).unwrap();
        assert_eq!(ipld, decoded);
    }

    #[test]
    fn test_ipld_json_roundtrip() {
        let ipld = Ipld::String("test".to_string());
        let json = ipld_to_json(&ipld).unwrap();
        let decoded = ipld_from_json(&json).unwrap();
        assert_eq!(ipld, decoded);
    }

    #[test]
    fn test_format_size() {
        assert_eq!(format_size(512), "512 B");
        assert_eq!(format_size(1024), "1.00 KB");
        assert_eq!(format_size(1_048_576), "1.00 MB");
        assert_eq!(format_size(1_073_741_824), "1.00 GB");
        assert_eq!(format_size(2_147_483_648), "2.00 GB");
    }

    #[test]
    fn test_estimate_chunks() {
        assert_eq!(estimate_chunks(100), 1);
        assert_eq!(estimate_chunks(300_000), 2);
        assert_eq!(estimate_chunks(1_000_000), 4);
    }

    #[test]
    fn test_needs_chunking() {
        assert!(!needs_chunking(100));
        assert!(!needs_chunking(1_000_000));
        assert!(!needs_chunking(2_000_000)); // 2MB < MAX_BLOCK_SIZE (2MiB)
        assert!(needs_chunking(3_000_000)); // 3MB > MAX_BLOCK_SIZE
        assert!(needs_chunking(10_000_000));
    }

    // Diagnostic and validation tests

    #[test]
    fn test_inspect_cid() {
        let cid = sha256_cid(b"test").unwrap();
        let info = inspect_cid(&cid);
        assert_eq!(info.version, 1);
        assert!(!info.cid_string.is_empty());
        assert!(info.hash_length > 0);
    }

    #[test]
    fn test_inspect_block() {
        let block = quick_block(b"test data").unwrap();
        let info = inspect_block(&block).unwrap();
        assert!(info.is_valid);
        assert_eq!(info.size, 9_u64);
        assert!(!info.cid.is_empty());
        assert!(!info.size_formatted.is_empty());
    }

    #[test]
    fn test_cid_info_display() {
        let cid = sha256_cid(b"test").unwrap();
        let info = inspect_cid(&cid);
        let display = format!("{}", info);
        assert!(display.contains("CID:"));
        assert!(display.contains("Version:"));
        assert!(display.contains("Codec:"));
    }

    #[test]
    fn test_block_info_display() {
        let block = quick_block(b"test").unwrap();
        let info = inspect_block(&block).unwrap();
        let display = format!("{}", info);
        assert!(display.contains("Block:"));
        assert!(display.contains("CID:"));
        assert!(display.contains("Valid:"));
    }

    #[test]
    fn test_validate_blocks() {
        let blocks = vec![
            quick_block(b"data1").unwrap(),
            quick_block(b"data2").unwrap(),
            quick_block(b"data3").unwrap(),
        ];

        let (valid, invalid) = validate_blocks(&blocks).unwrap();
        assert_eq!(valid, 3);
        assert_eq!(invalid, 0);
    }

    #[test]
    fn test_validate_blocks_empty() {
        let blocks: Vec<Block> = vec![];
        let (valid, invalid) = validate_blocks(&blocks).unwrap();
        assert_eq!(valid, 0);
        assert_eq!(invalid, 0);
    }

    #[test]
    fn test_find_invalid_blocks() {
        let blocks = vec![
            quick_block(b"data1").unwrap(),
            quick_block(b"data2").unwrap(),
        ];

        let invalid = find_invalid_blocks(&blocks).unwrap();
        assert_eq!(invalid.len(), 0);
    }

    #[test]
    fn test_measure_cid_generation() {
        let (duration, cid) = measure_cid_generation(b"test data", HashAlgorithm::Sha256).unwrap();
        assert!(duration > 0);
        assert!(!cid.to_string().is_empty());
    }

    #[test]
    fn test_measure_block_creation() {
        let (duration, block) = measure_block_creation(b"test data").unwrap();
        assert!(duration > 0);
        assert_eq!(block.size(), 9_u64);
    }

    #[test]
    fn test_deduplication_ratio() {
        let blocks = vec![
            quick_block(b"same").unwrap(),
            quick_block(b"same").unwrap(),
            quick_block(b"different").unwrap(),
        ];

        let ratio = deduplication_ratio(&blocks);
        // 2 unique out of 3 total
        assert!((ratio - 0.666).abs() < 0.01);
    }

    #[test]
    fn test_deduplication_ratio_all_unique() {
        let blocks = vec![
            quick_block(b"data1").unwrap(),
            quick_block(b"data2").unwrap(),
            quick_block(b"data3").unwrap(),
        ];

        let ratio = deduplication_ratio(&blocks);
        assert_eq!(ratio, 1.0);
    }

    #[test]
    fn test_deduplication_ratio_all_same() {
        let blocks = vec![
            quick_block(b"same").unwrap(),
            quick_block(b"same").unwrap(),
            quick_block(b"same").unwrap(),
        ];

        let ratio = deduplication_ratio(&blocks);
        // 1 unique out of 3 total
        assert!((ratio - 0.333).abs() < 0.01);
    }

    #[test]
    fn test_deduplication_ratio_empty() {
        let blocks: Vec<Block> = vec![];
        let ratio = deduplication_ratio(&blocks);
        assert_eq!(ratio, 0.0);
    }

    #[test]
    fn test_count_unique_blocks() {
        let blocks = vec![
            quick_block(b"same").unwrap(),
            quick_block(b"same").unwrap(),
            quick_block(b"different").unwrap(),
        ];

        assert_eq!(count_unique_blocks(&blocks), 2);
    }

    #[test]
    fn test_count_unique_blocks_all_unique() {
        let blocks = vec![
            quick_block(b"a").unwrap(),
            quick_block(b"b").unwrap(),
            quick_block(b"c").unwrap(),
        ];

        assert_eq!(count_unique_blocks(&blocks), 3);
    }

    #[test]
    fn test_count_unique_blocks_empty() {
        let blocks: Vec<Block> = vec![];
        assert_eq!(count_unique_blocks(&blocks), 0);
    }

    #[test]
    fn test_total_blocks_size() {
        let blocks = vec![
            quick_block(b"data1").unwrap(), // 5 bytes
            quick_block(b"data2").unwrap(), // 5 bytes
        ];

        assert_eq!(total_blocks_size(&blocks), 10);
    }

    #[test]
    fn test_total_blocks_size_empty() {
        let blocks: Vec<Block> = vec![];
        assert_eq!(total_blocks_size(&blocks), 0);
    }

    #[test]
    fn test_compress_block_data() {
        use crate::CompressionAlgorithm;

        let data = bytes::Bytes::from("Hello, World! ".repeat(100));
        let compressed = compress_block_data(&data, CompressionAlgorithm::Zstd, 5).unwrap();

        // Should compress well with repetitive data
        assert!(compressed.len() < data.len());

        // Decompress and verify
        let decompressed = decompress_block_data(&compressed, CompressionAlgorithm::Zstd).unwrap();
        assert_eq!(data, decompressed);
    }

    #[test]
    fn test_estimate_compression_savings() {
        use crate::CompressionAlgorithm;

        let data = bytes::Bytes::from("a".repeat(1000));
        let ratio = estimate_compression_savings(&data, CompressionAlgorithm::Zstd, 5).unwrap();

        // Highly repetitive data should compress very well
        assert!(ratio < 0.1);
    }

    #[test]
    fn test_should_compress() {
        use crate::CompressionAlgorithm;

        // Small data should not be compressed
        let small = bytes::Bytes::from_static(b"Hello");
        assert!(!should_compress(&small, CompressionAlgorithm::Zstd, 3).unwrap());

        // Large repetitive data should be compressed
        let large = bytes::Bytes::from("a".repeat(10000));
        assert!(should_compress(&large, CompressionAlgorithm::Zstd, 3).unwrap());

        // None algorithm should never compress
        assert!(!should_compress(&large, CompressionAlgorithm::None, 3).unwrap());
    }

    #[test]
    fn test_recommended_compression() {
        use crate::CompressionAlgorithm;

        assert_eq!(recommended_compression(true), CompressionAlgorithm::Zstd);
        assert_eq!(recommended_compression(false), CompressionAlgorithm::Lz4);
    }
}