omg_serde/interface/
map.rs

1use crate::generation::MapGenerationSerde;
2use anyhow::{Context, Result};
3use omg_core::generation::MapGenerator;
4use omg_core::interface::map::MapStorage;
5use std::fs;
6use std::fs::File;
7use std::io::Write;
8
9pub struct MapStorageWithSerde;
10
11impl MapStorageWithSerde {
12    pub fn inner_read(&self, path: &str) -> Result<MapGenerator> {
13        let string = fs::read_to_string(path)?;
14        let data: MapGenerationSerde = serde_yaml::from_str(&string)?;
15        data.try_convert()
16    }
17
18    pub fn inner_write(&self, map_generator: &MapGenerator, path: &str) -> Result<()> {
19        let mut file = File::create(path)?;
20
21        let data: MapGenerationSerde = map_generator.into();
22        let s = serde_yaml::to_string(&data)?;
23
24        file.write_all(s.as_bytes())?;
25
26        Ok(())
27    }
28}
29
30impl MapStorage for MapStorageWithSerde {
31    fn read(&self, path: &str) -> Result<MapGenerator> {
32        self.inner_read(path)
33            .with_context(|| format!("Failed to read MapGeneration from '{}'", path))
34    }
35
36    fn write(&self, map_generator: &MapGenerator, path: &str) -> Result<()> {
37        self.inner_write(map_generator, path).with_context(|| {
38            format!(
39                "Failed to write MapGeneration '{}' to '{}'",
40                map_generator.name(),
41                path
42            )
43        })
44    }
45}