-
Notifications
You must be signed in to change notification settings - Fork 96
/
lib.rs
2123 lines (1860 loc) · 59.4 KB
/
lib.rs
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
#![no_std]
//! Minimal safe wrapper around zstd-sys.
//!
//! This crates provides a minimal translation of the [zstd-sys] methods.
//! For a more comfortable high-level library, see the [zstd] crate.
//!
//! [zstd-sys]: https://crates.io/crates/zstd-sys
//! [zstd]: https://crates.io/crates/zstd
//!
//! Most of the functions here map 1-for-1 to a function from
//! [the C zstd library][zstd-c] mentioned in their descriptions.
//! Check the [source documentation][doc] for more information on their
//! behaviour.
//!
//! [doc]: https://facebook.github.io/zstd/zstd_manual.html
//! [zstd-c]: https://facebook.github.io/zstd/
//!
//! Features denoted as experimental in the C library are hidden behind an
//! `experimental` feature.
#![cfg_attr(feature = "doc-cfg", feature(doc_cfg))]
#[cfg(feature = "std")]
extern crate std;
#[cfg(test)]
mod tests;
// Re-export zstd-sys
pub use zstd_sys;
/// How to compress data.
pub use zstd_sys::ZSTD_strategy as Strategy;
/// Reset directive.
pub use zstd_sys::ZSTD_ResetDirective as ResetDirective;
#[cfg(feature = "std")]
use std::os::raw::{c_char, c_int, c_ulonglong, c_void};
#[cfg(not(feature = "std"))]
use libc::{c_char, c_int, c_ulonglong, c_void};
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};
use core::ptr::NonNull;
use core::str;
include!("constants.rs");
#[cfg(feature = "experimental")]
include!("constants_experimental.rs");
/// Represents the compression level used by zstd.
pub type CompressionLevel = i32;
/// Represents a possible error from the zstd library.
pub type ErrorCode = usize;
/// Wrapper result around most zstd functions.
///
/// Either a success code (usually number of bytes written), or an error code.
pub type SafeResult = Result<usize, ErrorCode>;
/// Returns true if code represents error.
fn is_error(code: usize) -> bool {
unsafe { zstd_sys::ZSTD_isError(code) != 0 }
}
/// Parse the result code
///
/// Returns the number of bytes written if the code represents success,
/// or the error message code otherwise.
fn parse_code(code: usize) -> SafeResult {
if !is_error(code) {
Ok(code)
} else {
Err(code)
}
}
fn ptr_void(src: &[u8]) -> *const c_void {
src.as_ptr() as *const c_void
}
fn ptr_mut_void(dst: &mut (impl WriteBuf + ?Sized)) -> *mut c_void {
dst.as_mut_ptr() as *mut c_void
}
pub fn version_number() -> u32 {
unsafe { zstd_sys::ZSTD_versionNumber() as u32 }
}
pub fn version_string() -> &'static str {
unsafe { c_char_to_str(zstd_sys::ZSTD_versionString()) }
}
/// Returns the minimum (fastest) compression level supported.
pub fn min_c_level() -> CompressionLevel {
unsafe { zstd_sys::ZSTD_minCLevel() as CompressionLevel }
}
/// Returns the maximum (slowest) compression level supported.
pub fn max_c_level() -> CompressionLevel {
unsafe { zstd_sys::ZSTD_maxCLevel() as CompressionLevel }
}
/// Wraps the `ZSTD_compress` function.
pub fn compress<C: WriteBuf + ?Sized>(
dst: &mut C,
src: &[u8],
compression_level: CompressionLevel,
) -> SafeResult {
unsafe {
dst.write_from(|buffer, capacity| {
parse_code(zstd_sys::ZSTD_compress(
buffer,
capacity,
ptr_void(src),
src.len(),
compression_level,
))
})
}
}
/// Wraps the `ZSTD_decompress` function.
pub fn decompress<C: WriteBuf + ?Sized>(
dst: &mut C,
src: &[u8],
) -> SafeResult {
unsafe {
dst.write_from(|buffer, capacity| {
parse_code(zstd_sys::ZSTD_decompress(
buffer,
capacity,
ptr_void(src),
src.len(),
))
})
}
}
/// Wraps the `ZSTD_getDecompressedSize` function.
#[deprecated(note = "Use ZSTD_getFrameContentSize instead")]
pub fn get_decompressed_size(src: &[u8]) -> u64 {
unsafe {
zstd_sys::ZSTD_getDecompressedSize(ptr_void(src), src.len()) as u64
}
}
/// maximum compressed size in worst case single-pass scenario
pub fn compress_bound(src_size: usize) -> usize {
unsafe { zstd_sys::ZSTD_compressBound(src_size) }
}
pub struct CCtx<'a>(NonNull<zstd_sys::ZSTD_CCtx>, PhantomData<&'a ()>);
impl Default for CCtx<'_> {
fn default() -> Self {
CCtx::create()
}
}
impl CCtx<'static> {
/// Tries to create a new context.
///
/// Returns `None` if zstd returns a NULL pointer - may happen if allocation fails.
pub fn try_create() -> Option<Self> {
Some(CCtx(
NonNull::new(unsafe { zstd_sys::ZSTD_createCCtx() })?,
PhantomData,
))
}
/// Wrap `ZSTD_createCCtx`
///
/// # Panics
///
/// If zstd returns a NULL pointer.
pub fn create() -> Self {
Self::try_create()
.expect("zstd returned null pointer when creating new context")
}
}
impl<'a> CCtx<'a> {
/// Wraps the `ZSTD_compressCCtx()` function
pub fn compress<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
compression_level: CompressionLevel,
) -> SafeResult {
unsafe {
dst.write_from(|buffer, capacity| {
parse_code(zstd_sys::ZSTD_compressCCtx(
self.0.as_ptr(),
buffer,
capacity,
ptr_void(src),
src.len(),
compression_level,
))
})
}
}
/// Wraps the `ZSTD_compress2()` function.
pub fn compress2<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
) -> SafeResult {
unsafe {
dst.write_from(|buffer, capacity| {
parse_code(zstd_sys::ZSTD_compress2(
self.0.as_ptr(),
buffer,
capacity,
ptr_void(src),
src.len(),
))
})
}
}
/// Wraps the `ZSTD_compress_usingDict()` function.
pub fn compress_using_dict<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
dict: &[u8],
compression_level: CompressionLevel,
) -> SafeResult {
unsafe {
dst.write_from(|buffer, capacity| {
parse_code(zstd_sys::ZSTD_compress_usingDict(
self.0.as_ptr(),
buffer,
capacity,
ptr_void(src),
src.len(),
ptr_void(dict),
dict.len(),
compression_level,
))
})
}
}
/// Wraps the `ZSTD_compress_usingCDict()` function.
pub fn compress_using_cdict<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
cdict: &CDict<'_>,
) -> SafeResult {
unsafe {
dst.write_from(|buffer, capacity| {
parse_code(zstd_sys::ZSTD_compress_usingCDict(
self.0.as_ptr(),
buffer,
capacity,
ptr_void(src),
src.len(),
cdict.0.as_ptr(),
))
})
}
}
pub fn init(&mut self, compression_level: CompressionLevel) -> usize {
unsafe {
zstd_sys::ZSTD_initCStream(self.0.as_ptr(), compression_level)
}
}
/// Wraps the `ZSTD_initCStream_srcSize()` function.
#[cfg(feature = "experimental")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
#[deprecated]
pub fn init_src_size(
&mut self,
compression_level: CompressionLevel,
pledged_src_size: u64,
) -> usize {
unsafe {
zstd_sys::ZSTD_initCStream_srcSize(
self.0.as_ptr(),
compression_level as c_int,
pledged_src_size as c_ulonglong,
)
}
}
/// Wraps the `ZSTD_initCStream_usingDict()` function.
#[cfg(feature = "experimental")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
#[deprecated]
pub fn init_using_dict(
&mut self,
dict: &[u8],
compression_level: CompressionLevel,
) -> SafeResult {
let code = unsafe {
zstd_sys::ZSTD_initCStream_usingDict(
self.0.as_ptr(),
ptr_void(dict),
dict.len(),
compression_level,
)
};
parse_code(code)
}
/// Wraps the `ZSTD_initCStream_usingCDict()` function.
#[cfg(feature = "experimental")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
#[deprecated]
pub fn init_using_cdict<'b>(&mut self, cdict: &CDict<'b>) -> SafeResult
where
'b: 'a, // Dictionary outlives the stream.
{
let code = unsafe {
zstd_sys::ZSTD_initCStream_usingCDict(
self.0.as_ptr(),
cdict.0.as_ptr(),
)
};
parse_code(code)
}
pub fn load_dictionary(&mut self, dict: &[u8]) -> SafeResult {
parse_code(unsafe {
zstd_sys::ZSTD_CCtx_loadDictionary(
self.0.as_ptr(),
ptr_void(dict),
dict.len(),
)
})
}
/// Wraps the `ZSTD_CCtx_refCDict()` function.
///
/// Dictionary must outlive the context.
pub fn ref_cdict<'b>(&mut self, cdict: &CDict<'b>) -> SafeResult
where
'b: 'a,
{
parse_code(unsafe {
zstd_sys::ZSTD_CCtx_refCDict(self.0.as_ptr(), cdict.0.as_ptr())
})
}
pub fn ref_prefix<'b>(&mut self, prefix: &'b [u8]) -> SafeResult
where
'b: 'a,
{
parse_code(unsafe {
zstd_sys::ZSTD_CCtx_refPrefix(
self.0.as_ptr(),
ptr_void(prefix),
prefix.len(),
)
})
}
pub fn compress_stream<C: WriteBuf + ?Sized>(
&mut self,
output: &mut OutBuffer<'_, C>,
input: &mut InBuffer<'_>,
) -> SafeResult {
let mut output = output.wrap();
let mut input = input.wrap();
let code = unsafe {
zstd_sys::ZSTD_compressStream(
self.0.as_ptr(),
ptr_mut(&mut output),
ptr_mut(&mut input),
)
};
parse_code(code)
}
/// Wraps the `ZSTD_compressStream2()` function.
pub fn compress_stream2<C: WriteBuf + ?Sized>(
&mut self,
output: &mut OutBuffer<'_, C>,
input: &mut InBuffer<'_>,
end_op: zstd_sys::ZSTD_EndDirective,
) -> SafeResult {
let mut output = output.wrap();
let mut input = input.wrap();
parse_code(unsafe {
zstd_sys::ZSTD_compressStream2(
self.0.as_ptr(),
ptr_mut(&mut output),
ptr_mut(&mut input),
end_op,
)
})
}
/// Wraps the `ZSTD_flushStream()` function.
pub fn flush_stream<C: WriteBuf + ?Sized>(
&mut self,
output: &mut OutBuffer<'_, C>,
) -> SafeResult {
let mut output = output.wrap();
let code = unsafe {
zstd_sys::ZSTD_flushStream(self.0.as_ptr(), ptr_mut(&mut output))
};
parse_code(code)
}
/// Wraps the `ZSTD_endStream()` function.
pub fn end_stream<C: WriteBuf + ?Sized>(
&mut self,
output: &mut OutBuffer<'_, C>,
) -> SafeResult {
let mut output = output.wrap();
let code = unsafe {
zstd_sys::ZSTD_endStream(self.0.as_ptr(), ptr_mut(&mut output))
};
parse_code(code)
}
pub fn sizeof(&self) -> usize {
unsafe { zstd_sys::ZSTD_sizeof_CCtx(self.0.as_ptr()) }
}
pub fn reset(&mut self, reset: ResetDirective) -> SafeResult {
parse_code(unsafe {
zstd_sys::ZSTD_CCtx_reset(self.0.as_ptr(), reset)
})
}
#[cfg(feature = "experimental")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
#[deprecated]
pub fn reset_cstream(&mut self, pledged_src_size: u64) -> SafeResult {
let code = unsafe {
zstd_sys::ZSTD_resetCStream(
self.0.as_ptr(),
pledged_src_size as c_ulonglong,
)
};
parse_code(code)
}
pub fn set_parameter(&mut self, param: CParameter) -> SafeResult {
// TODO: Until bindgen properly generates a binding for this, we'll need to do it here.
#[cfg(feature = "experimental")]
use zstd_sys::ZSTD_cParameter::{
ZSTD_c_experimentalParam1 as ZSTD_c_rsyncable,
ZSTD_c_experimentalParam10 as ZSTD_c_stableOutBuffer,
ZSTD_c_experimentalParam11 as ZSTD_c_blockDelimiters,
ZSTD_c_experimentalParam12 as ZSTD_c_validateSequences,
ZSTD_c_experimentalParam13 as ZSTD_c_useBlockSplitter,
ZSTD_c_experimentalParam14 as ZSTD_c_useRowMatchFinder,
ZSTD_c_experimentalParam15 as ZSTD_c_deterministicRefPrefix,
ZSTD_c_experimentalParam2 as ZSTD_c_format,
ZSTD_c_experimentalParam3 as ZSTD_c_forceMaxWindow,
ZSTD_c_experimentalParam4 as ZSTD_c_forceAttachDict,
ZSTD_c_experimentalParam5 as ZSTD_c_literalCompressionMode,
ZSTD_c_experimentalParam6 as ZSTD_c_targetCBlockSize,
ZSTD_c_experimentalParam7 as ZSTD_c_srcSizeHint,
ZSTD_c_experimentalParam8 as ZSTD_c_enableDedicatedDictSearch,
ZSTD_c_experimentalParam9 as ZSTD_c_stableInBuffer,
};
use zstd_sys::ZSTD_cParameter::*;
use CParameter::*;
let (param, value) = match param {
#[cfg(feature = "experimental")]
RSyncable(rsyncable) => (ZSTD_c_rsyncable, rsyncable as c_int),
#[cfg(feature = "experimental")]
Format(format) => (ZSTD_c_format, format as c_int),
#[cfg(feature = "experimental")]
ForceMaxWindow(force) => (ZSTD_c_forceMaxWindow, force as c_int),
#[cfg(feature = "experimental")]
ForceAttachDict(force) => (ZSTD_c_forceAttachDict, force as c_int),
#[cfg(feature = "experimental")]
TargetCBlockSize(value) => {
(ZSTD_c_targetCBlockSize, value as c_int)
}
#[cfg(feature = "experimental")]
SrcSizeHint(value) => (ZSTD_c_srcSizeHint, value as c_int),
#[cfg(feature = "experimental")]
EnableDedicatedDictSearch(enable) => {
(ZSTD_c_enableDedicatedDictSearch, enable as c_int)
}
#[cfg(feature = "experimental")]
StableInBuffer(stable) => (ZSTD_c_stableInBuffer, stable as c_int),
#[cfg(feature = "experimental")]
StableOutBuffer(stable) => {
(ZSTD_c_stableOutBuffer, stable as c_int)
}
#[cfg(feature = "experimental")]
BlockDelimiters(value) => (ZSTD_c_blockDelimiters, value as c_int),
#[cfg(feature = "experimental")]
ValidateSequences(validate) => {
(ZSTD_c_validateSequences, validate as c_int)
}
#[cfg(feature = "experimental")]
UseBlockSplitter(split) => {
(ZSTD_c_useBlockSplitter, split as c_int)
}
#[cfg(feature = "experimental")]
UseRowMatchFinder(mode) => {
(ZSTD_c_useRowMatchFinder, mode as c_int)
}
#[cfg(feature = "experimental")]
DeterministicRefPrefix(deterministic) => {
(ZSTD_c_deterministicRefPrefix, deterministic as c_int)
}
CompressionLevel(level) => (ZSTD_c_compressionLevel, level),
WindowLog(value) => (ZSTD_c_windowLog, value as c_int),
HashLog(value) => (ZSTD_c_hashLog, value as c_int),
ChainLog(value) => (ZSTD_c_chainLog, value as c_int),
SearchLog(value) => (ZSTD_c_searchLog, value as c_int),
MinMatch(value) => (ZSTD_c_minMatch, value as c_int),
TargetLength(value) => (ZSTD_c_targetLength, value as c_int),
Strategy(strategy) => (ZSTD_c_strategy, strategy as c_int),
#[cfg(feature = "experimental")]
LiteralCompressionMode(mode) => {
(ZSTD_c_literalCompressionMode, mode as c_int)
}
EnableLongDistanceMatching(flag) => {
(ZSTD_c_enableLongDistanceMatching, flag as c_int)
}
LdmHashLog(value) => (ZSTD_c_ldmHashLog, value as c_int),
LdmMinMatch(value) => (ZSTD_c_ldmMinMatch, value as c_int),
LdmBucketSizeLog(value) => {
(ZSTD_c_ldmBucketSizeLog, value as c_int)
}
LdmHashRateLog(value) => (ZSTD_c_ldmHashRateLog, value as c_int),
ContentSizeFlag(flag) => (ZSTD_c_contentSizeFlag, flag as c_int),
ChecksumFlag(flag) => (ZSTD_c_checksumFlag, flag as c_int),
DictIdFlag(flag) => (ZSTD_c_dictIDFlag, flag as c_int),
NbWorkers(value) => (ZSTD_c_nbWorkers, value as c_int),
JobSize(value) => (ZSTD_c_jobSize, value as c_int),
OverlapSizeLog(value) => (ZSTD_c_overlapLog, value as c_int),
};
parse_code(unsafe {
zstd_sys::ZSTD_CCtx_setParameter(self.0.as_ptr(), param, value)
})
}
pub fn set_pledged_src_size(
&mut self,
pledged_src_size: u64,
) -> SafeResult {
parse_code(unsafe {
zstd_sys::ZSTD_CCtx_setPledgedSrcSize(
self.0.as_ptr(),
pledged_src_size as c_ulonglong,
)
})
}
/// Creates a copy of this context.
///
/// This only works before any data has been compressed. An error will be
/// returned otherwise.
#[cfg(feature = "experimental")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
pub fn try_clone(
&self,
pledged_src_size: Option<u64>,
) -> Result<Self, ErrorCode> {
let context = NonNull::new(unsafe { zstd_sys::ZSTD_createCCtx() })
.ok_or(0usize)?;
parse_code(unsafe {
zstd_sys::ZSTD_copyCCtx(
context.as_ptr(),
self.0.as_ptr(),
pledged_src_size.unwrap_or(CONTENTSIZE_UNKNOWN),
)
})?;
Ok(CCtx(context, self.1))
}
/// Wraps the `ZSTD_getBlockSize()` function.
#[cfg(feature = "experimental")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
pub fn get_block_size(&self) -> usize {
unsafe { zstd_sys::ZSTD_getBlockSize(self.0.as_ptr()) }
}
/// Wraps the `ZSTD_compressBlock()` function.
#[cfg(feature = "experimental")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
pub fn compress_block<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
) -> SafeResult {
unsafe {
dst.write_from(|buffer, capacity| {
parse_code(zstd_sys::ZSTD_compressBlock(
self.0.as_ptr(),
buffer,
capacity,
ptr_void(src),
src.len(),
))
})
}
}
pub fn in_size() -> usize {
unsafe { zstd_sys::ZSTD_CStreamInSize() }
}
pub fn out_size() -> usize {
unsafe { zstd_sys::ZSTD_CStreamOutSize() }
}
}
pub fn create_cctx<'a>() -> CCtx<'a> {
CCtx::create()
}
impl<'a> Drop for CCtx<'a> {
fn drop(&mut self) {
unsafe {
zstd_sys::ZSTD_freeCCtx(self.0.as_ptr());
}
}
}
unsafe impl<'a> Send for CCtx<'a> {}
// CCtx can't be shared across threads, so it does not implement Sync.
unsafe fn c_char_to_str(text: *const c_char) -> &'static str {
#[cfg(not(feature = "std"))]
{
// To be safe, we need to compute right now its length
let len = libc::strlen(text);
// Cast it to a slice
let slice = core::slice::from_raw_parts(text as *mut u8, len);
// And hope it's still text.
str::from_utf8(slice).expect("bad error message from zstd")
}
#[cfg(feature = "std")]
{
std::ffi::CStr::from_ptr(text)
.to_str()
.expect("bad error message from zstd")
}
}
pub fn get_error_name(code: usize) -> &'static str {
unsafe {
let name = zstd_sys::ZSTD_getErrorName(code);
c_char_to_str(name)
}
}
/// Wraps the `ZSTD_compressCCtx()` function
pub fn compress_cctx(
ctx: &mut CCtx<'_>,
dst: &mut [u8],
src: &[u8],
compression_level: CompressionLevel,
) -> SafeResult {
ctx.compress(dst, src, compression_level)
}
/// Wraps the `ZSTD_compress2()` function.
pub fn compress2(
ctx: &mut CCtx<'_>,
dst: &mut [u8],
src: &[u8],
) -> SafeResult {
ctx.compress2(dst, src)
}
/// A Decompression Context.
///
/// The lifetime references the potential dictionary used for this context.
///
/// If no dictionary was used, it will most likely be `'static`.
///
/// Same as `DStream`.
pub struct DCtx<'a>(NonNull<zstd_sys::ZSTD_DCtx>, PhantomData<&'a ()>);
impl Default for DCtx<'_> {
fn default() -> Self {
DCtx::create()
}
}
impl DCtx<'static> {
pub fn try_create() -> Option<Self> {
Some(DCtx(
NonNull::new(unsafe { zstd_sys::ZSTD_createDCtx() })?,
PhantomData,
))
}
pub fn create() -> Self {
Self::try_create()
.expect("zstd returned null pointer when creating new context")
}
}
impl<'a> DCtx<'a> {
/// Wraps the `ZSTD_decompressDCtx()` function.
pub fn decompress<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
) -> SafeResult {
unsafe {
dst.write_from(|buffer, capacity| {
parse_code(zstd_sys::ZSTD_decompressDCtx(
self.0.as_ptr(),
buffer,
capacity,
ptr_void(src),
src.len(),
))
})
}
}
/// Wraps `ZSTD_decompress_usingDict`
pub fn decompress_using_dict<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
dict: &[u8],
) -> SafeResult {
unsafe {
dst.write_from(|buffer, capacity| {
parse_code(zstd_sys::ZSTD_decompress_usingDict(
self.0.as_ptr(),
buffer,
capacity,
ptr_void(src),
src.len(),
ptr_void(dict),
dict.len(),
))
})
}
}
/// Wraps the `ZSTD_decompress_usingDDict()` function.
pub fn decompress_using_ddict<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
ddict: &DDict<'_>,
) -> SafeResult {
unsafe {
dst.write_from(|buffer, capacity| {
parse_code(zstd_sys::ZSTD_decompress_usingDDict(
self.0.as_ptr(),
buffer,
capacity,
ptr_void(src),
src.len(),
ddict.0.as_ptr(),
))
})
}
}
/// Wraps the `ZSTD_initCStream()` function.
///
/// Initializes an existing `DStream` for decompression.
pub fn init(&mut self) -> usize {
unsafe { zstd_sys::ZSTD_initDStream(self.0.as_ptr()) }
}
/// Wraps the `ZSTD_initDStream_usingDict()` function.
#[cfg(feature = "experimental")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
#[deprecated]
pub fn init_using_dict(&mut self, dict: &[u8]) -> SafeResult {
let code = unsafe {
zstd_sys::ZSTD_initDStream_usingDict(
self.0.as_ptr(),
ptr_void(dict),
dict.len(),
)
};
parse_code(code)
}
/// Wraps the `ZSTD_initDStream_usingDDict()` function.
#[cfg(feature = "experimental")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
#[deprecated]
pub fn init_using_ddict<'b>(&mut self, ddict: &DDict<'b>) -> SafeResult
where
'b: 'a,
{
let code = unsafe {
zstd_sys::ZSTD_initDStream_usingDDict(
self.0.as_ptr(),
ddict.0.as_ptr(),
)
};
parse_code(code)
}
/// Wraps the `ZSTD_resetDStream()` function.
pub fn reset(&mut self) -> SafeResult {
let code = unsafe {
zstd_sys::ZSTD_DCtx_reset(
self.0.as_ptr(),
ResetDirective::ZSTD_reset_session_only,
)
};
parse_code(code)
}
pub fn load_dictionary(&mut self, dict: &[u8]) -> SafeResult {
parse_code(unsafe {
zstd_sys::ZSTD_DCtx_loadDictionary(
self.0.as_ptr(),
ptr_void(dict),
dict.len(),
)
})
}
pub fn ref_ddict<'b>(&mut self, ddict: &DDict<'b>) -> SafeResult
where
'b: 'a,
{
parse_code(unsafe {
zstd_sys::ZSTD_DCtx_refDDict(self.0.as_ptr(), ddict.0.as_ptr())
})
}
pub fn ref_prefix<'b>(&mut self, prefix: &'b [u8]) -> SafeResult
where
'b: 'a,
{
parse_code(unsafe {
zstd_sys::ZSTD_DCtx_refPrefix(
self.0.as_ptr(),
ptr_void(prefix),
prefix.len(),
)
})
}
pub fn set_parameter(&mut self, param: DParameter) -> SafeResult {
#[cfg(feature = "experimental")]
use zstd_sys::ZSTD_dParameter::{
ZSTD_d_experimentalParam1 as ZSTD_d_format,
ZSTD_d_experimentalParam2 as ZSTD_d_stableOutBuffer,
ZSTD_d_experimentalParam3 as ZSTD_d_forceIgnoreChecksum,
ZSTD_d_experimentalParam4 as ZSTD_d_refMultipleDDicts,
};
use zstd_sys::ZSTD_dParameter::*;
use DParameter::*;
let (param, value) = match param {
#[cfg(feature = "experimental")]
Format(format) => (ZSTD_d_format, format as c_int),
#[cfg(feature = "experimental")]
StableOutBuffer(stable) => {
(ZSTD_d_stableOutBuffer, stable as c_int)
}
#[cfg(feature = "experimental")]
ForceIgnoreChecksum(force) => {
(ZSTD_d_forceIgnoreChecksum, force as c_int)
}
#[cfg(feature = "experimental")]
RefMultipleDDicts(value) => {
(ZSTD_d_refMultipleDDicts, value as c_int)
}
WindowLogMax(value) => (ZSTD_d_windowLogMax, value as c_int),
};
parse_code(unsafe {
zstd_sys::ZSTD_DCtx_setParameter(self.0.as_ptr(), param, value)
})
}
/// Wraps the `ZSTD_decompressStream()` function.
pub fn decompress_stream<C: WriteBuf + ?Sized>(
&mut self,
output: &mut OutBuffer<'_, C>,
input: &mut InBuffer<'_>,
) -> SafeResult {
let mut output = output.wrap();
let mut input = input.wrap();
let code = unsafe {
zstd_sys::ZSTD_decompressStream(
self.0.as_ptr(),
ptr_mut(&mut output),
ptr_mut(&mut input),
)
};
parse_code(code)
}
/// Wraps the `ZSTD_DStreamInSize()` function.
///
/// Returns a hint for the recommended size of the input buffer for decompression.
pub fn in_size() -> usize {
unsafe { zstd_sys::ZSTD_DStreamInSize() }
}
/// Wraps the `ZSTD_DStreamOutSize()` function.
///
/// Returns a hint for the recommended size of the output buffer for decompression.
pub fn out_size() -> usize {
unsafe { zstd_sys::ZSTD_DStreamOutSize() }
}
/// Wraps the `ZSTD_sizeof_DCtx()` function.
pub fn sizeof(&self) -> usize {
unsafe { zstd_sys::ZSTD_sizeof_DCtx(self.0.as_ptr()) }
}
/// Wraps the `ZSTD_decompressBlock()` function.
#[cfg(feature = "experimental")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
pub fn decompress_block<C: WriteBuf + ?Sized>(
&mut self,
dst: &mut C,
src: &[u8],
) -> SafeResult {
unsafe {
dst.write_from(|buffer, capacity| {
parse_code(zstd_sys::ZSTD_decompressBlock(
self.0.as_ptr(),
buffer,
capacity,
ptr_void(src),
src.len(),
))
})
}
}
/// Wraps the `ZSTD_insertBlock()` function.
#[cfg(feature = "experimental")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
pub fn insert_block(&mut self, block: &[u8]) -> usize {
unsafe {
zstd_sys::ZSTD_insertBlock(
self.0.as_ptr(),
ptr_void(block),
block.len(),
)
}
}
/// Creates a copy of this context.
///
/// This only works before any data has been decompressed. An error will be
/// returned otherwise.
#[cfg(feature = "experimental")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "experimental")))]
pub fn try_clone(&self) -> Result<Self, ErrorCode> {
let context = NonNull::new(unsafe { zstd_sys::ZSTD_createDCtx() })
.ok_or(0usize)?;
unsafe { zstd_sys::ZSTD_copyDCtx(context.as_ptr(), self.0.as_ptr()) };
Ok(DCtx(context, self.1))
}
}
/// Prepares a new decompression context without dictionary.
pub fn create_dctx() -> DCtx<'static> {
DCtx::create()
}
impl Drop for DCtx<'_> {
fn drop(&mut self) {
unsafe {
zstd_sys::ZSTD_freeDCtx(self.0.as_ptr());
}
}
}
unsafe impl Send for DCtx<'_> {}
// DCtx can't be shared across threads, so it does not implement Sync.