use crate::error::StixError as Error;
use serde::{de::DeserializeOwned, Serialize};
use serde_value::Value;
pub fn get_field_by_name<T, R>(data: T, field: &str) -> Result<Option<R>, Error>
where
T: Serialize,
R: DeserializeOwned,
{
let mut map = match serde_value::to_value(data) {
Ok(Value::Map(map)) => map,
_ => {
return Err(Error::SerializationError(
"Could not serialize struct for field checking".to_string(),
))
}
};
let key = Value::String(field.to_owned());
let value = match map.remove(&key) {
Some(value) => value,
None => return Ok(None),
};
match R::deserialize(value) {
Ok(r) => Ok(Some(r)),
Err(e) => Err(Error::DeserializationError(format!(
"Could not deserialize value of field checked to correct type: {}",
e
))),
}
}