//! Compiled dictionaries bundled with the binary. //! //! The data files under `data/` are generated by `cargo xtask update-dict` use std::path::Path; use anyhow::{Context, Result}; use facet::Facet; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Lang { /// Japanese words, readings in kana. Ja, /// Chinese words, readings in pinyin. Zh, } impl Lang { pub fn name(self) -> &'static str { match self { Lang::Ja => "ja", Lang::Zh => "zh", } } } /// A compiled dictionary. #[derive(Clone, Debug, Default, Facet)] pub struct Dictionary { /// Source datasets and the version each was compiled from. pub sources: Vec<(String, String)>, pub entries: Vec, /// Curated default readings in inline notation. pub defaults: Vec, /// Forms never to annotate. pub bare: Vec, } /// One written form and its readings. #[derive(Clone, Debug, Default, Facet)] pub struct DictionaryEntry { pub form: String, pub readings: Vec, /// A place name: it only fills runs no common word claims. pub place: bool, } /// One reading of a form, with the metadata that ranks and selects it. #[derive(Clone, Debug, Default, Facet)] pub struct DictionaryReading { /// Alignment: `0:に;1:ほん`, or `0-1:きょう` for a reading spanning characters. pub words: String, /// Newspaper frequency bucket (0 when unranked). pub nf: u16, /// JLPT level listing this reading (0 when none). pub jlpt: u8, /// Priority tags, as a bitmask over [`crate::words::TAG_NAMES`]. pub tags: u16, /// Position of the reading among the form's readings, in JMdict order. pub order: u16, /// Uses in Tatoeba's example sentences. pub tatoeba: u16, /// Selected by the dictionary itself, whatever its ranking (CC-CEDICT /// entries carry no frequency metadata). pub common: bool, /// `来る`-type verb, whose kanji reads differently as it conjugates. pub conjugates: bool, /// Made the default by the curated list (1) or the user (2). pub pinned: u8, } const ZLIB_LEVEL: u32 = 9; pub fn encode(dictionary: &Dictionary) -> Result> { use std::io::Write; let raw = facet_postcard::to_vec(dictionary) .map_err(|error| anyhow::anyhow!("Failed to serialize dictionary: {error:?}"))?; let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(ZLIB_LEVEL)); encoder .write_all(&raw) .context("Failed to compress dictionary")?; encoder.finish().context("Failed to compress dictionary") } pub fn decode(bytes: &[u8]) -> Result { use std::io::Read; let mut decoder = flate2::read::ZlibDecoder::new(bytes); let mut raw = Vec::new(); decoder .read_to_end(&mut raw) .context("Failed to decompress dictionary")?; facet_postcard::from_slice(&raw) .map_err(|error| anyhow::anyhow!("Failed to decode dictionary: {error:?}")) } pub fn load_path(path: &Path) -> Result { let bytes = std::fs::read(path).with_context(|| format!("Failed to read dictionary {path:?}"))?; decode(&bytes) } #[cfg(feature = "dict-ja")] const DICT_JA: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/data/dict-ja.bin")); #[cfg(not(feature = "dict-ja"))] const DICT_JA: &[u8] = &[]; #[cfg(feature = "dict-zh")] const DICT_ZH: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/data/dict-zh.bin")); #[cfg(not(feature = "dict-zh"))] const DICT_ZH: &[u8] = &[]; /// Load the dictionary bundled for a language, if one is compiled in. pub fn load_bundled(lang: Lang) -> Option { let bytes = match lang { Lang::Ja => DICT_JA, Lang::Zh => DICT_ZH, }; if bytes.is_empty() { return None; } match decode(bytes) { Ok(dictionary) => Some(dictionary), Err(error) => { tracing::warn!( "Failed to decode bundled {} dictionary: {error:#}", lang.name() ); None } } }