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
//! The blosc `bytes->bytes` codec.
//!
//! It uses the [blosc](https://www.blosc.org/) container format.
//!
//! See <https://zarr-specs.readthedocs.io/en/latest/v3/codecs/blosc/v1.0.html>.

// NOTE: Zarr implementations MAY provide users an option to choose a shuffle mode automatically based on the typesize or other information, but MUST record in the metadata the mode that is chosen.

mod blosc_codec;
mod blosc_configuration;
mod blosc_partial_decoder;

use std::{
    ffi::c_int,
    ffi::{c_char, c_void},
};

pub use blosc_codec::BloscCodec;
pub use blosc_configuration::{BloscCodecConfiguration, BloscCodecConfigurationV1};
use blosc_sys::{
    blosc_cbuffer_validate, blosc_compress_ctx, blosc_decompress_ctx, BLOSC_BITSHUFFLE,
    BLOSC_BLOSCLZ_COMPNAME, BLOSC_LZ4HC_COMPNAME, BLOSC_LZ4_COMPNAME, BLOSC_MAX_OVERHEAD,
    BLOSC_NOSHUFFLE, BLOSC_SHUFFLE, BLOSC_SNAPPY_COMPNAME, BLOSC_ZLIB_COMPNAME,
    BLOSC_ZSTD_COMPNAME,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Debug, Error)]
#[error("blosc error")]
struct BloscError;

/// An integer from 0 to 9 controlling the compression level
///
/// A level of 1 is the fastest compression method and produces the least compressions, while 9 is slowest and produces the most compression.
/// Compression is turned off when the compression level is 0.
#[derive(Serialize, Copy, Clone, Debug, Eq, PartialEq)]
pub struct BloscCompressionLevel(u8);

impl TryFrom<u8> for BloscCompressionLevel {
    type Error = u8;
    fn try_from(level: u8) -> Result<Self, Self::Error> {
        if level <= 9 {
            Ok(Self(level))
        } else {
            Err(level)
        }
    }
}

impl<'de> serde::Deserialize<'de> for BloscCompressionLevel {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let level = u8::deserialize(d)?;
        if level <= 9 {
            Ok(Self(level))
        } else {
            Err(serde::de::Error::custom("clevel must be between 0 and 9"))
        }
    }
}

/// The blosc shuffle mode.
#[derive(Serialize, Deserialize, Copy, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
#[repr(u32)]
pub enum BloscShuffleMode {
    /// No shuffling.
    NoShuffle = BLOSC_NOSHUFFLE,
    /// Byte-wise shuffling.
    Shuffle = BLOSC_SHUFFLE,
    /// Bit-wise shuffling.
    BitShuffle = BLOSC_BITSHUFFLE,
}

/// The blosc compressor.
///
/// See <https://www.blosc.org/pages/>.
#[derive(Serialize, Deserialize, Copy, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum BloscCompressor {
    /// [BloscLZ](https://github.com/Blosc/c-blosc/blob/master/blosc/blosclz.h): blosc default compressor, heavily based on [FastLZ](http://fastlz.org/).
    BloscLZ,
    /// [LZ4](http://fastcompression.blogspot.com/p/lz4.html): a compact, very popular and fast compressor.
    LZ4,
    /// [LZ4HC](http://fastcompression.blogspot.com/p/lz4.html): a tweaked version of LZ4, produces better compression ratios at the expense of speed.
    LZ4HC,
    /// [Snappy](https://code.google.com/p/snappy): a popular compressor used in many places.
    Snappy,
    /// [Zlib](http://www.zlib.net/): a classic; somewhat slower than the previous ones, but achieving better compression ratios.
    Zlib,
    /// [Zstd](http://www.zstd.net/): an extremely well balanced codec; it provides the best compression ratios among the others above, and at reasonably fast speed.
    Zstd,
}

impl BloscCompressor {
    fn as_cstr(&self) -> *const u8 {
        match self {
            BloscCompressor::BloscLZ => BLOSC_BLOSCLZ_COMPNAME.as_ptr(),
            BloscCompressor::LZ4 => BLOSC_LZ4_COMPNAME.as_ptr(),
            BloscCompressor::LZ4HC => BLOSC_LZ4HC_COMPNAME.as_ptr(),
            BloscCompressor::Snappy => BLOSC_SNAPPY_COMPNAME.as_ptr(),
            BloscCompressor::Zlib => BLOSC_ZLIB_COMPNAME.as_ptr(),
            BloscCompressor::Zstd => BLOSC_ZSTD_COMPNAME.as_ptr(),
        }
    }
}

fn compress_bytes(
    src: &[u8],
    clevel: BloscCompressionLevel,
    shuffle_mode: BloscShuffleMode,
    typesize: usize,
    compressor: BloscCompressor,
    blocksize: usize,
) -> Result<Vec<u8>, BloscError> {
    // let mut dest = vec![0; src.len() + BLOSC_MAX_OVERHEAD as usize];
    let destsize = src.len() + BLOSC_MAX_OVERHEAD as usize;
    let mut dest: Vec<u8> = Vec::with_capacity(destsize);
    let destsize = unsafe {
        blosc_compress_ctx(
            c_int::from(clevel.0),
            shuffle_mode as c_int,
            typesize,
            src.len(),
            src.as_ptr().cast::<c_void>(),
            dest.as_mut_ptr().cast::<c_void>(),
            destsize,
            compressor.as_cstr().cast::<c_char>(),
            blocksize,
            1,
        )
    };
    if destsize > 0 {
        unsafe {
            #[allow(clippy::cast_sign_loss)]
            dest.set_len(destsize as usize);
        }
        dest.shrink_to_fit();
        Ok(dest)
    } else {
        Err(BloscError)
    }
}

fn decompress_bytes(src: &[u8]) -> Result<Vec<u8>, BloscError> {
    let mut destsize: usize = 0;
    let bytes_safe: bool = unsafe {
        blosc_cbuffer_validate(
            src.as_ptr().cast::<c_void>(),
            src.len(),
            std::ptr::addr_of_mut!(destsize),
        )
    } == 0;
    if bytes_safe {
        let mut dest: Vec<u8> = Vec::with_capacity(destsize);
        let destsize = unsafe {
            blosc_decompress_ctx(
                src.as_ptr().cast::<c_void>(),
                dest.as_mut_ptr().cast::<c_void>(),
                destsize,
                1,
            )
        };
        if destsize <= 0 {
            Err(BloscError)
        } else {
            unsafe {
                #[allow(clippy::cast_sign_loss)]
                dest.set_len(destsize as usize);
            }
            dest.shrink_to_fit();
            Ok(dest)
        }
    } else {
        Err(BloscError)
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        array::{
            codec::BytesToBytesCodecTraits, ArrayRepresentation, BytesRepresentation, DataType,
            FillValue,
        },
        array_subset::ArraySubset,
        byte_range::ByteRange,
    };

    use super::*;

    const JSON_VALID1: &'static str = r#"
{
    "cname": "lz4",
    "clevel": 5,
    "shuffle": "shuffle",
    "typesize": 4,
    "blocksize": 0
}"#;

    const JSON_VALID2: &'static str = r#"
{
    "cname": "lz4",
    "clevel": 4,
    "shuffle": "bitshuffle",
    "typesize": 4,
    "blocksize": 0
}"#;

    #[test]
    fn codec_blosc_round_trip1() {
        let elements: Vec<u16> = (0..32).collect();
        let bytes = safe_transmute::transmute_to_bytes(&elements).to_vec();
        let bytes_representation = BytesRepresentation::KnownSize(bytes.len());

        let codec_configuration: BloscCodecConfiguration =
            serde_json::from_str(JSON_VALID1).unwrap();
        let codec = BloscCodec::new_with_configuration(&codec_configuration).unwrap();

        let encoded = codec.encode(bytes.clone()).unwrap();
        let decoded = codec
            .decode(encoded.clone(), &bytes_representation)
            .unwrap();
        assert_eq!(bytes, decoded);
    }

    #[test]
    fn codec_blosc_round_trip2() {
        let elements: Vec<u16> = (0..32).collect();
        let bytes = safe_transmute::transmute_to_bytes(&elements).to_vec();
        let bytes_representation = BytesRepresentation::KnownSize(bytes.len());

        let codec_configuration: BloscCodecConfiguration =
            serde_json::from_str(JSON_VALID2).unwrap();
        let codec = BloscCodec::new_with_configuration(&codec_configuration).unwrap();

        let encoded = codec.encode(bytes.clone()).unwrap();
        let decoded = codec
            .decode(encoded.clone(), &bytes_representation)
            .unwrap();
        assert_eq!(bytes, decoded);
    }

    #[test]
    fn codec_blosc_partial_decode() {
        let array_representation =
            ArrayRepresentation::new(vec![2, 2, 2], DataType::UInt16, FillValue::from(0u16))
                .unwrap();
        let bytes_representation = BytesRepresentation::KnownSize(array_representation.size());

        let elements: Vec<u16> = (0..array_representation.num_elements() as u16).collect();
        let bytes = safe_transmute::transmute_to_bytes(&elements).to_vec();

        let codec_configuration: BloscCodecConfiguration =
            serde_json::from_str(JSON_VALID2).unwrap();
        let codec = BloscCodec::new_with_configuration(&codec_configuration).unwrap();

        let encoded = codec.encode(bytes.clone()).unwrap();
        let decoded_regions: Vec<ByteRange> =
            ArraySubset::new_with_start_shape(vec![0, 1, 0], vec![2, 1, 1])
                .unwrap()
                .byte_ranges(
                    array_representation.shape(),
                    array_representation.element_size(),
                )
                .unwrap();
        let input_handle = Box::new(std::io::Cursor::new(encoded));
        let partial_decoder = codec.partial_decoder(input_handle);
        let decoded = partial_decoder
            .partial_decode(&bytes_representation, &decoded_regions)
            .unwrap();

        let decoded: Vec<u16> = decoded
            .into_iter()
            .flatten()
            .collect::<Vec<_>>()
            .chunks(std::mem::size_of::<u16>())
            .map(|b| u16::from_ne_bytes(b.try_into().unwrap()))
            .collect();

        let answer: Vec<u16> = vec![2, 6];
        assert_eq!(answer, decoded);
    }
}