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::{ConstantArray, ConstantEncoding};
use vortex_array::encoding::{Encoding, EncodingRef};
use vortex_array::stats::ArrayStatistics;
use vortex_array::{ArrayData, IntoArrayData};
use vortex_error::{VortexExpect, VortexResult};

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

#[derive(Debug)]
pub struct ConstantCompressor;

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

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

    fn can_compress(&self, array: &ArrayData) -> Option<&dyn EncodingCompressor> {
        array
            .statistics()
            .compute_is_constant()?
            .then_some(self as &dyn EncodingCompressor)
    }

    fn compress<'a>(
        &'a self,
        array: &ArrayData,
        _like: Option<CompressionTree<'a>>,
        _ctx: SamplingCompressor<'a>,
    ) -> VortexResult<CompressedArray<'a>> {
        Ok(CompressedArray::compressed(
            ConstantArray::new(
                array
                    .as_constant()
                    .vortex_expect("ConstantCompressor expects constant array"),
                array.len(),
            )
            .into_array(),
            Some(CompressionTree::flat(self)),
            array,
        ))
    }

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