From 41b18c97b0468c4660894705e837941310e22fa0 Mon Sep 17 00:00:00 2001 From: xenua Date: Wed, 4 Jan 2023 11:02:37 +0100 Subject: [PATCH] refactor out meta_str_to_map --- src/main.rs | 37 +++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/src/main.rs b/src/main.rs index 83fc4d0..560c139 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,6 +46,21 @@ pub enum Error { FS, } +fn meta_str_to_map(from: &str) -> Result, Error> { + let map = from + .lines() + .map(|line| line.trim()) + .filter(|line| line.len() > 0) + .map(|line| { + line.split_once(": ") + .ok_or(Error::Metadata) + .and_then(|(k, v)| Ok((k, v.to_string()))) + }) + .collect::, Error>>()?; + + Ok(map) +} + struct TextPaste { pub text: String, pub meta: TextMeta, @@ -57,16 +72,7 @@ struct TextMeta { impl TextMeta { pub fn parse(from: &str) -> Result { - let mut map = HashMap::new(); - - from.lines() - .map(|line| line.trim()) - .filter(|line| line.len() > 0) - .map(|line| { - line.split_once(": ") - .ok_or(Error::Metadata) - .map(|(k, v)| map.insert(k.to_string(), v.to_string())) - }); + let map = meta_str_to_map(from)?; // meh, this prolly doesnt perform well but idc its only init code Ok(Self { language: map.remove("language"), @@ -80,14 +86,9 @@ struct FileMeta { impl FileMeta { pub fn parse(from: &str) -> Result { - let map = from - .lines() - .map(|line| line.trim()) - .filter(|line| line.len() > 0) - .map(|line| line.split_once(": ").ok_or(Error::Metadata)) - .collect::, Error>>()?; - - let file_name = map.remove("file_name").ok_or(Error::Metadata)?.to_string(); + let map = meta_str_to_map(from)?; + + let file_name = map.remove("file_name").ok_or(Error::Metadata)?; Ok(Self { file_name }) } }