evoxel_io/
write.rs

1use crate::document::EvoxelInfoDocument;
2use crate::error::Error;
3use crate::write_impl::{write_to_parquet, write_to_xyz};
4use crate::{
5    FILE_NAME_ECOORD, FILE_NAME_INFO, FILE_NAME_VOXEL_DATA_COMPRESSED,
6    FILE_NAME_VOXEL_DATA_UNCOMPRESSED,
7};
8use evoxel_core::VoxelGrid;
9use std::fs;
10use std::fs::OpenOptions;
11use std::path::{Path, PathBuf};
12
13/// `EvoxelReader` sets up a reader for the custom reader data structure.
14///
15#[derive(Debug, Clone)]
16pub struct EvoxelWriter {
17    path: PathBuf,
18    compressed: bool,
19}
20
21impl EvoxelWriter {
22    pub fn new(path: impl AsRef<Path>) -> Self {
23        Self {
24            path: path.as_ref().to_owned(),
25            compressed: true,
26        }
27    }
28
29    pub fn with_compressed(mut self, compressed: bool) -> Self {
30        self.compressed = compressed;
31        self
32    }
33
34    pub fn finish(&self, voxel_grid: &VoxelGrid) -> Result<(), Error> {
35        fs::create_dir_all(self.path.clone())?;
36
37        if self.compressed {
38            let parquet_file_path = self.path.join(FILE_NAME_VOXEL_DATA_COMPRESSED);
39            write_to_parquet(voxel_grid, parquet_file_path)?;
40        } else {
41            let xyz_file_path = self.path.join(FILE_NAME_VOXEL_DATA_UNCOMPRESSED);
42            write_to_xyz(voxel_grid, xyz_file_path)?;
43        }
44
45        let info_document_path = self.path.join(FILE_NAME_INFO);
46        let info_document = EvoxelInfoDocument::new(
47            voxel_grid.info().frame_id().clone().into(),
48            voxel_grid.info().resolution(),
49        );
50        let file = OpenOptions::new()
51            .create(true)
52            .write(true)
53            .truncate(true)
54            .open(info_document_path)?;
55        serde_json::to_writer_pretty(file, &info_document)?;
56
57        let ecoord_document_path = self.path.join(FILE_NAME_ECOORD);
58        ecoord::io::EcoordWriter::from_path(ecoord_document_path)?
59            .finish(voxel_grid.reference_frames())?;
60
61        Ok(())
62    }
63}