use arco::state::State;
use std::fmt;
use std::hash::{Hash, Hasher};
#[derive(Clone)]
struct Counter {
value: u8,
max_value: u8,
}
impl Counter {
fn new(value: u8, max_value: u8) -> Self {
assert!(value <= max_value);
Self { value, max_value }
}
fn increment(&self) -> Self {
if self.value >= self.max_value {
Self { value: 0, ..*self }
} else {
Self {
value: self.value + 1,
..*self
}
}
}
fn reset(&self) -> Self {
Self { value: 0, ..*self }
}
}
impl State for Counter {
type Encoding = Vec<u8>;
fn canonical_encoding(&self) -> Self::Encoding {
vec![self.value, self.max_value]
}
fn distance(&self, other: &Self) -> u32 {
let mut diff = 0u32;
if self.value != other.value {
diff += 1;
}
if self.max_value != other.max_value {
diff += 1;
}
diff
}
}
impl PartialEq for Counter {
fn eq(&self, other: &Self) -> bool {
self.value == other.value && self.max_value == other.max_value
}
}
impl Eq for Counter {}
impl Hash for Counter {
fn hash<H: Hasher>(&self, state: &mut H) {
self.value.hash(state);
self.max_value.hash(state);
}
}
impl fmt::Debug for Counter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Counter({}/{})", self.value, self.max_value)
}
}
impl fmt::Display for Counter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.value)
}
}
fn main() {
println!("=== Example 01: Custom State ===\n");
let s1 = Counter::new(0, 5);
let s2 = Counter::new(3, 5);
let s3 = Counter::new(0, 5);
println!("s1 encoding: {:?}", s1.canonical_encoding());
println!("s2 encoding: {:?}", s2.canonical_encoding());
println!("s3 encoding: {:?}", s3.canonical_encoding());
println!("\ns1 == s2: {}", s1 == s2);
println!("s1 == s3: {}", s1 == s3);
println!("\nDistance s1 → s2: {}", s1.distance(&s2)); println!("Distance s1 → s3: {}", s1.distance(&s3)); println!("Distance s1 → s1: {}", s1.distance(&s1));
let s4 = s1.increment();
println!("\ns1 after increment: {} (unchanged)", s1.value);
println!("s4 after increment: {} (new state)", s4.value);
let s5 = s1.reset();
println!("s1 after reset: {} (unchanged)", s1.value);
println!("s5 after reset: {} (new state)", s5.value);
println!("\n✓ Counter implements State correctly.");
println!(" The state provides reusable operations (increment, reset).");
println!(" Rules will decide *when* to call them.");
}