vortex_sampling_compressor/compressors/
dict.rs

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
use std::collections::HashSet;

use vortex::array::{Primitive, PrimitiveArray, VarBin, VarBinArray};
use vortex::encoding::EncodingRef;
use vortex::stats::ArrayStatistics;
use vortex::{Array, ArrayDef, IntoArray};
use vortex_dict::{dict_encode_primitive, dict_encode_varbin, Dict, DictArray, DictEncoding};
use vortex_error::VortexResult;

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

#[derive(Debug)]
pub struct DictCompressor;

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

    fn can_compress(&self, array: &Array) -> Option<&dyn EncodingCompressor> {
        // TODO(robert): Add support for VarBinView
        if array.encoding().id() != Primitive::ID && array.encoding().id() != VarBin::ID {
            return None;
        };

        // No point dictionary coding if the array is unique.
        // We don't have a unique stat yet, but strict-sorted implies unique.
        if array
            .statistics()
            .compute_is_strict_sorted()
            .unwrap_or(false)
        {
            return None;
        }

        Some(self)
    }

    fn compress<'a>(
        &'a self,
        array: &Array,
        like: Option<CompressionTree<'a>>,
        ctx: SamplingCompressor<'a>,
    ) -> VortexResult<CompressedArray<'a>> {
        let (codes, values) = match array.encoding().id() {
            Primitive::ID => {
                let p = PrimitiveArray::try_from(array)?;
                let (codes, values) = dict_encode_primitive(&p);
                (codes.into_array(), values.into_array())
            }
            VarBin::ID => {
                let vb = VarBinArray::try_from(array)?;
                let (codes, values) = dict_encode_varbin(&vb);
                (codes.into_array(), values.into_array())
            }

            _ => unreachable!("This array kind should have been filtered out"),
        };

        let (codes, values) = (
            ctx.auxiliary("codes")
                .excluding(self)
                .compress(&codes, like.as_ref().and_then(|l| l.child(0)))?,
            ctx.named("values")
                .excluding(self)
                .compress(&values, like.as_ref().and_then(|l| l.child(1)))?,
        );

        Ok(CompressedArray::new(
            DictArray::try_new(codes.array, values.array)?.into_array(),
            Some(CompressionTree::new(self, vec![codes.path, values.path])),
        ))
    }

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