1use crate::Result;
2use serde::Serialize;
3use stac::{FromJson, SelfHref, ToJson};
4use std::{fs::File, io::Read, path::Path};
5
6pub trait FromJsonPath: FromJson + SelfHref {
8 fn from_json_path(path: impl AsRef<Path>) -> Result<Self> {
19 let path = path.as_ref();
20 let mut buf = Vec::new();
21 let _ = File::open(path)?.read_to_end(&mut buf)?;
22 let mut value = Self::from_json_slice(&buf)?;
23 value.set_self_href(path.to_string_lossy());
24 Ok(value)
25 }
26}
27
28pub trait ToJsonPath: ToJson {
29 fn to_json_path(&self, path: impl AsRef<Path>, pretty: bool) -> Result<()> {
40 let file = File::create(path)?;
41 self.to_json_writer(file, pretty)?;
42 Ok(())
43 }
44}
45
46impl<T: FromJson + SelfHref> FromJsonPath for T {}
47impl<T: Serialize> ToJsonPath for T {}
48
49#[cfg(test)]
50mod tests {
51 use super::FromJsonPath;
52 use stac::{Item, SelfHref};
53
54 #[test]
55 fn set_href() {
56 let item = Item::from_json_path("examples/simple-item.json").unwrap();
57 assert!(
58 item.self_href()
59 .unwrap()
60 .ends_with("examples/simple-item.json")
61 );
62 }
63}