lindera_dictionary/
decompress.rs

1use std::{io::Read, str::FromStr};
2
3use flate2::read::{DeflateDecoder, GzDecoder, ZlibDecoder};
4use rkyv::{Archive, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize};
5use serde::{Deserialize, Serialize};
6use strum::IntoEnumIterator;
7use strum_macros::EnumIter;
8
9use crate::error::{LinderaError, LinderaErrorKind};
10
11#[derive(
12    Debug,
13    Clone,
14    EnumIter,
15    Copy,
16    PartialEq,
17    Eq,
18    Serialize,
19    Deserialize,
20    Archive,
21    RkyvSerialize,
22    RkyvDeserialize,
23)]
24#[repr(u32)] // explicit representation for consistency
25#[serde(rename_all = "lowercase")]
26
27pub enum Algorithm {
28    Deflate = 0,
29    Zlib = 1,
30    Gzip = 2,
31    Raw = 3,
32}
33
34impl Algorithm {
35    pub fn variants() -> Vec<Algorithm> {
36        Algorithm::iter().collect::<Vec<_>>()
37    }
38
39    pub fn as_str(&self) -> &str {
40        match self {
41            Algorithm::Deflate => "deflate",
42            Algorithm::Zlib => "zlib",
43            Algorithm::Gzip => "gzip",
44            Algorithm::Raw => "raw",
45        }
46    }
47}
48
49impl FromStr for Algorithm {
50    type Err = LinderaError;
51    fn from_str(input: &str) -> Result<Algorithm, Self::Err> {
52        match input {
53            "deflate" => Ok(Algorithm::Deflate),
54            "zlib" => Ok(Algorithm::Zlib),
55            "gzip" => Ok(Algorithm::Gzip),
56            "raw" => Ok(Algorithm::Raw),
57            _ => Err(LinderaErrorKind::Algorithm
58                .with_error(anyhow::anyhow!("Invalid algorithm: {input}"))),
59        }
60    }
61}
62
63#[derive(Debug, Clone, Serialize, Deserialize, Archive, RkyvSerialize, RkyvDeserialize)]
64
65pub struct CompressedData {
66    pub algorithm: Algorithm,
67    pub data: Vec<u8>,
68}
69
70impl CompressedData {
71    pub fn new(algorithm: Algorithm, data: Vec<u8>) -> Self {
72        CompressedData { algorithm, data }
73    }
74}
75
76pub fn decompress(data: CompressedData) -> anyhow::Result<Vec<u8>> {
77    match data.algorithm {
78        Algorithm::Deflate => {
79            let mut decoder = DeflateDecoder::new(data.data.as_slice());
80            let mut output_data = Vec::new();
81            decoder.read_to_end(&mut output_data)?;
82            Ok(output_data)
83        }
84        Algorithm::Zlib => {
85            let mut decoder = ZlibDecoder::new(data.data.as_slice());
86            let mut output_data = Vec::new();
87            decoder.read_to_end(&mut output_data)?;
88            Ok(output_data)
89        }
90        Algorithm::Gzip => {
91            let mut decoder = GzDecoder::new(data.data.as_slice());
92            let mut output_data = Vec::new();
93            decoder.read_to_end(&mut output_data)?;
94            Ok(output_data)
95        }
96        Algorithm::Raw => Ok(data.data),
97    }
98}