Adds some formatting, some testing and better deltas
Build Successful The build was successful
Gitea/epoch_forge/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2025-12-15 18:57:11 +01:00
parent 3bda2fa258
commit b8d7029cc7
16 changed files with 522 additions and 88 deletions

View File

@ -4,37 +4,7 @@
//! An *epoch* is a snapshot of the game state that can be written to disk or rolled back to an earlier one.
//! Every entity type (`character`, `town`, `event`, …) has the same set of operations:
//!
//! ## Summary
//!
//! | Sub-command | Usage | What it changes |
//! |-------------|-------|-----------------|
//! | **add** | `<entity> add [OPTIONS] [IDENTIFIER]` | Creates a new `<entity>`, pushes it to the epoch's list, and writes the epoch. |
//! | **del** | `<entity> del <IDENTIFIER>` | Removes the matching `<entity>` from the list and writes the epoch. |
//! | **edit** | `<entity> edit <IDENTIFIER> [OPTIONS]` | Modifies the stats/position/duration/effect/bounds of the chosen `<entity>` and writes the epoch. |
//! | **find** | `<entity> find <IDENTIFIER>` | Prints full details of a single `<entity>`. |
//! | **show** | `<entity> show [<IDENTIFIER>]` | Lists all entities on one line, or shows one `<entity>` in full detail. |
//! | **diff** | `<entity> diff <IDENTIFIER>` | Prints the difference between the current and previous epoch for that `<entity>`. |
//!
//! *`IDENTIFIER`* is either a **name** or a **@tag** (`@1234`).
//! If omitted, a random name is generated for the type you are working on.
//!
//! ### Options
//!
//! | Flag | Group | Description |
//! |------|-------|-------------|
//! | `-d, --delta` | *edit* | Treat the supplied `stats` values as a delta (add/subtract)
//! instead of an absolute overwrite. |
//! | `-v, --verbose…` | *global* | Increases the amount of diagnostic output. |
//! | `--rng <RNG>` | *add/edit* | How to initialise *missing* stats. Possible values: `zero`, `low`, `med`, `high`, `legendary`, `mixed`, `flawed`. Default: `zero`. |
//! | `--pos-exact <POS>` / `--pos <POS>` | *add/edit* | Set the entity's coordinates. `--pos-exact` forces the coordinates to be used verbatim; `--pos` applies the map's current position transformation (if any). |
//! | `--duration <DURATION>` | *add/edit* | Lifespan of the entity - e.g. `Permanent`, `Temporary` or `Duration(1)` for a one-turn event. |
//! | `--bounds <BOUNDS>` | *add/edit* | Effect limits in the form `min,max` (e.g. `10,80`). |
//! | `--effect <EFFECT>` | *add/edit* | How the effect is applied: `recurring`, `when-present`, `permanent-effect-to-apply`, `permanent-effect-applied`. |
//! | `-s, --stats <STATS>` | *add/edit* | One or more `key:value` pairs - e.g. `fod:10 military:8`. |
//! | `--rng-name` | *add* | If set, the tool generates a random name instead of using the supplied identifier. |
//!
//! All changes are **persisted immediately** to the epoch file after the
//! command completes.//!
//! ## Usage
//! All the following example use `chr` as a choice of entity but can be safely substitued to any entity: `event`, `town`, `blocker` etc...
//!
@ -65,6 +35,37 @@
//! > **Tip** - `<entity> diff` automatically loads the current epoch and the previous one, so you don't need to specify epoch numbers.
//!
//! *All changes are persisted immediately to the epoch file after the command finishes.*
//!
//! ## Summary
//!
//! | Sub-command | Usage | What it changes |
//! |-------------|------- |----------------- |
//! | **add** | `<entity> add [OPTIONS] [IDENTIFIER]` | Creates a new `<entity>`, pushes it to the epoch's list, and writes the epoch. |
//! | **del** | `<entity> del <IDENTIFIER>` | Removes the matching `<entity>` from the list and writes the epoch. |
//! | **edit** | `<entity> edit <IDENTIFIER> [OPTIONS]` | Modifies the stats/position/duration/effect/bounds of the chosen `<entity>` and writes the epoch. |
//! | **find** | `<entity> find <IDENTIFIER>` | Prints full details of a single `<entity>`. |
//! | **show** | `<entity> show [<IDENTIFIER>]` | Lists all entities on one line, or shows one `<entity>` in full detail. |
//! | **diff** | `<entity> diff <IDENTIFIER>` | Prints the difference between the current and previous epoch for that `<entity>`. |
//!
//! *`IDENTIFIER`* is either a **name** or a **@tag** (`@1234`).
//! If omitted, a random name is generated for the type you are working on.
//!
//! ### Options
//!
//! | Flag | Group | Description |
//! |------ |------- |------------- |
//! | `-d, --delta` | *edit* | Treat the supplied `stats` values as a delta (add/subtract) instead of an absolute overwrite. |
//! | `-v, --verbose…` | *global* | Increases the amount of diagnostic output. |
//! | `--rng <RNG>` | *add/edit* | How to initialise *missing* stats. Possible values: `zero`, `low`, `med`, `high`, `legendary`, `mixed`, `flawed`. Default: `zero`. |
//! | `--pos-exact <POS>` / `--pos <POS>` | *add/edit* | Set the entity's coordinates. `--pos-exact` forces the coordinates to be used verbatim; `--pos` applies the map's current position transformation (if any). |
//! | `--duration <DURATION>` | *add/edit* | Lifespan of the entity - e.g. `Permanent`, `Temporary` or `Duration(1)` for a one-turn event. |
//! | `--bounds <BOUNDS>` | *add/edit* | Effect limits in the form `min,max` (e.g. `10,80`). |
//! | `--effect <EFFECT>` | *add/edit* | How the effect is applied: `recurring`, `when-present`, `permanent-effect-to-apply`, `permanent-effect-applied`. |
//! | `-s, --stats <STATS>` | *add/edit* | One or more `key:value` pairs - e.g. `fod:10 military:8`. |
//! | `--rng-name` | *add* | If set, the tool generates a random name instead of using the supplied identifier. |
//!
//! All changes are **persisted immediately** to the epoch file after the
//! command completes.
#![warn(unused_attributes)]
use clap::{Args, Subcommand};
@ -305,7 +306,11 @@ pub(crate) fn handle_create_entity(
// Create new (rng) entity
let mut entity = Entity::create_rng(e_type, &entity_args.rng)?;
// Update entity with sensible defaults
helper_functions::update_stats(&entity_args.common_args.stats, false, &mut entity);
helper_functions::update_stats(
&entity_args.common_args.stats,
stats::Modification::Replace,
&mut entity,
);
helper_functions::update_defaults(entity_args, &mut entity);
// Do all updates from the common args
@ -443,7 +448,7 @@ fn handle_edit_entity(
}
helper_functions::update_stats(
&entity_args.common_args.stats,
entity_args.delta,
entity_args.delta.into(),
&mut entity,
);
let position = if let Some(position) = &entity_args.common_args.position {

View File

@ -12,9 +12,9 @@ use log::info;
use crate::commands::entity_generic::{AddArgs, CommonArgs};
/// Update the given stats with the given argumenbts
/// Note that this function will not change name & id due to the usage variance between caller
pub(crate) fn update_stats(pair_list: &Vec<StatPair>, is_a_delta: bool, e: &mut Entity) {
pub(crate) fn update_stats(pair_list: &Vec<StatPair>, delta: stats::Modification, e: &mut Entity) {
for stat in pair_list {
e.change_stat_fuzzy(stat.clone(), is_a_delta);
e.change_stat_fuzzy(stat.clone(), delta);
}
}
@ -126,10 +126,10 @@ pub fn update_common_values(
entity.modify_description(description.clone());
}
if let Some(prestige) = &entity_args.prestige {
entity.modify_prestige(*prestige)
entity.modify_prestige(*prestige, stats::Modification::Replace)
}
if let Some(prestige) = &entity_args.prestige_add {
entity.modify_prestige_by_delta(*prestige)
entity.modify_prestige(*prestige, stats::Modification::Delta)
}
}

View File

@ -33,16 +33,16 @@
//!
//! ### Summary
//!
//! | Sub-command | Usage | What it changes |
//! |-------------|-------|-----------------|
//! | `log` | `efo epoch log [--limit N]` | Prints the chronological list of epochs up to the current one. |
//! | `switch` | `efo epoch switch <id>` | Sets the current epoch to the specified `<id>` (must already exist). |
//! | `next` | `efo epoch next` | Generates the next scheduled epoch and inserts it. |
//! | `reset` | `efo epoch reset` | Deletes all epochs with an identifier greater than the current one. |
//! | `diff` | `efo epoch diff <id1> <id2>` | *Unimplemented* - placeholder for future diffing logic. |
//! | `tag` | `efo epoch tag <TAG>` | Adds a unique tag to the current epoch, updating the global tag map. |
//! | `fsck` | `efo epoch fsck` | *Unimplemented* - intended to run a consistency check. |
//! | `summary` | `efo epoch summary <text>` | Replaces the `summary` field of the current epoch with `<text>`. |
//! | Sub-command | Usage | What it changes |
//! |-------------|------------------------------|----------------------------------------------------------------------|
//! | `log` | `efo epoch log [--limit N]` | Prints the chronological list of epochs up to the current one. |
//! | `switch` | `efo epoch switch <id>` | Sets the current epoch to the specified `<id>` (must already exist). |
//! | `next` | `efo epoch next` | Generates the next scheduled epoch and inserts it. |
//! | `reset` | `efo epoch reset` | Deletes all epochs with an identifier greater than the current one. |
//! | `diff` | `efo epoch diff <id1> <id2>` | *Unimplemented* - placeholder for future diffing logic. |
//! | `tag` | `efo epoch tag <TAG>` | Adds a unique tag to the current epoch, updating the global tag map. |
//! | `fsck` | `efo epoch fsck` | *Unimplemented* - intended to run a consistency check. |
//! | `summary` | `efo epoch summary <text>` | Replaces the `summary` field of the current epoch with `<text>`. |
//!
#![warn(missing_docs, clippy::missing_docs_in_private_items)]

View File

@ -96,20 +96,27 @@ fn uuid_to_symbol(id: Uuid, epoch_info: &EpochInfo, e_type: &stats::EntityType)
///
/// This function performs a direct overwrite: the existing value is
/// discarded and the new value from `pair` is written in its place.
fn overwrite_stat(stats: &mut stats::OverallStats, pair: stats::StatPair) {
let affected_stat = stats.get_field_mut(&pair.stat);
*affected_stat = pair.value;
}
/// Add a delta to a statistic in `stats`.
///
/// The delta in `pair.value` is added to the current statistic value
/// using `saturating_add`, so that the result never overflows the
/// underlying integer type.
fn add_to_stat(stats: &mut stats::OverallStats, pair: stats::StatPair) {
let affected_stat = stats.get_field_mut(&pair.stat);
let current_value = *affected_stat;
*affected_stat = stats::GenericStat(current_value.saturating_add(*pair.value));
#[inline]
fn overwrite_stat(
stats: &mut stats::OverallStats,
pair: stats::StatPair,
delta: stats::Modification,
) {
match delta {
stats::Modification::Delta => {
let affected_stat = stats.get_field_mut(&pair.stat);
let current_value = *affected_stat;
*affected_stat = stats::GenericStat(current_value.saturating_add(*pair.value));
}
stats::Modification::Replace => {
let affected_stat = stats.get_field_mut(&pair.stat);
*affected_stat = pair.value;
}
stats::Modification::Delete => {
let affected_stat = stats.get_field_mut(&pair.stat);
*affected_stat = stats::GenericStat::default();
}
}
}
/// Compare a field on `self` with the same field on `other`.

View File

@ -256,8 +256,8 @@ impl Entity {
/// # Arguments
/// * `pair` - The stat pair containing the key and new value.
///
pub fn change_stat_strict(&mut self, pair: stats::StatPair) {
implementations::overwrite_stat(&mut self.stats, pair);
pub fn change_stat_strict(&mut self, pair: stats::StatPair, delta: stats::Modification) {
implementations::overwrite_stat(&mut self.stats, pair, delta);
}
/// Mutate a statistic in a “fuzzy” way.
@ -269,7 +269,7 @@ impl Entity {
/// # Parameters
/// * `pair` - a `StatPair` that contains the target statistic and the
/// value that should be used for the fuzzy change.
pub fn change_stat_fuzzy(&mut self, pair: stats::StatPair, delta: bool) {
pub fn change_stat_fuzzy(&mut self, pair: stats::StatPair, delta: stats::Modification) {
let stats_demo = [
stats::ListStats::Population,
stats::ListStats::Growthrate,
@ -314,7 +314,7 @@ impl Entity {
self.change_random_stats_by(&stats_inf, pair.value, delta)
}
_ => self.change_stat_strict(pair),
_ => self.change_stat_strict(pair, delta),
}
}
@ -329,7 +329,7 @@ impl Entity {
&mut self,
stats_demo: &[stats::ListStats],
amount: stats::GenericStat,
delta: bool,
delta: stats::Modification,
) {
let mut r = rand::rng();
let nb = (1..stats_demo.len() + 1).choose(&mut r).unwrap_or(1);
@ -338,17 +338,13 @@ impl Entity {
let (a, b) = (std::cmp::min(a, b), std::cmp::max(a, b));
let mut value = || stats::GenericStat((a..b).choose(&mut r).unwrap_or(1));
stats.for_each(|stat| {
if delta {
self.delta_stat(stats::StatPair {
self.change_stat_strict(
stats::StatPair {
stat: *stat,
value: value(),
});
} else {
self.change_stat_strict(stats::StatPair {
stat: *stat,
value: value(),
})
}
},
delta,
);
});
}
/// Change the entity's duration.
@ -383,8 +379,9 @@ impl Entity {
///
/// # Arguments
/// * `pair` - The stat pair representing the change to apply.
#[deprecated]
pub fn delta_stat(&mut self, pair: stats::StatPair) {
implementations::add_to_stat(&mut self.stats, pair);
implementations::overwrite_stat(&mut self.stats, pair, stats::Modification::Delta);
}
/// Replace the entity's duration.
@ -457,13 +454,14 @@ impl Entity {
///
/// The prestige value is stored directly in the entity's metadata
/// and overwrites any previous value.
pub fn modify_prestige(&mut self, prestige: stats::GenericStat) {
self.metadata.prestige = prestige;
}
/// Adjusts the entity's prestige stat by adding a delta.
pub fn modify_prestige_by_delta(&mut self, prestige: stats::GenericStat) {
self.metadata.prestige = self.metadata.prestige.add(prestige);
pub fn modify_prestige(&mut self, prestige: stats::GenericStat, delta: stats::Modification) {
match delta {
stats::Modification::Delta => {
self.metadata.prestige = self.metadata.prestige.add(prestige)
}
stats::Modification::Replace => self.metadata.prestige = prestige,
stats::Modification::Delete => self.metadata.prestige = stats::GenericStat(0),
}
}
/// Add a governor to the entity if the id exists

View File

@ -0,0 +1,50 @@
---
source: lib_efo/src/entity/test.rs
expression: dump_entity(&e)
---
{
"name": "JBE Zorg",
"description": "Another description",
"id": "00000000-0000-0000-0000-000000000001",
"stats": {
"demographics": 0,
"population": 14,
"growth_rate": 0,
"crime": 0,
"happiness": 0,
"economy": 0,
"food": 0,
"industry": 0,
"science": 0,
"trade": 0,
"military": 0,
"army": 0,
"strength": 0,
"fortification": 0,
"threat": 0,
"infrastructure": 0,
"bureaucracy": 0,
"transportation": 0,
"sprawl": 0,
"health": 0
},
"metadata": {
"position": [
6000,
40000
],
"capital": null,
"governor": null,
"faction": 42,
"links": [],
"prestige": 30,
"reach": "Global"
},
"entity_type": "Event",
"duration": "Done",
"effect_nature": "Recurring",
"effect_bounds": {
"min": 0,
"max": 0
}
}

View File

@ -0,0 +1,50 @@
---
source: lib_efo/src/entity/test.rs
expression: dump_entity(&e)
---
{
"name": "JBE Zorg",
"description": "Another description",
"id": "00000000-0000-0000-0000-000000000001",
"stats": {
"demographics": 0,
"population": 14,
"growth_rate": 0,
"crime": 0,
"happiness": 0,
"economy": 0,
"food": 0,
"industry": 0,
"science": 0,
"trade": 0,
"military": 0,
"army": 0,
"strength": 0,
"fortification": 0,
"threat": 0,
"infrastructure": 0,
"bureaucracy": 0,
"transportation": 0,
"sprawl": 0,
"health": 0
},
"metadata": {
"position": [
6000,
40000
],
"capital": "ffffffff-ffff-ffff-ffff-ffffffffffff",
"governor": "00000000-0000-0000-0000-000000000000",
"faction": 42,
"links": [],
"prestige": 30,
"reach": "Global"
},
"entity_type": "Event",
"duration": "Done",
"effect_nature": "Recurring",
"effect_bounds": {
"min": 0,
"max": 0
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,7 @@
// tests/mod.rs - or put this inside your crate's tests module
#![allow(unused_imports)]
use crate::stats::{ListStats, PositionGrid};
use std::arch::x86_64::_mm256_mask_inserti64x2;
use std::str::FromStr;
@ -13,6 +14,7 @@ use std::io::Write;
use super::*;
use crate::Displayable;
use cli_table::Cell;
use insta::{assert_debug_snapshot, assert_snapshot};
use uuid::Uuid;
@ -354,10 +356,13 @@ fn snapshot_overwrite_stat() {
let mut entity = Entity::default();
let stats = OverallStats::linear(0);
entity.stats = stats;
entity.change_stat_strict(StatPair {
stat: stats::ListStats::Population,
value: stats::GenericStat(33),
});
entity.change_stat_strict(
StatPair {
stat: stats::ListStats::Population,
value: stats::GenericStat(33),
},
stats::Modification::Replace,
);
assert_snapshot!(format!("{:#?}", entity.stats));
}
@ -518,7 +523,10 @@ fn snapshot_delta_stat_positive() {
init_snapshot_env();
let mut e = Entity::default();
e.delta_stat(StatPair::from_str("health:4").unwrap());
e.change_stat_strict(
StatPair::from_str("health:4").unwrap(),
stats::Modification::Delta,
);
e.id = Uuid::nil();
assert_snapshot!(format!("{:#?}", e));
@ -593,3 +601,104 @@ fn effect_application_from_str_snapshots() {
}
assert_snapshot!(collect);
}
/// Helper that prints a “nice”, deterministic view of the entity.
/// It uses `serde_json::to_string_pretty` so that every run has the same ordering.
fn dump_entity(e: &Entity) -> String {
// We purposely ignore `temp_stats` because it is marked `#[serde(skip)]`
// and we want deterministic snapshots.
serde_json::to_string_pretty(e).expect("JSON should be serialisable")
}
#[test]
fn test_entity_lifecycle() {
// --------------------------------------------------------------------
// 1️⃣ Create a brand‑new entity (all fields default)
// --------------------------------------------------------------------
let mut e = Entity {
name: "JBE Zorg".into(),
description: "A test entity".into(),
id: Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap(),
duration: EntityDuration::default(),
..Default::default()
};
e.change_description("A brand new description".into());
e.change_duration(EntityDuration::default());
e.modify_description("Another description".into());
let pos = Position::from((30, 200));
e.modify_position(pos.clone());
assert_eq!(pos.distance(e.position()), 0);
e.modify_position_grid(PositionGrid::from((30, 200)));
e.modify_prestige(stats::GenericStat(18), stats::Modification::Replace);
e.modify_prestige(stats::GenericStat(12), stats::Modification::Delta);
e.modify_reach(stats::Reach::Global);
e.modify_faction(Some(stats::FactionId::from(42)));
let link = TypedLink {
id: Uuid::from_u128_le(21),
role: stats::Role::Govern,
};
e.add_to_links(link);
let link_dup = link; // same value, will be ignored
e.add_to_links(link_dup);
let removed = e.del_from_links(link);
assert_eq!(removed, Some(link));
assert!(e.del_from_links(link).is_none());
e.change_stat_strict(
StatPair {
stat: ListStats::Population,
value: stats::GenericStat(10),
},
stats::Modification::Replace,
);
e.change_stat_fuzzy(
StatPair {
stat: ListStats::Population,
value: stats::GenericStat(4),
},
stats::Modification::Delta,
);
e.modify_effect_application(EffectApplication::Recurring);
e.modify_effect_bounds(EffectBounds::default());
let governor = stats::CharacterId(Uuid::nil());
e.change_governor(governor);
let capital = TownId(Uuid::max());
e.change_capital(capital);
assert_snapshot!("entity_lifecycle: start", dump_entity(&e));
assert_eq!(e.remove_capital(), Some(capital));
assert_eq!(e.remove_capital(), None);
assert_eq!(e.remove_governor(), Some(governor));
assert_eq!(e.remove_governor(), None);
assert_snapshot!("entity_lifecycle: end", dump_entity(&e));
assert_debug_snapshot!(
"entity_lifecycle: table",
e.stats_to_table().map(|t| t.to_string())
);
}
#[test]
fn name_prefix_match() {
let e = Entity {
name: "AlphaBetaGamma".into(),
id: Uuid::parse_str("12345678-1234-5678-1234-567812345678").unwrap(),
..Entity::default() // fill the rest with defaults
};
let ident = Some(EntityIdentifier::Name("Alpha".into()));
assert!(e.match_identifier(&ident), "Name prefix should match");
let ident = Some(EntityIdentifier::Name("Beta".into()));
assert!(!e.match_identifier(&ident), "Name prefix should NOT match");
let ident = Some(EntityIdentifier::Id("1234".into()));
assert!(e.match_identifier(&ident), "ID prefix should match");
let ident = Some(EntityIdentifier::Id("9999".into()));
assert!(!e.match_identifier(&ident), "ID prefix should NOT match");
assert!(!e.match_identifier(&None), "None should return false");
}

View File

@ -449,7 +449,7 @@ impl Position {
///
/// The distance is computed in the 2-D Euclidean space.
pub fn distance(&self, other: &Self) -> isize {
((self.0 - other.0).pow(2) + (self.1 * other.1).pow(2)).isqrt()
((self.0 - other.0).pow(2) + (self.1 - other.1).pow(2)).isqrt()
}
/// Converts this point to its corresponding grid position.
@ -723,3 +723,37 @@ pub enum Reach {
#[default]
None,
}
/// A description of how a value should be updated.
///
/// The enum is intentionally tiny – only the three actions that
/// matter in our state‑diff engine. Each variant is documented
/// with a short, practical example so you know exactly when
/// you’d pick it.
///
/// The enum is `Copy`, so you can freely pass it around without
/// ownership worries. The `From<&str>` implementation below
/// lets you read the operation name from configuration files or
/// CLI flags:
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Modification {
/// The modification will be a *delta*, i.e. an increment.
///
/// For numeric values this is equivalent to adding the new
/// value to the existing one. For collections it usually
/// means “append”.
Delta,
/// The modification will *replace* the existing value.
///
/// This is a hard overwrite: the old value is dropped
/// entirely and the new one is written in its place.
Replace,
/// The modification will *reset* the underlying value.
///
/// For plain types this is typically a default/zero value.
/// For `Option<T>` it sets the field to `None`. It can
/// also be interpreted as “delete the field entirely”.
Delete,
}

View File

@ -138,6 +138,16 @@ impl From<(isize, isize)> for Position {
Self(value.0, value.1)
}
}
/// Convert a tuple of two signed integers into a `PositionGrid`.
///
/// This implementation simply wraps the `(isize, isize)` tuple into a
/// `Position` struct. It is equivalent to `Position(x, y)` where `x` is the
/// first element and `y` is the second.
impl From<(isize, isize)> for PositionGrid {
fn from(value: (isize, isize)) -> Self {
Self(value.0, value.1)
}
}
impl std::str::FromStr for stats::Reach {
type Err = EpochError; // Clap accepts any type that implements `Display`
@ -201,3 +211,30 @@ impl FromStr for GenericStat {
.map(Self)
}
}
impl std::str::FromStr for stats::Modification {
type Err = EpochError; // placeholder – you can make a custom error
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
w if w.starts_with("delt") => Ok(stats::Modification::Delta),
"add" => Ok(stats::Modification::Delta),
w if w.starts_with("repl") => Ok(stats::Modification::Replace),
"change" => Ok(stats::Modification::Replace),
w if w.starts_with("del") => Ok(stats::Modification::Delete),
_ => Err(EpochError::ParsingArgument {
argument_parsed: s.to_owned(),
while_parsing: "Modification",
}), // trick: convert a bad string into a ParseIntError
}
}
}
impl From<bool> for stats::Modification {
fn from(value: bool) -> Self {
match value {
true => stats::Modification::Delta,
false => stats::Modification::Replace,
}
}
}

View File

@ -0,0 +1,8 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: collect
---
valid_positive = Ok(GenericStat(42))
valid_negative = Ok(GenericStat(-7))
invalid_non_numeric = Err(ParsingArgument { argument_parsed: "foo", while_parsing: "GenericStat" })

View File

@ -0,0 +1,39 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: tests
---
[
(
"delta",
Ok(
Delta,
),
),
(
"repl",
Ok(
Replace,
),
),
(
"del",
Ok(
Delete,
),
),
(
"add",
Ok(
Delta,
),
),
(
"unknown",
Err(
ParsingArgument {
argument_parsed: "unknown",
while_parsing: "Modification",
},
),
),
]

View File

@ -0,0 +1,9 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: collect
---
valid_comma_separated = Ok(PositionGrid(3, 4))
valid_larger_numbers = Ok(PositionGrid(10, 20))
invalid_non_numeric = Err(ParsePositionError("a,b"))
invalid_wrong_separator = Err(InvalidPositionFormat("3 4"))

View File

@ -0,0 +1,13 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: collect
---
id_valid = Ok(Id(Name("42@epoch")))
id_invalid_non_numeric = Ok(Id(Name("foo@bar")))
grid_tilde = Ok(Grid(PositionGrid(3, 4)))
grid_g = Ok(Grid(PositionGrid(5, 6)))
grid_invalid_bad_prefix = Err(ParsingArgument { argument_parsed: "~bad,grid", while_parsing: "PositionIdentifier::PositionGrid" })
exact_valid = Ok(Exact(Position(7, 8)))
exact_invalid_non_numeric = Err(ParsingArgument { argument_parsed: "x,y", while_parsing: "PositionIdentifier::Position" })
invalid_no_delimiter = Err(ParsingArgument { argument_parsed: "3-4", while_parsing: "PositionIdentifier::Position" })

View File

@ -349,3 +349,71 @@ fn test_reach_parsing() {
assert_debug_snapshot!(format!("parse_{}", input), parsed);
}
}
#[test]
fn generic_stat_from_str_snapshots() {
let test_cases = [
("valid_positive", "42"),
("valid_negative", "-7"),
("invalid_non_numeric", "foo"),
];
let mut collect = String::new();
for (snapshot_name, input) in test_cases {
let result: Result<GenericStat, EpochError> = GenericStat::from_str(input);
collect = format!("{}\n{} = {:?}", collect, snapshot_name, result);
}
assert_snapshot!(collect);
}
#[test]
fn position_grid_from_str_snapshots() {
let mut collect = String::new();
let test_cases = [
("valid_comma_separated", "3,4"),
("valid_larger_numbers", "10,20"),
("invalid_non_numeric", "a,b"),
("invalid_wrong_separator", "3 4"),
];
for (snapshot_name, input) in test_cases {
let result: Result<stats::PositionGrid, EpochError> = stats::PositionGrid::from_str(input);
collect = format!("{}\n{} = {:?}", collect, snapshot_name, result);
}
assert_snapshot!(collect);
}
#[test]
fn position_identifier_from_str_snapshots() {
let test_cases = [
// ID‑variant
("id_valid", "42@epoch"),
("id_invalid_non_numeric", "foo@bar"),
// Grid‑variant
("grid_tilde", "~3,4"),
("grid_g", "g5,6"),
("grid_invalid_bad_prefix", "~bad,grid"),
// Exact‑variant
("exact_valid", "7,8"),
("exact_invalid_non_numeric", "x,y"),
// General invalid
("invalid_no_delimiter", "3-4"),
];
let mut collect = String::new();
for (snapshot_name, input) in test_cases {
let result: Result<stats::PositionIdentifier, EpochError> =
stats::PositionIdentifier::from_str(input);
collect = format!("{}\n{} = {:?}", collect, snapshot_name, result);
}
assert_snapshot!(collect);
}
#[test]
fn test_modification_from_str() {
let tests = [
("delta", "delta".parse::<stats::Modification>()),
("repl", "repl".parse::<stats::Modification>()),
("del", "del".parse::<stats::Modification>()),
("add", "add".parse::<stats::Modification>()),
("unknown", "unknown".parse::<stats::Modification>()),
];
assert_debug_snapshot!(tests);
}