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