epoch_forge/lib_efo/src/epoch_traits.rs

81 lines
2.4 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! epoch_traits.rs
//!
//! All traits used by the `lib_efo` library.
//! These traits are marker traits that describe behaviour
//! common to many of the library’s element types.
#![warn(clippy::missing_docs_in_private_items)]
use serde::Serialize;
use std::{fs::File, io::Write};
use crate::{epoch_struct::SaveMode, error::EpochError};
/// Elements that can be compared with another instance to produce a diff.
pub trait Diffable {}
/// Elements that can be applied to the current world state.
pub trait Applyable {}
/// Elements that can advance to a next state over time.
///
/// Implementors usually provide a `.next()` method that returns the
/// element’s state after a time step (e.g., fading or diminishing).
pub trait Nextable {}
/// Elements that can be rendered into a pretty, human‑readable form.
pub trait Prettiable {
// TODO: Doc
/// Show many as a table
fn show_as_table(list: Vec<&Self>) {
list.iter().for_each(|e| {
e.show_as_log();
});
}
/// Print function as a log
fn show_as_log(&self) {
println!("{}", self.as_log())
}
/// Convert the struct into a pretty log
fn as_log(&self) -> String;
}
/// Trait representing a serialisable / writable config
pub trait ConfigWritable: Serialize {
/// The full path indicating where to save the config
fn save_path(&self) -> String;
/// The folder where to save the file to save the config
fn save_folder(&self) -> String;
/// Have the config as JSON
fn as_json(&self, action: String) -> Result<String, EpochError> {
serde_json::to_string_pretty(self).map_err(|e| EpochError::Serde {
source: e,
file_name: action,
help: None,
})
}
/// Save the config into it's nominal path
///
/// This command will NOT create all subdirectories
fn save_with_context(
&self,
// Very unsure about this versus a macro
action_description: &str,
do_not_erase: &SaveMode,
// advice: Option<String>,
) -> Result<(), EpochError> {
let mut f = match *do_not_erase {
SaveMode::Erase => File::create(self.save_path()),
SaveMode::DoNotErase => File::create_new(self.save_path()),
}
.map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?;
write!(f, "{}", self.as_json(action_description.to_owned())?)
.map_err(EpochError::ConfigWrite)?;
Ok(())
}
}