Skip to main content

jpreprocess_dictionary/dictionary/
word_encoding.rs

1use jpreprocess_core::word_line::WordDetailsLine;
2use lindera_dictionary::{error::LinderaErrorKind, LinderaResult};
3
4/// A trait for encoding and decoding as dictionary entry.
5pub trait DictionaryWordEncoding: Sized {
6    fn identifier() -> &'static str;
7    fn encode(row: WordDetailsLine) -> LinderaResult<Vec<u8>>;
8}
9
10pub struct JPreprocessDictionaryWordEncoding;
11impl JPreprocessDictionaryWordEncoding {
12    pub fn serialize(
13        data: &jpreprocess_core::word_entry::WordEntry,
14    ) -> Result<Vec<u8>, bincode::error::EncodeError> {
15        bincode::serde::encode_to_vec(data, Self::bincode_option())
16    }
17    pub fn deserialize(
18        data: &[u8],
19    ) -> Result<jpreprocess_core::word_entry::WordEntry, bincode::error::DecodeError> {
20        let (decoded, _size) = bincode::serde::decode_from_slice(data, Self::bincode_option())?;
21        Ok(decoded)
22    }
23
24    fn bincode_option() -> bincode::config::Configuration {
25        bincode::config::standard()
26            .with_no_limit()
27            .with_little_endian()
28    }
29}
30impl DictionaryWordEncoding for JPreprocessDictionaryWordEncoding {
31    fn identifier() -> &'static str {
32        concat!("jpreprocess ", env!("CARGO_PKG_VERSION"))
33    }
34
35    fn encode(row: WordDetailsLine) -> LinderaResult<Vec<u8>> {
36        let data = row
37            .try_into()
38            .map_err(|err| LinderaErrorKind::Serialize.with_error(err))?;
39        Self::serialize(&data).map_err(|err| LinderaErrorKind::Serialize.with_error(err))
40    }
41}