foyer_storage/compress.rs
1// Copyright 2026 foyer Project Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// TODO(MrCroxx): unify compress interface?
16
17use foyer_common::error::{Error, ErrorKind};
18
19/// The compression algorithm of the disk cache.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
23pub enum Compression {
24 /// No compression enabled.
25 #[default]
26 None,
27 /// Use zstd compression.
28 Zstd,
29 /// Use lz4 compression.
30 Lz4,
31}
32
33impl Compression {
34 /// Get the u8 that represent the compression algorithm.
35 pub fn to_u8(&self) -> u8 {
36 match self {
37 Self::None => 0,
38 Self::Zstd => 1,
39 Self::Lz4 => 2,
40 }
41 }
42}
43
44impl From<Compression> for u8 {
45 fn from(value: Compression) -> Self {
46 match value {
47 Compression::None => 0,
48 Compression::Zstd => 1,
49 Compression::Lz4 => 2,
50 }
51 }
52}
53
54impl TryFrom<u8> for Compression {
55 type Error = Error;
56
57 fn try_from(value: u8) -> Result<Self, Self::Error> {
58 match value {
59 0 => Ok(Self::None),
60 1 => Ok(Self::Zstd),
61 2 => Ok(Self::Lz4),
62 _ => Err(Error::new(ErrorKind::Parse, "failed to parse Compression").with_context("value", value)),
63 }
64 }
65}