use serde::Serialize;
use super::format::FormatError;
use super::{SavedDocument, SavedObject};
pub const NATIVE_FORMAT: &str = "ferrocad";
pub const NATIVE_VERSION: u32 = 1;
pub fn default_format() -> String {
NATIVE_FORMAT.to_owned()
}
pub fn default_version() -> u32 {
NATIVE_VERSION
}
pub fn encode(doc: &SavedDocument) -> Result<Vec<u8>, FormatError> {
#[derive(Serialize)]
struct Envelope<'a> {
format: &'static str,
version: u32,
name: &'a str,
objects: &'a [SavedObject],
}
serde_json::to_vec(&Envelope {
format: NATIVE_FORMAT,
version: NATIVE_VERSION,
name: &doc.name,
objects: &doc.objects,
})
.map_err(FormatError::Encode)
}
pub fn write(doc: &SavedDocument, path: &str) -> Result<(), FormatError> {
let bytes = encode(doc)?;
std::fs::write(path, bytes).map_err(|e| FormatError::io(path, e))
}
pub fn read(path: &str) -> Result<SavedDocument, FormatError> {
let data = std::fs::read(path).map_err(|e| FormatError::io(path, e))?;
decode(path, &data)
}
pub fn decode(path: &str, data: &[u8]) -> Result<SavedDocument, FormatError> {
let doc: SavedDocument =
serde_json::from_slice(data).map_err(|e| FormatError::json(path, e))?;
check_envelope(path, &doc)?;
Ok(doc)
}
pub fn check_envelope(path: &str, doc: &SavedDocument) -> Result<(), FormatError> {
if doc.format != NATIVE_FORMAT {
return Err(FormatError::NotNative {
path: path.to_owned(),
format: doc.format.clone(),
});
}
if doc.version > NATIVE_VERSION {
return Err(FormatError::NewerVersion {
path: path.to_owned(),
version: doc.version,
});
}
Ok(())
}