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
use vortex_array::aliases::hash_set::HashSet;
use vortex_array::array::{VarBinArray, VarBinEncoding};
use vortex_array::encoding::{Encoding, EncodingRef};
use vortex_array::{ArrayDType, ArrayData, IntoArrayData};
use vortex_error::VortexResult;

use crate::compressors::{CompressedArray, CompressionTree, EncodingCompressor};
use crate::downscale::downscale_integer_array;
use crate::{constants, SamplingCompressor};

#[derive(Debug)]
pub struct VarBinCompressor;

impl EncodingCompressor for VarBinCompressor {
    fn id(&self) -> &str {
        VarBinEncoding::ID.as_ref()
    }

    fn cost(&self) -> u8 {
        constants::VARBIN_COST
    }

    fn can_compress(&self, array: &ArrayData) -> Option<&dyn EncodingCompressor> {
        array.is_encoding(VarBinEncoding::ID).then_some(self)
    }

    fn compress<'a>(
        &'a self,
        array: &ArrayData,
        like: Option<CompressionTree<'a>>,
        ctx: SamplingCompressor<'a>,
    ) -> VortexResult<CompressedArray<'a>> {
        let varbin_array = VarBinArray::try_from(array.clone())?;
        let offsets = ctx.auxiliary("offsets").compress(
            &downscale_integer_array(varbin_array.offsets())?,
            like.as_ref().and_then(|l| l.child(0)),
        )?;
        Ok(CompressedArray::compressed(
            VarBinArray::try_new(
                offsets.array,
                varbin_array.bytes(), // we don't compress the raw bytes
                array.dtype().clone(),
                varbin_array.validity(),
            )?
            .into_array(),
            Some(CompressionTree::new(self, vec![offsets.path, None, None])),
            array,
        ))
    }

    fn used_encodings(&self) -> HashSet<EncodingRef> {
        HashSet::from([&VarBinEncoding as EncodingRef])
    }
}