1use std::collections::HashMap;
2use std::error::Error;
3
4use crate::error::ParseError;
5use crate::values::Values;
6pub trait SerializeHelper<T> {
8 fn get_val_unsafe(&self, attr: &str, fun: fn(&Values) -> Option<T>) -> T;
13 fn get_val_opt(&self, attr: &str, fun: fn(&Values) -> Option<T>) -> Option<T>;
17 fn get_val_res(&self, attr: &str, fun: fn(&Values) -> Option<T>) -> Result<T, ParseError>;
22 fn rm_val(&mut self, attr: &str, fun: fn(Values) -> Option<T>) -> Result<T, ParseError>;
27 fn map_val(
32 &mut self,
33 attr: &str,
34 fun: fn(Values) -> Result<T, ParseError>,
35 ) -> Result<T, ParseError>;
36 fn map_ref_val(
41 &mut self,
42 attr: &str,
43 fun: fn(&Values) -> Result<T, ParseError>,
44 ) -> Result<T, ParseError>;
45 fn map_val_and_err<E: Error>(
50 &mut self,
51 attr: &str,
52 fun: fn(Values) -> Result<T, E>,
53 ) -> Result<T, ParseError>;
54 fn map_opt_val(
60 &mut self,
61 attr: &str,
62 fun: fn(Values) -> Option<T>,
63 ) -> Result<Option<T>, ParseError>;
64}
65
66impl<T> SerializeHelper<T> for HashMap<String, Values> {
67 fn get_val_unsafe(&self, attr: &str, fun: fn(&Values) -> Option<T>) -> T {
68 SerializeHelper::get_val_res(self, attr, fun).unwrap()
69 }
70 fn get_val_opt(&self, attr: &str, fun: fn(&Values) -> Option<T>) -> Option<T> {
71 SerializeHelper::get_val_res(self, attr, fun).ok()
72 }
73 fn get_val_res(&self, attr: &str, fun: fn(&Values) -> Option<T>) -> Result<T, ParseError> {
74 self.get(&String::from(attr))
75 .map(fun)
76 .ok_or(ParseError::new())?
77 .ok_or(ParseError::new())
78 }
79 fn rm_val(&mut self, attr: &str, fun: fn(Values) -> Option<T>) -> Result<T, ParseError> {
80 self.remove(&String::from(attr))
81 .map(fun)
82 .ok_or(ParseError::new())?
83 .ok_or(ParseError::new())
84 }
85 fn map_val(
86 &mut self,
87 attr: &str,
88 fun: fn(Values) -> Result<T, ParseError>,
89 ) -> Result<T, ParseError> {
90 self.remove(&String::from(attr))
91 .map(fun)
92 .ok_or(ParseError::new())?
93 }
94 fn map_ref_val(
95 &mut self,
96 attr: &str,
97 fun: fn(&Values) -> Result<T, ParseError>,
98 ) -> Result<T, ParseError> {
99 self.get(&String::from(attr))
100 .map(fun)
101 .ok_or(ParseError::new())?
102 }
103 fn map_val_and_err<E: Error>(
104 &mut self,
105 attr: &str,
106 fun: fn(Values) -> Result<T, E>,
107 ) -> Result<T, ParseError> {
108 self.remove(&String::from(attr))
109 .map(fun)
110 .ok_or(ParseError::new())?
111 .map_err(|_err| ParseError::new())
112 }
113 fn map_opt_val(
114 &mut self,
115 attr: &str,
116 fun: fn(Values) -> Option<T>,
117 ) -> Result<Option<T>, ParseError> {
118 self.remove(attr).map(fun).ok_or(ParseError::new())
119 }
120}