//! Versioned RON files. //! //! Every saved file is an [`Envelope`] with a `format_version` field, so a newer //! build can reject data it does not understand and an older one can migrate it //! forward through the chain in [`crate::migrate`]. use core::fmt; use std::collections::BTreeMap; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use crate::migrate::{self, MigrateError, Migration}; /// The format version written by this build. pub const CURRENT_VERSION: u32 = 1; /// A payload with the version of the schema it follows. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Envelope { /// Schema version of `payload`. pub format_version: u32, /// The document itself. pub payload: T, } /// Serialises `payload` as a pretty RON envelope at [`CURRENT_VERSION`]. pub fn to_ron(payload: &T) -> Result { let envelope = Envelope { format_version: CURRENT_VERSION, payload, }; ron::ser::to_string_pretty(&envelope, ron::ser::PrettyConfig::default()) .map_err(|error| FormatError::Encode(error.to_string())) } /// Reads an envelope written at [`CURRENT_VERSION`]. /// /// Older documents are rejected because no migration steps are known here; use /// [`from_ron_with_migrations`] to supply them. pub fn from_ron(text: &str) -> Result { from_ron_with_migrations(text, &BTreeMap::new()) } /// Reads an envelope, migrates an older payload forward, then decodes it. /// /// A version newer than [`CURRENT_VERSION`] is always rejected: a newer file may /// contain fields this build would silently drop. pub fn from_ron_with_migrations( text: &str, steps: &BTreeMap, ) -> Result { let envelope: Envelope = ron::from_str(text).map_err(|error| FormatError::Parse(error.to_string()))?; if envelope.format_version > CURRENT_VERSION { return Err(FormatError::TooNew { found: envelope.format_version, current: CURRENT_VERSION, }); } let payload = migrate::migrate_value( envelope.payload, envelope.format_version, CURRENT_VERSION, steps, )?; payload .into_rust() .map_err(|error| FormatError::Decode(error.to_string())) } /// Why a file could not be read or written. #[derive(Debug)] pub enum FormatError { /// The text is not a RON envelope. Parse(String), /// The payload could not be serialised. Encode(String), /// The payload does not match the requested type after migration. Decode(String), /// The file was written by a newer build. TooNew { /// Version found in the file. found: u32, /// Version this build understands. current: u32, }, /// A migration step failed. Migration(MigrateError), } impl From for FormatError { fn from(error: MigrateError) -> Self { Self::Migration(error) } } impl fmt::Display for FormatError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Parse(reason) => write!(formatter, "cannot parse the RON envelope: {reason}"), Self::Encode(reason) => write!(formatter, "cannot encode the RON payload: {reason}"), Self::Decode(reason) => write!(formatter, "cannot decode the RON payload: {reason}"), Self::TooNew { found, current } => write!( formatter, "format version {found} is newer than the supported version {current}" ), Self::Migration(error) => write!(formatter, "migration failed: {error}"), } } } impl std::error::Error for FormatError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Self::Migration(error) => Some(error), _ => None, } } } #[cfg(test)] mod tests;