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

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

#[derive(Debug)]
pub struct SparseCompressor;

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

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

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

    fn compress<'a>(
        &'a self,
        array: &ArrayData,
        _: Option<CompressionTree<'a>>,
        ctx: SamplingCompressor<'a>,
    ) -> VortexResult<CompressedArray<'a>> {
        let sparse_array = SparseArray::try_from(array.clone())?;
        let compressed_patches = ctx
            .auxiliary("patches")
            .compress_patches(sparse_array.patches())?;
        Ok(CompressedArray::compressed(
            SparseArray::try_new_from_patches(
                compressed_patches,
                sparse_array.len(),
                sparse_array.indices_offset(),
                sparse_array.fill_scalar(),
            )?
            .into_array(),
            Some(CompressionTree::new(self, vec![])),
            array,
        ))
    }

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