From 89c53131c152eb17a1632e58c12f00a24000162d Mon Sep 17 00:00:00 2001 From: Alex Auvolat Date: Fri, 6 Oct 2023 19:05:58 +0200 Subject: serialize charsets as strings --- src/charset.rs | 25 ++++++++++++++++++++++++- src/main.rs | 8 ++++---- 2 files changed, 28 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/charset.rs b/src/charset.rs index a79eddb..71e1e84 100644 --- a/src/charset.rs +++ b/src/charset.rs @@ -2,7 +2,8 @@ use std::cmp::Ordering; use serde::{Deserialize, Serialize}; -#[derive(Debug, Eq, PartialEq, Hash, Clone, Serialize, Deserialize, Default)] +#[derive(Debug, Eq, PartialEq, Hash, Clone, Default, Serialize, Deserialize)] +#[serde(into = "String", from = "CharsetSerializedEnum")] pub struct Charset(pub Vec); impl Charset { @@ -153,6 +154,28 @@ impl Charset { } } +impl Into for Charset { + fn into(self) -> String { + self.to_string() + } +} + +#[derive(Deserialize)] +#[serde(untagged)] +enum CharsetSerializedEnum { + Array(Vec), + Str(String), +} + +impl From for Charset { + fn from(s: CharsetSerializedEnum) -> Charset { + match s { + CharsetSerializedEnum::Array(a) => Charset::from_iter(a.into_iter()), + CharsetSerializedEnum::Str(s) => Charset::new(&s), + } + } +} + #[cfg(test)] mod test { use super::*; diff --git a/src/main.rs b/src/main.rs index 9e08418..4addd02 100644 --- a/src/main.rs +++ b/src/main.rs @@ -88,7 +88,7 @@ fn main() { let mut batches: Vec = fs::read("data/batches.json") .map_err(anyhow::Error::from) .and_then(|x| Ok(serde_json::from_slice(&x)?)) - .unwrap_or_default(); + .expect("failed to decode batches.json"); for batch in batches.iter_mut() { simplify_batch(batch); } @@ -104,7 +104,7 @@ fn main() { let mut batches: Vec = fs::read("data/batches.json") .map_err(anyhow::Error::from) .and_then(|x| Ok(serde_json::from_slice(&x)?)) - .unwrap_or_default(); + .expect("failed to decode batches.json"); let kanji_levels = read_kanji_levels().expect("read_kanji_levels"); let kanji_levels = kanji_levels .into_iter() @@ -123,7 +123,7 @@ fn main() { let mut batches: Vec = fs::read("data/batches.json") .map_err(anyhow::Error::from) .and_then(|x| Ok(serde_json::from_slice(&x)?)) - .unwrap_or_default(); + .expect("failed to decode batches.json"); let jlpt_vocab = load_jlpt_vocab().expect("load_jlpt_vocab"); add_vocab(&mut batches, &jlpt_vocab); fs::write( @@ -150,7 +150,7 @@ fn main() { let mut batches: Vec = fs::read("data/batches.json") .map_err(anyhow::Error::from) .and_then(|x| Ok(serde_json::from_slice(&x)?)) - .unwrap_or_default(); + .expect("failed to decode batches.json"); add_examples(&mut batches, &ex); -- cgit v1.2.3