static_lang_word_lists/
metadata.rs1use std::{borrow::Cow, fs, path::Path};
2
3use serde::Deserialize;
4
5use crate::WordListError;
6
7#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize)]
15#[serde(deny_unknown_fields)]
16pub struct WordListMetadata {
17 pub name: Cow<'static, str>,
19 pub script: Option<Cow<'static, str>>,
24 pub language: Option<Cow<'static, str>>,
29}
30
31impl WordListMetadata {
32 #[must_use]
34 pub(crate) const fn new(
35 name: &'static str,
36 script: Option<&'static str>,
37 language: Option<&'static str>,
38 ) -> Self {
39 let script = match script {
41 Some(script) => Some(Cow::Borrowed(script)),
42 None => None,
43 };
44 let language = match language {
45 Some(language) => Some(Cow::Borrowed(language)),
46 None => None,
47 };
48 WordListMetadata {
49 name: Cow::Borrowed(name),
50 script,
51 language,
52 }
53 }
54
55 #[allow(clippy::result_large_err)]
57 pub fn load(
58 metadata_path: impl AsRef<Path>,
59 ) -> Result<Self, WordListError> {
60 let path = metadata_path.as_ref();
61 let metadata_content = fs::read_to_string(path).map_err(|io_err| {
62 WordListError::FailedToRead(path.to_owned(), io_err)
63 })?;
64 let metadata: WordListMetadata = toml::from_str(&metadata_content)
65 .map_err(|json_err| {
66 WordListError::MetadataError(path.to_owned(), json_err)
67 })?;
68 Ok(metadata)
69 }
70
71 pub(crate) fn new_from_name(name: impl Into<String>) -> Self {
72 WordListMetadata {
73 name: Cow::Owned(name.into()),
74 script: None,
75 language: None,
76 }
77 }
78
79 #[inline]
81 #[must_use]
82 pub fn name(&self) -> &str {
83 self.name.as_ref()
84 }
85
86 #[inline]
92 #[must_use]
93 pub fn script(&self) -> Option<&str> {
94 self.script.as_deref()
95 }
96
97 #[inline]
102 #[must_use]
103 pub fn language(&self) -> Option<&str> {
104 self.language.as_deref()
105 }
106}
107
108impl<S> From<S> for WordListMetadata
109where
110 S: Into<Cow<'static, str>>,
111{
112 fn from(word_list_name: S) -> Self {
113 WordListMetadata {
114 name: word_list_name.into(),
115 script: None,
116 language: None,
117 }
118 }
119}