From 16bb6a48a2cba2ee5e021b3ef228eaab393b282b Mon Sep 17 00:00:00 2001 From: 0xf8 <0xf8.dev@proton.me> Date: Wed, 19 Apr 2023 20:53:16 -0400 Subject: [PATCH] More efficient method for KeywordSection::load() --- src/config.rs | 2 +- src/keywords.rs | 26 ++++++-------------------- 2 files changed, 7 insertions(+), 21 deletions(-) diff --git a/src/config.rs b/src/config.rs index a3886e1..43944fc 100644 --- a/src/config.rs +++ b/src/config.rs @@ -122,7 +122,7 @@ impl Config { .as_object() .unwrap() .into_iter() - .map(|a| (a.0.to_owned(), KeywordSection::load(a.1))) + .map(|a| (a.0.to_owned(), KeywordSection::load(a.1).unwrap())) .collect(); Self { diff --git a/src/keywords.rs b/src/keywords.rs index 3df3bfd..3539fda 100644 --- a/src/keywords.rs +++ b/src/keywords.rs @@ -1,7 +1,8 @@ use serde_json::Value; +use serde::{Deserialize, Serialize}; -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Deserialize, Serialize)] pub struct KeywordSection { pub threshold: u64, pub required: Vec, @@ -9,25 +10,10 @@ pub struct KeywordSection { } impl KeywordSection { - pub fn load(json: &Value) -> Self { - let threshold: u64 = json["threshold"].as_u64().unwrap(); - let required: Vec = json["requiredKeywords"] - .as_array() - .unwrap() - .into_iter() - .map(|a| a.as_str().unwrap().to_string()) - .collect(); - let keywords: Vec = json["keywords"] - .as_array() - .unwrap() - .into_iter() - .map(|a| a.as_str().unwrap().to_string()) - .collect(); - - Self { - threshold, - required, - keywords, + pub fn load(json: &Value) -> Option { + match serde_json::from_value(json.to_owned()) { + Ok(j) => Some(j), + Err(e) => { eprintln!("{e}"); None } } }