diff --git a/Cargo.lock b/Cargo.lock index bce1ca6..1d8352a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -108,6 +108,7 @@ dependencies = [ "colored", "derive_more", "env_logger", + "insta", "lib_efo", "log", "miette", @@ -212,6 +213,18 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "console" +version = "0.15.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8" +dependencies = [ + "encode_unicode", + "libc", + "once_cell", + "windows-sys 0.59.0", +] + [[package]] name = "convert_case" version = "0.10.0" @@ -265,6 +278,12 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + [[package]] name = "env_filter" version = "0.1.4" @@ -322,6 +341,17 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "insta" +version = "1.44.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c943d4415edd8153251b6f197de5eb1640e56d84e8d9159bea190421c73698" +dependencies = [ + "console", + "once_cell", + "similar", +] + [[package]] name = "is_ci" version = "1.2.0" @@ -383,6 +413,7 @@ dependencies = [ "colored", "derive_more", "env_logger", + "insta", "log", "miette", "once_cell", @@ -678,6 +709,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + [[package]] name = "strsim" version = "0.11.1" diff --git a/Cargo.toml b/Cargo.toml index 7b1664b..79701f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,3 +13,4 @@ env_logger = "0.11.8" log = "0.4.28" derive_more = { version = "2.0.1", features = ["display", "add"] } colored = "3.0.0" +insta = "1.44.3" diff --git a/README.md b/README.md index 168d6f4..8bf7e8d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,5 @@ -![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg) - # πŸ“¦ Epoch Forge (`epoch_forge`) +![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg) > **A Rust-powered CLI for managing fantasy organisations across time.** > *Think of it as a living, breathing world-state engine that lets you β€œrewind”, β€œfast-forward”, and **alter** the history of guilds, towns, wars, and characters.* diff --git a/bin_efo/Cargo.toml b/bin_efo/Cargo.toml index ae03300..1accc67 100644 --- a/bin_efo/Cargo.toml +++ b/bin_efo/Cargo.toml @@ -14,3 +14,6 @@ env_logger = {workspace = true} log = {workspace = true} derive_more = {workspace = true} colored = {workspace = true} + +[dev-dependencies] +insta = {workspace = true} diff --git a/bin_efo/src/success.rs b/bin_efo/src/success.rs index 436082c..702b1af 100644 --- a/bin_efo/src/success.rs +++ b/bin_efo/src/success.rs @@ -22,13 +22,13 @@ pub enum SuccessMessages { #[display("Successfully computed the new epoch. The current epoch is now {_1} (was {_0})")] EpochNextSuccess(EpochId, EpochId), - #[display("Successfully deleted the entity {_0} ({_1} @ {_2})")] + #[display("Successfully deleted the entity {_0} ({_1} σ°»Ύ[{_2}])")] DeletedEntity(String, String, String), - #[display("Successfully created the entity {_0} ({_1} @ {_2})")] + #[display("Successfully created the entity {_0} ({_1} σ°»Ύ[{_2}])")] CreatedEntity(String, String, String), - #[display("Successfully edited the entity {_0} ({_1} @ {_2})")] + #[display("Successfully edited the entity {_0} ({_1} σ°»Ύ[{_2}])")] EditedEntity(String, String, String), #[display("Showing delta between Epoch ({_0} & {_1})")] DiffBetweenEpoch(lib_efo::epoch::EpochId, lib_efo::epoch::EpochId), diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index 615394b..e96c4e6 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -17,3 +17,7 @@ uuid = { version = "1.18.1", features = ["serde", "v4"] } colored = {workspace = true} rand = "0.9.2" once_cell = "1.21.3" + +[dev-dependencies] +insta = {workspace = true} + diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs index b1cc3e5..4d3832c 100644 --- a/lib_efo/src/entity.rs +++ b/lib_efo/src/entity.rs @@ -147,6 +147,6 @@ pub enum EntityIdentifier { Id(String), } -#[cfg(test)] #[allow(clippy::unwrap_used)] +#[cfg(test)] mod test; diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index 9c55ae9..63868af 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -29,14 +29,14 @@ impl Displayable for Entity { .metadata .capital .as_ref() - .map(|c| format!(" | πŸ’° {:>2}", c)) + .map(|c| format!("ο†œ σ°»Ύ[{:>2}] ", c).green()) .unwrap_or_default(); let governor = self .metadata .governor .as_ref() - .map(|g| format!(" | πŸ‘‘ {:>2}", g)) + .map(|g| format!("ο“Š σ°»Ύ[{:>2}]", g).red()) .unwrap_or_default(); let prestige = if *self.metadata.prestige > 0 { @@ -169,7 +169,7 @@ impl Entity { // ── Top line: out.push_str(&format!( - "[{} {} ({})]\n", + "[{} {} σ°»Ύ[{}]]\n", self.entity_type.to_symbol().blue().bold(), self.name.cyan().bold(), self.id.to_string().blue().bold() @@ -214,7 +214,7 @@ impl Entity { let symbol = if last { "└─" } else { "β”œβ”€" }; out.push_str(&indent( 1, - &format!("{} {}", symbol.cyan(), link.to_string().yellow()), + &format!("{} σ°»Ύ[{}]\n", symbol, link.to_string().yellow()), )); } } diff --git a/lib_efo/src/entity/implementations/from_impl.rs b/lib_efo/src/entity/implementations/from_impl.rs index 64c1694..b30bc5b 100644 --- a/lib_efo/src/entity/implementations/from_impl.rs +++ b/lib_efo/src/entity/implementations/from_impl.rs @@ -5,7 +5,7 @@ use crate::{ error::EpochError, }; -use std::str::FromStr; +use std::{ops::Range, str::FromStr}; /// Simple error type used by `FromStr`. /// clap only needs the error to implement `Display`, so a `String` is fine. @@ -112,3 +112,21 @@ impl FromStr for EntityIdentifier { } } } + +impl From<(usize, usize)> for EffectBounds { + fn from(value: (usize, usize)) -> Self { + Self { + min: value.0, + max: value.1, + } + } +} + +impl From> for EffectBounds { + fn from(value: Range) -> Self { + Self { + min: value.start, + max: value.end, + } + } +} diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap new file mode 100644 index 0000000..f9b9836 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap @@ -0,0 +1,14 @@ +--- +source: lib_efo/src/entity/test.rs +expression: e.to_pretty_tree() +--- +[ Hero σ°»Ύ[0c000000-0000-0000-0000-000000000000]] + β”œβ”€ metadata + β”‚ β”œβ”€ capital: Some(TownId(50)) + β”‚ β”œβ”€ prestige: 3 + β”‚ └─ position: ( 2, 4)βš“ + β”œβ”€ links + β”‚ └─ σ°»Ύ[3] + β”œβ”€ duration: β§—10 + β”œβ”€ effect_nature: Recurring + └─ effect_bounds: (1 β­Ύ 5) diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap new file mode 100644 index 0000000..3f3d182 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap @@ -0,0 +1,8 @@ +--- +source: lib_efo/src/entity/test.rs +expression: e.oneline_display() +--- +β”œβ”€β”€β”¬β”€ 0c00000 Hero  ──────> ( 2, 4)βš“ β§—10 +β”‚ β”œβ”€ Faction: 2 β”‚ Effect: ⟳ (1 β­Ύ 5), Stats: 0ο“½ 0πŸ’° 0ο„² 0σ°‘’ 3πŸ“ˆ +β”‚ └─ ο†œ σ°»Ύ[50] ο“Š σ°»Ύ[11] +β”‚ diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_no_temp.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_no_temp.snap new file mode 100644 index 0000000..e2c91d6 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_no_temp.snap @@ -0,0 +1,12 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{}\", table)" +--- +β”Œ─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐ +β”‚ DEM β”‚ POP β”‚ GRW β”‚ CRM β”‚ HPY β”‚ ECO β”‚ FOD β”‚ IND β”‚ SCI β”‚ TRD β”‚ MIL β”‚ ARM β”‚ STR β”‚ FRT β”‚ THR β”‚ IFR β”‚ BUR β”‚ TRP β”‚ SPR β”‚ HLT β”‚ +β”œ─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό────── +β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ +β”œ─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό────── +β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ +β””─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”˜ + diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_with_temp.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_with_temp.snap new file mode 100644 index 0000000..e2c91d6 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_with_temp.snap @@ -0,0 +1,12 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{}\", table)" +--- +β”Œ─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐ +β”‚ DEM β”‚ POP β”‚ GRW β”‚ CRM β”‚ HPY β”‚ ECO β”‚ FOD β”‚ IND β”‚ SCI β”‚ TRD β”‚ MIL β”‚ ARM β”‚ STR β”‚ FRT β”‚ THR β”‚ IFR β”‚ BUR β”‚ TRP β”‚ SPR β”‚ HLT β”‚ +β”œ─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό────── +β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ +β”œ─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό─────β”Ό────── +β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ 0  β”‚ +β””─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”΄─────β”˜ + diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_minimal_oneline_display-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_minimal_oneline_display-2.snap new file mode 100644 index 0000000..c7e7d4e --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_minimal_oneline_display-2.snap @@ -0,0 +1,10 @@ +--- +source: lib_efo/src/entity/test.rs +expression: e.to_pretty_tree() +--- +[ξͺ† σ°»Ύ[00000000-0000-0000-0000-000000000000]] + β”œβ”€ metadata + β”‚ └─ position: ( 0, 0)βš“ + β”œβ”€ duration: βœ” + β”œβ”€ effect_nature: PermanentEffectToApply + └─ effect_bounds: (0 β­Ύ 0) diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_minimal_oneline_display.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_minimal_oneline_display.snap new file mode 100644 index 0000000..bf6a2cb --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_minimal_oneline_display.snap @@ -0,0 +1,7 @@ +--- +source: lib_efo/src/entity/test.rs +expression: e.oneline_display() +--- +β”œβ”€β”€β”¬β”€ 0000000 ξͺ† ──────> ( 0, 0)βš“ βœ” +β”‚ └─ Faction: Ø β”‚ Effect: ☈ (0 β­Ύ 0), Stats: 0ο“½ 0πŸ’° 0ο„² 0σ°‘’ +β”‚ diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_print_full_output.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_print_full_output.snap new file mode 100644 index 0000000..67966a5 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_print_full_output.snap @@ -0,0 +1,5 @@ +--- +source: lib_efo/src/entity/test.rs +expression: output +--- + diff --git a/lib_efo/src/entity/test.rs b/lib_efo/src/entity/test.rs index ecba9cb..467fa24 100644 --- a/lib_efo/src/entity/test.rs +++ b/lib_efo/src/entity/test.rs @@ -3,8 +3,18 @@ use std::str::FromStr; -use crate::entity::{EffectBounds, EntityDuration, EntityIdentifier}; +use crate::entity::{EffectApplication, EffectBounds, Entity, EntityDuration, EntityIdentifier}; use crate::error::EpochError; +use crate::stats::{self, EntityType, MetaStats, Position, TownId}; +use std::io::Write; + +use super::*; +use crate::Displayable; +use insta::assert_snapshot; +use uuid::Uuid; + +/// The same structs & enums that the original crate exports – adjust the names +/// if your crate uses different identifiers. // ---------- EntityDuration ---------- #[test] @@ -226,3 +236,98 @@ fn entity_identifier_errors_on_invalid_id() { // _ => panic!("Expected Name variant"), // } // } +// + +/// Disable coloured output so that snapshots are stable (no ANSI codes). +fn init_snapshot_env() { + colored::control::set_override(false); +} + +/// Build a fully‑featured entity (capital, governor, prestige > 0). +fn full_entity() -> Entity { + Entity { + id: Uuid::from_u128_le(12), + name: "Hero".into(), + entity_type: EntityType::Character, // ← change to a real variant + metadata: MetaStats { + capital: Some(stats::TownId(50)), + governor: Some(stats::CharacterId(11)), + prestige: stats::GenericStat(3), + position: Position::from((2, 4)), // ← real variant + faction: Some(crate::stats::FactionId(2)), + links: vec![TownId(3)], + }, + duration: EntityDuration::Duration(10), + effect_nature: EffectApplication::Recurring, // ← real variant + effect_bounds: EffectBounds::from((1, 5)), // ← real constructor + stats: stats::OverallStats::default(), // ← real constructor + temp_stats: Some(stats::OverallStats::default()), + } +} + +#[test] +fn snapshot_full_oneline_display() { + init_snapshot_env(); + let e = full_entity(); + assert_snapshot!(e.oneline_display()); + assert_snapshot!(e.to_pretty_tree()); +} + +#[test] +fn snapshot_minimal_oneline_display() { + init_snapshot_env(); + let e = Entity::default(); + assert_snapshot!(e.oneline_display()); + assert_snapshot!(e.to_pretty_tree()); +} + +#[test] +fn snapshot_print_full_output() { + init_snapshot_env(); + + let e = full_entity(); + + // Capture stdout into a buffer + let buffer = Vec::new(); + { + // let stdout = std::io::stdout(); + // let mut handle = stdout.lock(); + + // // Temporarily swap the real stdout for our buffer. + // let original = std::mem::replace(&mut handle, &mut buffer); + // Run the method we want to snapshot. + e.print_full(); + // Restore the original stdout. + // std::mem::replace(&mut handle, original); + } + + // Convert buffer β†’ UTF‑8 string and snapshot it. + let output = String::from_utf8_lossy(&buffer); + assert_snapshot!(output); +} + +#[test] +fn snapshot_full_stats_no_temp() { + init_snapshot_env(); + + let e = full_entity(); + let table = e.full_stats_to_table().expect("table generation failed"); + assert_snapshot!(format!("{}", table)); +} + +#[test] +fn snapshot_full_stats_with_temp() { + init_snapshot_env(); + + let mut e = full_entity(); + // Give the entity a temporary stat that is *different* from the + // permanent one so we can see two distinct rows in the table. + // + // If `Stats` offers a builder or `new` you can use it here. + // Otherwise just clone the default – the snapshot will contain + // two identical rows and that is fine for a regression test. + e.temp_stats = Some(OverallStats::default()); + + let table = e.full_stats_to_table().expect("table generation failed"); + assert_snapshot!(format!("{}", table)); +} diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs index 0066830..bddb4a1 100644 --- a/lib_efo/src/stats/implementations.rs +++ b/lib_efo/src/stats/implementations.rs @@ -1,13 +1,13 @@ //! All traits implementatition for the main structs are deffered here +use crate::stats::GameStat; use colored::Colorize; use std::str::FromStr; use crate::entity::{EffectApplication, EffectBounds, EntityDuration}; use crate::error::EpochError; use crate::stats::{ - self, EntityType, FactionId, GameStat, GenericStat, ListStats, OverallStats, Position, - StatPair, Symbols, + EntityType, FactionId, GenericStat, ListStats, OverallStats, Position, Symbols, }; /// Creates a thin, deref-able wrapper around an inner type. @@ -301,68 +301,6 @@ impl OverallStats { } } -impl FromStr for StatPair { - type Err = EpochError; - - /// Parse a string into a `StatPair`. - /// - /// The input can be either in the form `"stat:value"` or `"stat value"`. - /// If the format is invalid, an `EpochError::IllFormedStatQualifier` - /// is returned. - fn from_str(s: &str) -> Result { - let (stat_str, val_str) = if let Some(idx) = s.find(':') { - (&s[..idx], &s[idx + 1..]) - } else { - let parts: Vec<&str> = s.split_whitespace().collect(); - if parts.len() != 2 { - return Err(EpochError::IllFormedStatQualifier(s.to_owned())); - } - (parts[0], parts[1]) - }; - - let stat: ListStats = stat_str.parse()?; - let value: isize = val_str - .parse() - .map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?; - Ok(StatPair { - stat, - value: stats::GenericStat(value), - }) - } -} - -/// Parse a string into a `Position`. -/// -/// The input must be two signed integers separated by a comma, optionally -/// surrounded by whitespace. Leading and trailing whitespace around each -/// component is ignored. -/// -/// # Errors -/// -/// * `ParsePositionError::InvalidFormat` - the string does not contain -/// exactly one comma or there are not exactly two components. -/// * `ParsePositionError::ParseIntError` - one of the components cannot be -/// parsed as an `isize`. -impl std::str::FromStr for Position { - type Err = EpochError; - - fn from_str(s: &str) -> Result { - let parts: Vec<&str> = s.split(',').collect(); - if parts.len() != 2 { - return Err(EpochError::InvalidPositionFormat(s.to_string())); - } - let x: isize = parts[0] - .trim() - .parse() - .map_err(|_| EpochError::ParsePositionError(s.to_string()))?; - let y: isize = parts[1] - .trim() - .parse() - .map_err(|_| EpochError::ParsePositionError(s.to_string()))?; - Ok(Position(x, y)) - } -} - impl Symbols for EntityType { fn to_shortest(&self) -> String { match self { @@ -510,5 +448,8 @@ impl Symbols for Option { } } } + +mod from_impl; + #[cfg(test)] pub(crate) mod test; diff --git a/lib_efo/src/stats/implementations/from_impl.rs b/lib_efo/src/stats/implementations/from_impl.rs new file mode 100644 index 0000000..fe89c42 --- /dev/null +++ b/lib_efo/src/stats/implementations/from_impl.rs @@ -0,0 +1,75 @@ +//! All from implementations + +use crate::{ + error::EpochError, + stats::{self, ListStats, Position, StatPair}, +}; +use std::str::FromStr; + +impl FromStr for StatPair { + type Err = EpochError; + + /// Parse a string into a `StatPair`. + /// + /// The input can be either in the form `"stat:value"` or `"stat value"`. + /// If the format is invalid, an `EpochError::IllFormedStatQualifier` + /// is returned. + fn from_str(s: &str) -> Result { + let (stat_str, val_str) = if let Some(idx) = s.find(':') { + (&s[..idx], &s[idx + 1..]) + } else { + let parts: Vec<&str> = s.split_whitespace().collect(); + if parts.len() != 2 { + return Err(EpochError::IllFormedStatQualifier(s.to_owned())); + } + (parts[0], parts[1]) + }; + + let stat: ListStats = stat_str.parse()?; + let value: isize = val_str + .parse() + .map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?; + Ok(StatPair { + stat, + value: stats::GenericStat(value), + }) + } +} + +/// Parse a string into a `Position`. +/// +/// The input must be two signed integers separated by a comma, optionally +/// surrounded by whitespace. Leading and trailing whitespace around each +/// component is ignored. +/// +/// # Errors +/// +/// * `ParsePositionError::InvalidFormat` - the string does not contain +/// exactly one comma or there are not exactly two components. +/// * `ParsePositionError::ParseIntError` - one of the components cannot be +/// parsed as an `isize`. +impl std::str::FromStr for Position { + type Err = EpochError; + + fn from_str(s: &str) -> Result { + let parts: Vec<&str> = s.split(',').collect(); + if parts.len() != 2 { + return Err(EpochError::InvalidPositionFormat(s.to_string())); + } + let x: isize = parts[0] + .trim() + .parse() + .map_err(|_| EpochError::ParsePositionError(s.to_string()))?; + let y: isize = parts[1] + .trim() + .parse() + .map_err(|_| EpochError::ParsePositionError(s.to_string()))?; + Ok(Position(x, y)) + } +} + +impl From<(isize, isize)> for Position { + fn from(value: (isize, isize)) -> Self { + Self(value.0, value.1) + } +} diff --git a/lib_efo/src/stats/implementations/test.rs b/lib_efo/src/stats/implementations/test.rs index ac75edd..03716c3 100644 --- a/lib_efo/src/stats/implementations/test.rs +++ b/lib_efo/src/stats/implementations/test.rs @@ -2,6 +2,7 @@ use super::*; use crate::stats::GameStat; use crate::stats::GenericStat; +use crate::stats::StatPair; use std::str::FromStr; struct Person {