lsm_tree/config/
compression.rs

1// Copyright (c) 2024-present, fjall-rs
2// This source code is licensed under both the Apache 2.0 and MIT License
3// (found in the LICENSE-* files in the repository)
4
5use crate::CompressionType;
6
7/// Compression policy
8#[derive(Debug, Clone, Eq, PartialEq)]
9pub struct CompressionPolicy(Vec<CompressionType>);
10
11impl std::ops::Deref for CompressionPolicy {
12    type Target = [CompressionType];
13
14    fn deref(&self) -> &Self::Target {
15        &self.0
16    }
17}
18
19// TODO: remove default
20impl Default for CompressionPolicy {
21    fn default() -> Self {
22        #[cfg(feature = "lz4")]
23        let c = Self::new(&[CompressionType::None, CompressionType::Lz4]);
24
25        #[cfg(not(feature = "lz4"))]
26        let c = Self::new(&[CompressionType::None]);
27
28        c
29    }
30}
31
32impl CompressionPolicy {
33    pub(crate) fn get(&self, level: usize) -> CompressionType {
34        self.0
35            .get(level)
36            .copied()
37            .unwrap_or_else(|| self.last().copied().expect("policy should not be empty"))
38    }
39
40    /// Disables all compression.
41    #[must_use]
42    pub fn disabled() -> Self {
43        Self::all(CompressionType::None)
44    }
45
46    // TODO: accept Vec... Into<Vec<...>>? or owned
47
48    /// Uses the same compression in every level.
49    #[must_use]
50    pub fn all(c: CompressionType) -> Self {
51        Self(vec![c])
52    }
53
54    /// Constructs a custom compression policy.
55    ///
56    /// # Example
57    ///
58    /// Skip compression in level 0:
59    ///
60    /// ```
61    /// # use lsm_tree::{CompressionType, config::CompressionPolicy};
62    /// let policy = CompressionPolicy::new(&[
63    ///   CompressionType::None,
64    ///   CompressionType::Lz4, // use LZ4 for L1+
65    /// ]);
66    /// ```
67    #[must_use]
68    pub fn new(policy: &[CompressionType]) -> Self {
69        assert!(!policy.is_empty(), "compression policy may not be empty");
70        assert!(policy.len() <= 255, "compression policy is too large");
71        Self(policy.into())
72    }
73}