epoch_forge/lib_efo/src/lib.rs

143 lines
4.8 KiB
Rust

//! # `lib_efo`
//!
//! The **engine** that drives *Epoch Forge*. It contains a pure, representation of a fantasy world and all the logic needed to manipulate it.
//!
//! All public types implement `serde::Serialize / Deserialize` so that they can
//! be persisted easily. The `World` struct also offers a convenient
//! `World::load()` / `World::save()` API that uses the default JSON file
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
#![deny(clippy::unwrap_used)]
use crate::epoch::EpochInfo;
#[macro_use]
#[allow(unused_assignments)]
pub mod error;
pub mod entity;
pub mod epoch;
pub mod naming;
pub mod stats;
pub mod utils;
// use std::io::Result as IoResult;
// /// Marker trait for anything that can be persisted via the `Store<T>` abstraction.
// ///
// /// It is a thin wrapper around `serde::Serialize` and `serde::de::DeserializeOwned` so that the
// /// compiler can infer that the type is both serialisable *and* deserialisable.
// pub trait Persistable: serde::Serialize + serde::de::DeserializeOwned {}
// impl<T> Persistable for T where T: serde::Serialize + serde::de::DeserializeOwned + 'static {}
// /// The generic store. All domain entities that need persistence should use this trait.
// /// It can be backed by a file, a DB, an HTTP API, … as long as it knows how to read/write the type `T`.
// pub trait Store<T>
// where
// T: Persistable,
// {
// /// Read a value identified by `id`.
// fn read(&self, id: &str) -> IoResult<Option<T>>;
// /// Write (or overwrite) a value identified by `id`.
// fn write(&self, id: &str, value: &T) -> IoResult<()>;
// /// Delete the value identified by `id`.
// fn delete(&self, id: &str) -> IoResult<()>;
// /// List all ids known to this store.
// fn list_ids(&self) -> IoResult<Vec<String>>;
// }
/// A trait for types that can be displayed in a command-line tool.
///
/// Implementors should provide three levels of representation:
/// 1. **Full** - a detailed view suitable for a long-running command.
/// 2. **Short** - a concise, user-friendly view that fits on a single line.
/// 3. **Oneline** - a compact, machine-friendly string that can be embedded
/// inside a `Vec<T>` representation.
///
/// ## `Vec<T>` support
///
/// The trait is implemented generically for `Vec<T>` as long as `T: Displayable`.
/// This allows you to call `full_display`, `short_display` or `oneline_display`
/// directly on a vector of displayable items.
pub trait Displayable {
/// Return a fully-described string representation.
fn print_full(&self, epoch_info: &EpochInfo) {
println!("{}", self.short_display(epoch_info));
}
/// Return a short, user-friendly string. Resolves Ids
fn short_display(&self, _epoch_info: &EpochInfo) -> String {
self.oneline_display()
}
/// Return a one-liner string, suitable for embedding in a collection
/// representation (e.g. a `Vec<T>`). Implementations should avoid
/// new-lines to keep the output usable in a single line context.
fn oneline_display(&self) -> String;
}
/// Implement `Displayable` for vectors of displayable items.
///
/// The implementation simply delegates to the underlying `T::oneline_display`
/// method and joins the results with a comma. It works for any `T` that
/// already implements `Displayable`. This is a **blanket implementation**,
/// so you do not need to write a manual impl for each concrete type
impl<T: Displayable> Displayable for Vec<T> {
fn print_full(&self, epoch_info: &EpochInfo) {
self.iter().for_each(|e| e.print_full(epoch_info));
}
fn short_display(&self, epoch_info: &EpochInfo) -> String {
self.iter()
.map(|e| e.short_display(epoch_info))
.collect::<Vec<String>>()
.join("\n")
}
fn oneline_display(&self) -> String {
// No brackets - just a flat, comma-separated list.
self.iter()
.map(|x| x.oneline_display())
.collect::<Vec<_>>()
.join("\n")
}
}
// tests/api.rs --------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use insta::assert_snapshot;
struct Dummy {
name: String,
}
impl Displayable for Dummy {
fn oneline_display(&self) -> String {
self.name.clone()
}
}
#[test]
fn test_displayable_vec() {
let vec = vec![
Dummy {
name: "Alice".to_string(),
},
Dummy {
name: "Bob".to_string(),
},
Dummy {
name: "Eve".to_string(),
},
];
let efo = EpochInfo::default();
vec.print_full(&efo);
vec.short_display(&efo);
assert_snapshot!("dummy_vec_oneline", vec.oneline_display());
assert_snapshot!("dummy_vec_oneline", vec.short_display(&efo));
}
}