libsodium-rs 0.2.4

A comprehensive, idiomatic Rust wrapper for libsodium, providing a safe and ergonomic API for cryptographic operations
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
//! # Extendable Output Functions (XOFs)
//!
//! This module provides extendable output functions (XOFs) based on the Keccak permutation.
//! Unlike regular hash functions with fixed-size output, XOFs can produce output of arbitrary
//! length from the same input.
//!
//! ## Available XOFs
//!
//! - **SHAKE128/SHAKE256**: NIST-standardized XOFs from FIPS 202, based on Keccak with 24 rounds
//! - **TurboSHAKE128/TurboSHAKE256**: Faster variants using 12 rounds, standardized in RFC 9861
//!
//! ## When to Use Each Variant
//!
//! **TurboSHAKE128** is recommended for most applications:
//! - ~2x faster than SHAKE
//! - 128-bit security (sufficient for virtually all use cases)
//! - Built-in domain separation support
//!
//! Use SHAKE variants only when NIST FIPS 202 compliance is required.
//!
//! ## Use Cases
//!
//! - **Key derivation**: Derive multiple keys from a single seed
//! - **Deterministic random generation**: Expand a seed into arbitrary-length output
//! - **Hash functions**: Use as a hash with any output size
//! - **Domain-separated hashing**: Use custom domain separators for independent functions
//!
//! ## Example
//!
//! ```rust
//! use libsodium_rs::crypto_xof::turboshake128;
//!
//! // One-shot hashing
//! let message = b"Arbitrary data to hash";
//! let hash = turboshake128::hash(message, 32).unwrap();
//!
//! // Multi-part hashing with incremental squeezing
//! let mut state = turboshake128::State::new().unwrap();
//! state.update(b"part 1").unwrap();
//! state.update(b"part 2").unwrap();
//!
//! // Squeeze multiple outputs
//! let key1 = state.squeeze(32).unwrap();
//! let key2 = state.squeeze(32).unwrap();
//! ```

use crate::{Result, SodiumError};

/// SHAKE128 XOF (128-bit security, 24 rounds)
///
/// SHAKE128 is a NIST-standardized XOF from FIPS 202. It provides 128-bit security
/// and uses 24 rounds of the Keccak permutation.
///
/// For most applications, prefer `turboshake128` which is faster while maintaining
/// the same security level.
pub mod shake128 {
    use super::*;

    /// Block size in bytes (168)
    pub const BLOCKBYTES: usize = libsodium_sys::crypto_xof_shake128_BLOCKBYTES as usize;

    /// State size in bytes (256)
    pub const STATEBYTES: usize = libsodium_sys::crypto_xof_shake128_STATEBYTES as usize;

    /// Standard domain separator (0x1F)
    pub const DOMAIN_STANDARD: u8 = libsodium_sys::crypto_xof_shake128_DOMAIN_STANDARD as u8;

    /// Returns the block size in bytes
    pub fn blockbytes() -> usize {
        unsafe { libsodium_sys::crypto_xof_shake128_blockbytes() }
    }

    /// Returns the state size in bytes
    pub fn statebytes() -> usize {
        unsafe { libsodium_sys::crypto_xof_shake128_statebytes() }
    }

    /// Returns the standard domain separator
    pub fn domain_standard() -> u8 {
        unsafe { libsodium_sys::crypto_xof_shake128_domain_standard() }
    }

    /// Computes the SHAKE128 XOF of the input in one shot
    ///
    /// # Arguments
    ///
    /// * `input` - The input data to hash
    /// * `output_len` - The desired output length in bytes
    ///
    /// # Returns
    ///
    /// The XOF output of the specified length
    ///
    /// # Example
    ///
    /// ```rust
    /// use libsodium_rs::crypto_xof::shake128;
    ///
    /// let message = b"Hello, World!";
    /// let hash = shake128::hash(message, 32).unwrap();
    /// assert_eq!(hash.len(), 32);
    /// ```
    pub fn hash(input: &[u8], output_len: usize) -> Result<Vec<u8>> {
        let mut output = vec![0u8; output_len];
        let result = unsafe {
            libsodium_sys::crypto_xof_shake128(
                output.as_mut_ptr(),
                output_len,
                input.as_ptr(),
                input.len() as u64,
            )
        };

        if result != 0 {
            return Err(SodiumError::OperationError("SHAKE128 hash failed".into()));
        }

        Ok(output)
    }

    /// State for incremental SHAKE128 hashing
    ///
    /// Allows absorbing data in chunks and squeezing output incrementally.
    /// Once squeezing begins, no more data can be absorbed.
    pub struct State {
        state: libsodium_sys::crypto_xof_shake128_state,
        squeezed: bool,
    }

    impl State {
        /// Creates a new SHAKE128 state with the standard domain separator
        pub fn new() -> Result<Self> {
            let mut state = Self {
                state: unsafe { std::mem::zeroed() },
                squeezed: false,
            };

            let result = unsafe { libsodium_sys::crypto_xof_shake128_init(&mut state.state) };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "SHAKE128 state initialization failed".into(),
                ));
            }

            Ok(state)
        }

        /// Creates a new SHAKE128 state with a custom domain separator
        ///
        /// Domain separators allow creating independent hash functions from the same primitive.
        /// The domain must be between 0x01 and 0x7F.
        ///
        /// # Arguments
        ///
        /// * `domain` - The domain separator (must be between 0x01 and 0x7F)
        pub fn new_with_domain(domain: u8) -> Result<Self> {
            if domain == 0 || domain > 0x7F {
                return Err(SodiumError::InvalidInput(
                    "domain must be between 0x01 and 0x7F".into(),
                ));
            }

            let mut state = Self {
                state: unsafe { std::mem::zeroed() },
                squeezed: false,
            };

            let result = unsafe {
                libsodium_sys::crypto_xof_shake128_init_with_domain(&mut state.state, domain)
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "SHAKE128 state initialization with domain failed".into(),
                ));
            }

            Ok(state)
        }

        /// Absorbs data into the state
        ///
        /// Can be called multiple times before squeezing.
        /// Returns an error if called after squeezing has begun.
        pub fn update(&mut self, input: &[u8]) -> Result<()> {
            if self.squeezed {
                return Err(SodiumError::OperationError(
                    "cannot absorb after squeezing".into(),
                ));
            }

            let result = unsafe {
                libsodium_sys::crypto_xof_shake128_update(
                    &mut self.state,
                    input.as_ptr(),
                    input.len() as u64,
                )
            };

            if result != 0 {
                return Err(SodiumError::OperationError("SHAKE128 update failed".into()));
            }

            Ok(())
        }

        /// Squeezes output from the state
        ///
        /// Can be called multiple times to produce additional output.
        /// The concatenation of all squeezed outputs is identical to squeezing
        /// the total length at once.
        pub fn squeeze(&mut self, output_len: usize) -> Result<Vec<u8>> {
            self.squeezed = true;

            let mut output = vec![0u8; output_len];
            let result = unsafe {
                libsodium_sys::crypto_xof_shake128_squeeze(
                    &mut self.state,
                    output.as_mut_ptr(),
                    output_len,
                )
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "SHAKE128 squeeze failed".into(),
                ));
            }

            Ok(output)
        }

        /// Squeezes output into a provided buffer
        pub fn squeeze_into(&mut self, output: &mut [u8]) -> Result<()> {
            self.squeezed = true;

            let result = unsafe {
                libsodium_sys::crypto_xof_shake128_squeeze(
                    &mut self.state,
                    output.as_mut_ptr(),
                    output.len(),
                )
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "SHAKE128 squeeze failed".into(),
                ));
            }

            Ok(())
        }
    }

    impl Default for State {
        fn default() -> Self {
            Self::new().expect("SHAKE128 state initialization should not fail")
        }
    }
}

/// SHAKE256 XOF (256-bit security, 24 rounds)
///
/// SHAKE256 is a NIST-standardized XOF from FIPS 202. It provides 256-bit security
/// and uses 24 rounds of the Keccak permutation.
///
/// For most applications, prefer `turboshake256` which is faster while maintaining
/// the same security level.
pub mod shake256 {
    use super::*;

    /// Block size in bytes (136)
    pub const BLOCKBYTES: usize = libsodium_sys::crypto_xof_shake256_BLOCKBYTES as usize;

    /// State size in bytes (256)
    pub const STATEBYTES: usize = libsodium_sys::crypto_xof_shake256_STATEBYTES as usize;

    /// Standard domain separator (0x1F)
    pub const DOMAIN_STANDARD: u8 = libsodium_sys::crypto_xof_shake256_DOMAIN_STANDARD as u8;

    /// Returns the block size in bytes
    pub fn blockbytes() -> usize {
        unsafe { libsodium_sys::crypto_xof_shake256_blockbytes() }
    }

    /// Returns the state size in bytes
    pub fn statebytes() -> usize {
        unsafe { libsodium_sys::crypto_xof_shake256_statebytes() }
    }

    /// Returns the standard domain separator
    pub fn domain_standard() -> u8 {
        unsafe { libsodium_sys::crypto_xof_shake256_domain_standard() }
    }

    /// Computes the SHAKE256 XOF of the input in one shot
    ///
    /// # Arguments
    ///
    /// * `input` - The input data to hash
    /// * `output_len` - The desired output length in bytes
    ///
    /// # Returns
    ///
    /// The XOF output of the specified length
    pub fn hash(input: &[u8], output_len: usize) -> Result<Vec<u8>> {
        let mut output = vec![0u8; output_len];
        let result = unsafe {
            libsodium_sys::crypto_xof_shake256(
                output.as_mut_ptr(),
                output_len,
                input.as_ptr(),
                input.len() as u64,
            )
        };

        if result != 0 {
            return Err(SodiumError::OperationError("SHAKE256 hash failed".into()));
        }

        Ok(output)
    }

    /// State for incremental SHAKE256 hashing
    pub struct State {
        state: libsodium_sys::crypto_xof_shake256_state,
        squeezed: bool,
    }

    impl State {
        /// Creates a new SHAKE256 state with the standard domain separator
        pub fn new() -> Result<Self> {
            let mut state = Self {
                state: unsafe { std::mem::zeroed() },
                squeezed: false,
            };

            let result = unsafe { libsodium_sys::crypto_xof_shake256_init(&mut state.state) };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "SHAKE256 state initialization failed".into(),
                ));
            }

            Ok(state)
        }

        /// Creates a new SHAKE256 state with a custom domain separator
        ///
        /// The domain must be between 0x01 and 0x7F.
        pub fn new_with_domain(domain: u8) -> Result<Self> {
            if domain == 0 || domain > 0x7F {
                return Err(SodiumError::InvalidInput(
                    "domain must be between 0x01 and 0x7F".into(),
                ));
            }

            let mut state = Self {
                state: unsafe { std::mem::zeroed() },
                squeezed: false,
            };

            let result = unsafe {
                libsodium_sys::crypto_xof_shake256_init_with_domain(&mut state.state, domain)
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "SHAKE256 state initialization with domain failed".into(),
                ));
            }

            Ok(state)
        }

        /// Absorbs data into the state
        pub fn update(&mut self, input: &[u8]) -> Result<()> {
            if self.squeezed {
                return Err(SodiumError::OperationError(
                    "cannot absorb after squeezing".into(),
                ));
            }

            let result = unsafe {
                libsodium_sys::crypto_xof_shake256_update(
                    &mut self.state,
                    input.as_ptr(),
                    input.len() as u64,
                )
            };

            if result != 0 {
                return Err(SodiumError::OperationError("SHAKE256 update failed".into()));
            }

            Ok(())
        }

        /// Squeezes output from the state
        pub fn squeeze(&mut self, output_len: usize) -> Result<Vec<u8>> {
            self.squeezed = true;

            let mut output = vec![0u8; output_len];
            let result = unsafe {
                libsodium_sys::crypto_xof_shake256_squeeze(
                    &mut self.state,
                    output.as_mut_ptr(),
                    output_len,
                )
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "SHAKE256 squeeze failed".into(),
                ));
            }

            Ok(output)
        }

        /// Squeezes output into a provided buffer
        pub fn squeeze_into(&mut self, output: &mut [u8]) -> Result<()> {
            self.squeezed = true;

            let result = unsafe {
                libsodium_sys::crypto_xof_shake256_squeeze(
                    &mut self.state,
                    output.as_mut_ptr(),
                    output.len(),
                )
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "SHAKE256 squeeze failed".into(),
                ));
            }

            Ok(())
        }
    }

    impl Default for State {
        fn default() -> Self {
            Self::new().expect("SHAKE256 state initialization should not fail")
        }
    }
}

/// TurboSHAKE128 XOF (128-bit security, 12 rounds)
///
/// TurboSHAKE128 is a faster variant of SHAKE128 that uses 12 rounds of the Keccak
/// permutation instead of 24. It is roughly twice as fast as SHAKE128 while
/// maintaining the same 128-bit security level.
///
/// This is the recommended XOF for most applications.
///
/// ## Example
///
/// ```rust
/// use libsodium_rs::crypto_xof::turboshake128;
///
/// // One-shot hashing
/// let hash = turboshake128::hash(b"message", 32).unwrap();
///
/// // Multi-part with domain separation
/// let mut state = turboshake128::State::new_with_domain(0x01).unwrap();
/// state.update(b"key derivation input").unwrap();
/// let key1 = state.squeeze(32).unwrap();
/// let key2 = state.squeeze(32).unwrap();
/// ```
pub mod turboshake128 {
    use super::*;

    /// Block size in bytes (168)
    pub const BLOCKBYTES: usize = libsodium_sys::crypto_xof_turboshake128_BLOCKBYTES as usize;

    /// State size in bytes (256)
    pub const STATEBYTES: usize = libsodium_sys::crypto_xof_turboshake128_STATEBYTES as usize;

    /// Standard domain separator (0x1F)
    pub const DOMAIN_STANDARD: u8 = libsodium_sys::crypto_xof_turboshake128_DOMAIN_STANDARD as u8;

    /// Returns the block size in bytes
    pub fn blockbytes() -> usize {
        unsafe { libsodium_sys::crypto_xof_turboshake128_blockbytes() }
    }

    /// Returns the state size in bytes
    pub fn statebytes() -> usize {
        unsafe { libsodium_sys::crypto_xof_turboshake128_statebytes() }
    }

    /// Returns the standard domain separator
    pub fn domain_standard() -> u8 {
        unsafe { libsodium_sys::crypto_xof_turboshake128_domain_standard() }
    }

    /// Computes the TurboSHAKE128 XOF of the input in one shot
    ///
    /// # Arguments
    ///
    /// * `input` - The input data to hash
    /// * `output_len` - The desired output length in bytes
    ///
    /// # Returns
    ///
    /// The XOF output of the specified length
    ///
    /// # Example
    ///
    /// ```rust
    /// use libsodium_rs::crypto_xof::turboshake128;
    ///
    /// let message = b"Hello, World!";
    /// let hash = turboshake128::hash(message, 32).unwrap();
    /// assert_eq!(hash.len(), 32);
    ///
    /// // Generate deterministic test data
    /// let seed = b"test seed";
    /// let test_data = turboshake128::hash(seed, 1000).unwrap();
    /// ```
    pub fn hash(input: &[u8], output_len: usize) -> Result<Vec<u8>> {
        let mut output = vec![0u8; output_len];
        let result = unsafe {
            libsodium_sys::crypto_xof_turboshake128(
                output.as_mut_ptr(),
                output_len,
                input.as_ptr(),
                input.len() as u64,
            )
        };

        if result != 0 {
            return Err(SodiumError::OperationError(
                "TurboSHAKE128 hash failed".into(),
            ));
        }

        Ok(output)
    }

    /// State for incremental TurboSHAKE128 hashing
    ///
    /// Allows absorbing data in chunks and squeezing output incrementally.
    /// This is useful for:
    /// - Hashing large data that doesn't fit in memory
    /// - Deriving multiple keys from a single seed
    /// - Generating arbitrary amounts of deterministic output
    pub struct State {
        state: libsodium_sys::crypto_xof_turboshake128_state,
        squeezed: bool,
    }

    impl State {
        /// Creates a new TurboSHAKE128 state with the standard domain separator
        pub fn new() -> Result<Self> {
            let mut state = Self {
                state: unsafe { std::mem::zeroed() },
                squeezed: false,
            };

            let result = unsafe { libsodium_sys::crypto_xof_turboshake128_init(&mut state.state) };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "TurboSHAKE128 state initialization failed".into(),
                ));
            }

            Ok(state)
        }

        /// Creates a new TurboSHAKE128 state with a custom domain separator
        ///
        /// Domain separators allow creating independent hash functions from the same primitive.
        /// This is useful for domain separation in cryptographic protocols.
        ///
        /// # Arguments
        ///
        /// * `domain` - The domain separator (must be between 0x01 and 0x7F)
        ///
        /// # Example
        ///
        /// ```rust
        /// use libsodium_rs::crypto_xof::turboshake128;
        ///
        /// const DOMAIN_KEY_DERIVATION: u8 = 0x01;
        /// const DOMAIN_COMMITMENT: u8 = 0x02;
        ///
        /// // These produce independent outputs even with the same input
        /// let mut state1 = turboshake128::State::new_with_domain(DOMAIN_KEY_DERIVATION).unwrap();
        /// let mut state2 = turboshake128::State::new_with_domain(DOMAIN_COMMITMENT).unwrap();
        ///
        /// state1.update(b"secret").unwrap();
        /// state2.update(b"secret").unwrap();
        ///
        /// let key = state1.squeeze(32).unwrap();
        /// let commitment = state2.squeeze(32).unwrap();
        ///
        /// assert_ne!(key, commitment);
        /// ```
        pub fn new_with_domain(domain: u8) -> Result<Self> {
            if domain == 0 || domain > 0x7F {
                return Err(SodiumError::InvalidInput(
                    "domain must be between 0x01 and 0x7F".into(),
                ));
            }

            let mut state = Self {
                state: unsafe { std::mem::zeroed() },
                squeezed: false,
            };

            let result = unsafe {
                libsodium_sys::crypto_xof_turboshake128_init_with_domain(&mut state.state, domain)
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "TurboSHAKE128 state initialization with domain failed".into(),
                ));
            }

            Ok(state)
        }

        /// Absorbs data into the state
        ///
        /// Can be called multiple times before squeezing.
        /// Returns an error if called after squeezing has begun.
        pub fn update(&mut self, input: &[u8]) -> Result<()> {
            if self.squeezed {
                return Err(SodiumError::OperationError(
                    "cannot absorb after squeezing".into(),
                ));
            }

            let result = unsafe {
                libsodium_sys::crypto_xof_turboshake128_update(
                    &mut self.state,
                    input.as_ptr(),
                    input.len() as u64,
                )
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "TurboSHAKE128 update failed".into(),
                ));
            }

            Ok(())
        }

        /// Squeezes output from the state
        ///
        /// Can be called multiple times to produce additional output.
        /// The concatenation of all squeezed outputs is identical to squeezing
        /// the total length at once.
        ///
        /// # Example
        ///
        /// ```rust
        /// use libsodium_rs::crypto_xof::turboshake128;
        ///
        /// let mut state = turboshake128::State::new().unwrap();
        /// state.update(b"seed").unwrap();
        ///
        /// // Squeeze three independent 32-byte keys
        /// let key1 = state.squeeze(32).unwrap();
        /// let key2 = state.squeeze(32).unwrap();
        /// let key3 = state.squeeze(32).unwrap();
        ///
        /// // Each key is different
        /// assert_ne!(key1, key2);
        /// assert_ne!(key2, key3);
        /// ```
        pub fn squeeze(&mut self, output_len: usize) -> Result<Vec<u8>> {
            self.squeezed = true;

            let mut output = vec![0u8; output_len];
            let result = unsafe {
                libsodium_sys::crypto_xof_turboshake128_squeeze(
                    &mut self.state,
                    output.as_mut_ptr(),
                    output_len,
                )
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "TurboSHAKE128 squeeze failed".into(),
                ));
            }

            Ok(output)
        }

        /// Squeezes output into a provided buffer
        pub fn squeeze_into(&mut self, output: &mut [u8]) -> Result<()> {
            self.squeezed = true;

            let result = unsafe {
                libsodium_sys::crypto_xof_turboshake128_squeeze(
                    &mut self.state,
                    output.as_mut_ptr(),
                    output.len(),
                )
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "TurboSHAKE128 squeeze failed".into(),
                ));
            }

            Ok(())
        }
    }

    impl Default for State {
        fn default() -> Self {
            Self::new().expect("TurboSHAKE128 state initialization should not fail")
        }
    }
}

/// TurboSHAKE256 XOF (256-bit security, 12 rounds)
///
/// TurboSHAKE256 is a faster variant of SHAKE256 that uses 12 rounds of the Keccak
/// permutation instead of 24. It provides 256-bit security (collision resistance
/// up to 2^128 work).
///
/// Use this when you need 256-bit collision resistance. For most applications,
/// `turboshake128` is sufficient and faster due to its larger block size.
pub mod turboshake256 {
    use super::*;

    /// Block size in bytes (136)
    pub const BLOCKBYTES: usize = libsodium_sys::crypto_xof_turboshake256_BLOCKBYTES as usize;

    /// State size in bytes (256)
    pub const STATEBYTES: usize = libsodium_sys::crypto_xof_turboshake256_STATEBYTES as usize;

    /// Standard domain separator (0x1F)
    pub const DOMAIN_STANDARD: u8 = libsodium_sys::crypto_xof_turboshake256_DOMAIN_STANDARD as u8;

    /// Returns the block size in bytes
    pub fn blockbytes() -> usize {
        unsafe { libsodium_sys::crypto_xof_turboshake256_blockbytes() }
    }

    /// Returns the state size in bytes
    pub fn statebytes() -> usize {
        unsafe { libsodium_sys::crypto_xof_turboshake256_statebytes() }
    }

    /// Returns the standard domain separator
    pub fn domain_standard() -> u8 {
        unsafe { libsodium_sys::crypto_xof_turboshake256_domain_standard() }
    }

    /// Computes the TurboSHAKE256 XOF of the input in one shot
    ///
    /// # Arguments
    ///
    /// * `input` - The input data to hash
    /// * `output_len` - The desired output length in bytes
    ///
    /// # Returns
    ///
    /// The XOF output of the specified length
    pub fn hash(input: &[u8], output_len: usize) -> Result<Vec<u8>> {
        let mut output = vec![0u8; output_len];
        let result = unsafe {
            libsodium_sys::crypto_xof_turboshake256(
                output.as_mut_ptr(),
                output_len,
                input.as_ptr(),
                input.len() as u64,
            )
        };

        if result != 0 {
            return Err(SodiumError::OperationError(
                "TurboSHAKE256 hash failed".into(),
            ));
        }

        Ok(output)
    }

    /// State for incremental TurboSHAKE256 hashing
    pub struct State {
        state: libsodium_sys::crypto_xof_turboshake256_state,
        squeezed: bool,
    }

    impl State {
        /// Creates a new TurboSHAKE256 state with the standard domain separator
        pub fn new() -> Result<Self> {
            let mut state = Self {
                state: unsafe { std::mem::zeroed() },
                squeezed: false,
            };

            let result = unsafe { libsodium_sys::crypto_xof_turboshake256_init(&mut state.state) };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "TurboSHAKE256 state initialization failed".into(),
                ));
            }

            Ok(state)
        }

        /// Creates a new TurboSHAKE256 state with a custom domain separator
        ///
        /// The domain must be between 0x01 and 0x7F.
        pub fn new_with_domain(domain: u8) -> Result<Self> {
            if domain == 0 || domain > 0x7F {
                return Err(SodiumError::InvalidInput(
                    "domain must be between 0x01 and 0x7F".into(),
                ));
            }

            let mut state = Self {
                state: unsafe { std::mem::zeroed() },
                squeezed: false,
            };

            let result = unsafe {
                libsodium_sys::crypto_xof_turboshake256_init_with_domain(&mut state.state, domain)
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "TurboSHAKE256 state initialization with domain failed".into(),
                ));
            }

            Ok(state)
        }

        /// Absorbs data into the state
        pub fn update(&mut self, input: &[u8]) -> Result<()> {
            if self.squeezed {
                return Err(SodiumError::OperationError(
                    "cannot absorb after squeezing".into(),
                ));
            }

            let result = unsafe {
                libsodium_sys::crypto_xof_turboshake256_update(
                    &mut self.state,
                    input.as_ptr(),
                    input.len() as u64,
                )
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "TurboSHAKE256 update failed".into(),
                ));
            }

            Ok(())
        }

        /// Squeezes output from the state
        pub fn squeeze(&mut self, output_len: usize) -> Result<Vec<u8>> {
            self.squeezed = true;

            let mut output = vec![0u8; output_len];
            let result = unsafe {
                libsodium_sys::crypto_xof_turboshake256_squeeze(
                    &mut self.state,
                    output.as_mut_ptr(),
                    output_len,
                )
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "TurboSHAKE256 squeeze failed".into(),
                ));
            }

            Ok(output)
        }

        /// Squeezes output into a provided buffer
        pub fn squeeze_into(&mut self, output: &mut [u8]) -> Result<()> {
            self.squeezed = true;

            let result = unsafe {
                libsodium_sys::crypto_xof_turboshake256_squeeze(
                    &mut self.state,
                    output.as_mut_ptr(),
                    output.len(),
                )
            };

            if result != 0 {
                return Err(SodiumError::OperationError(
                    "TurboSHAKE256 squeeze failed".into(),
                ));
            }

            Ok(())
        }
    }

    impl Default for State {
        fn default() -> Self {
            Self::new().expect("TurboSHAKE256 state initialization should not fail")
        }
    }
}

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

    #[test]
    fn test_shake128_constants() {
        assert_eq!(shake128::BLOCKBYTES, 168);
        assert_eq!(shake128::STATEBYTES, 256);
        assert_eq!(shake128::DOMAIN_STANDARD, 0x1F);

        assert_eq!(shake128::blockbytes(), 168);
        assert_eq!(shake128::statebytes(), 256);
        assert_eq!(shake128::domain_standard(), 0x1F);
    }

    #[test]
    fn test_shake256_constants() {
        assert_eq!(shake256::BLOCKBYTES, 136);
        assert_eq!(shake256::STATEBYTES, 256);
        assert_eq!(shake256::DOMAIN_STANDARD, 0x1F);

        assert_eq!(shake256::blockbytes(), 136);
        assert_eq!(shake256::statebytes(), 256);
        assert_eq!(shake256::domain_standard(), 0x1F);
    }

    #[test]
    fn test_turboshake128_constants() {
        assert_eq!(turboshake128::BLOCKBYTES, 168);
        assert_eq!(turboshake128::STATEBYTES, 256);
        assert_eq!(turboshake128::DOMAIN_STANDARD, 0x1F);

        assert_eq!(turboshake128::blockbytes(), 168);
        assert_eq!(turboshake128::statebytes(), 256);
        assert_eq!(turboshake128::domain_standard(), 0x1F);
    }

    #[test]
    fn test_turboshake256_constants() {
        assert_eq!(turboshake256::BLOCKBYTES, 136);
        assert_eq!(turboshake256::STATEBYTES, 256);
        assert_eq!(turboshake256::DOMAIN_STANDARD, 0x1F);

        assert_eq!(turboshake256::blockbytes(), 136);
        assert_eq!(turboshake256::statebytes(), 256);
        assert_eq!(turboshake256::domain_standard(), 0x1F);
    }

    #[test]
    fn test_shake128_hash() {
        let message = b"Hello, World!";
        let hash = shake128::hash(message, 32).unwrap();
        assert_eq!(hash.len(), 32);

        // Same input should produce same output
        let hash2 = shake128::hash(message, 32).unwrap();
        assert_eq!(hash, hash2);

        // Different output lengths are prefixes of each other
        let hash_short = shake128::hash(message, 16).unwrap();
        let hash_long = shake128::hash(message, 32).unwrap();
        assert_eq!(&hash_short[..], &hash_long[..16]);
    }

    #[test]
    fn test_shake256_hash() {
        let message = b"Hello, World!";
        let hash = shake256::hash(message, 64).unwrap();
        assert_eq!(hash.len(), 64);

        // Prefix property
        let hash_short = shake256::hash(message, 32).unwrap();
        assert_eq!(&hash_short[..], &hash[..32]);
    }

    #[test]
    fn test_turboshake128_hash() {
        let message = b"Hello, World!";
        let hash = turboshake128::hash(message, 32).unwrap();
        assert_eq!(hash.len(), 32);

        // Different from SHAKE128 (different number of rounds)
        let shake_hash = shake128::hash(message, 32).unwrap();
        assert_ne!(hash, shake_hash);
    }

    #[test]
    fn test_turboshake256_hash() {
        let message = b"Hello, World!";
        let hash = turboshake256::hash(message, 64).unwrap();
        assert_eq!(hash.len(), 64);

        // Different from SHAKE256
        let shake_hash = shake256::hash(message, 64).unwrap();
        assert_ne!(hash, shake_hash);
    }

    #[test]
    fn test_shake128_incremental() {
        let message = b"Hello, World!";

        // One-shot
        let hash1 = shake128::hash(message, 32).unwrap();

        // Incremental
        let mut state = shake128::State::new().unwrap();
        state.update(b"Hello, ").unwrap();
        state.update(b"World!").unwrap();
        let hash2 = state.squeeze(32).unwrap();

        assert_eq!(hash1, hash2);
    }

    #[test]
    fn test_shake256_incremental() {
        let message = b"Hello, World!";

        let hash1 = shake256::hash(message, 64).unwrap();

        let mut state = shake256::State::new().unwrap();
        state.update(message).unwrap();
        let hash2 = state.squeeze(64).unwrap();

        assert_eq!(hash1, hash2);
    }

    #[test]
    fn test_turboshake128_incremental() {
        let message = b"Hello, World!";

        let hash1 = turboshake128::hash(message, 32).unwrap();

        let mut state = turboshake128::State::new().unwrap();
        state.update(b"Hello, ").unwrap();
        state.update(b"World!").unwrap();
        let hash2 = state.squeeze(32).unwrap();

        assert_eq!(hash1, hash2);
    }

    #[test]
    fn test_turboshake256_incremental() {
        let message = b"Hello, World!";

        let hash1 = turboshake256::hash(message, 64).unwrap();

        let mut state = turboshake256::State::new().unwrap();
        state.update(message).unwrap();
        let hash2 = state.squeeze(64).unwrap();

        assert_eq!(hash1, hash2);
    }

    #[test]
    fn test_incremental_squeeze() {
        // Squeezing in parts should equal squeezing all at once
        let message = b"seed";

        let full = turboshake128::hash(message, 96).unwrap();

        let mut state = turboshake128::State::new().unwrap();
        state.update(message).unwrap();
        let part1 = state.squeeze(32).unwrap();
        let part2 = state.squeeze(32).unwrap();
        let part3 = state.squeeze(32).unwrap();

        let mut combined = Vec::new();
        combined.extend_from_slice(&part1);
        combined.extend_from_slice(&part2);
        combined.extend_from_slice(&part3);

        assert_eq!(full, combined);
    }

    #[test]
    fn test_domain_separation() {
        let message = b"same input";

        // Different domains should produce different outputs
        let mut state1 = turboshake128::State::new_with_domain(0x01).unwrap();
        let mut state2 = turboshake128::State::new_with_domain(0x02).unwrap();

        state1.update(message).unwrap();
        state2.update(message).unwrap();

        let hash1 = state1.squeeze(32).unwrap();
        let hash2 = state2.squeeze(32).unwrap();

        assert_ne!(hash1, hash2);

        // Standard domain should also be different
        let mut state3 = turboshake128::State::new().unwrap();
        state3.update(message).unwrap();
        let hash3 = state3.squeeze(32).unwrap();

        assert_ne!(hash1, hash3);
        assert_ne!(hash2, hash3);
    }

    #[test]
    fn test_invalid_domain() {
        // Domain 0 is invalid
        assert!(shake128::State::new_with_domain(0x00).is_err());
        assert!(shake256::State::new_with_domain(0x00).is_err());
        assert!(turboshake128::State::new_with_domain(0x00).is_err());
        assert!(turboshake256::State::new_with_domain(0x00).is_err());

        // Domain > 0x7F is invalid
        assert!(shake128::State::new_with_domain(0x80).is_err());
        assert!(shake256::State::new_with_domain(0x80).is_err());
        assert!(turboshake128::State::new_with_domain(0x80).is_err());
        assert!(turboshake256::State::new_with_domain(0x80).is_err());

        // Valid domain
        assert!(turboshake128::State::new_with_domain(0x01).is_ok());
        assert!(turboshake128::State::new_with_domain(0x7F).is_ok());
    }

    #[test]
    fn test_no_update_after_squeeze() {
        let mut state = turboshake128::State::new().unwrap();
        state.update(b"data").unwrap();
        state.squeeze(32).unwrap();

        // Should fail to update after squeezing
        assert!(state.update(b"more data").is_err());
    }

    #[test]
    fn test_squeeze_into() {
        let message = b"test";
        let mut state = turboshake128::State::new().unwrap();
        state.update(message).unwrap();

        let mut output = [0u8; 32];
        state.squeeze_into(&mut output).unwrap();

        let expected = turboshake128::hash(message, 32).unwrap();
        assert_eq!(&output[..], &expected[..]);
    }

    #[test]
    fn test_variable_output_lengths() {
        let message = b"test";

        // Various output sizes
        for len in [1, 16, 32, 64, 100, 256, 1000] {
            let output = turboshake128::hash(message, len).unwrap();
            assert_eq!(output.len(), len);
        }
    }

    #[test]
    fn test_empty_input() {
        // Empty input should work
        let hash = turboshake128::hash(&[], 32).unwrap();
        assert_eq!(hash.len(), 32);

        let mut state = turboshake128::State::new().unwrap();
        let hash2 = state.squeeze(32).unwrap();
        assert_eq!(hash, hash2);
    }
}