snappy_cpp/
lib.rs

1/*!
2This library provides zero-overhead bindings to Google's Snappy C++ library.
3
4These bindings should only be used in testing and benchmarks.
5*/
6
7extern crate libc;
8
9use libc::{c_int, size_t};
10
11/// Compress the bytes in `src` into `dst`. `dst` must be big enough to
12/// hold the maximum compressed size of the bytes in `src`.
13///
14/// If there was a problem compressing `src`, an error is returned.
15pub fn compress(src: &[u8], dst: &mut [u8]) -> Result<usize, String> {
16    unsafe {
17        let mut dst_len = snappy_max_compressed_length(src.len());
18        if dst.len() < dst_len {
19            return Err(format!(
20                "destination buffer too small ({} < {})",
21                dst.len(), dst_len));
22        }
23        snappy_compress(
24            src.as_ptr(),
25            src.len(),
26            dst.as_mut_ptr(),
27            &mut dst_len);
28        Ok(dst_len)
29    }
30}
31
32/// Decompress the bytes in `src` into `dst`. `dst` must be big enough to
33/// hold the the uncompressed size of the bytes in `src`.
34///
35/// If there was a problem decompressing `src`, an error is returned.
36pub fn decompress(src: &[u8], dst: &mut [u8]) -> Result<usize, String> {
37    unsafe {
38        let mut dst_len = 0;
39        snappy_uncompressed_length(
40            src.as_ptr(), src.len() as size_t, &mut dst_len);
41        if dst.len() < dst_len {
42            return Err(format!(
43                "destination buffer too small ({} < {})", dst.len(), dst_len));
44        }
45        let r = snappy_uncompress(
46            src.as_ptr(),
47            src.len(),
48            dst.as_mut_ptr(),
49            &mut dst_len);
50        if r == 0 {
51            Ok(dst_len)
52        } else {
53            Err("snappy: invalid input".to_owned())
54        }
55    }
56}
57
58extern {
59    fn snappy_compress(
60        input: *const u8,
61        input_len: size_t,
62        compressed: *mut u8,
63        compressed_len: *mut size_t,
64    ) -> c_int;
65
66    fn snappy_uncompress(
67        compressed: *const u8,
68        compressed_len: size_t,
69        uncompressed: *mut u8,
70        uncompressed_len: *mut size_t,
71    ) -> c_int;
72
73    fn snappy_max_compressed_length(input_len: size_t) -> size_t;
74
75    fn snappy_uncompressed_length(
76        compressed: *const u8,
77        compressed_len: size_t,
78        result: *mut size_t,
79    ) -> c_int;
80}