happenstance_sync_testkit/violation.rs
1//! How a sync rule fails: a value, not a panic.
2
3use alloc::string::String;
4use core::fmt;
5
6/// A peer did something a sync rule forbids.
7///
8/// Every rule in [`rules`](crate::rules) returns `Result<RuleOutcome,
9/// Violation>`, and every emitter's test function returns
10/// `Result<(), Violation>`, so a failure reaches libtest — or
11/// `wasm-bindgen-test`, which accepts the same shape — as the test's error,
12/// named by the clause it breaks. The event-store and projection families fail
13/// by panicking instead; this family returns the failure because a rule that
14/// cannot fail without a panic would need a `panic!` in this crate's library
15/// code, which the workspace's standard forbids.
16///
17/// `Debug` prints what `Display` prints. Libtest reports a returned error
18/// through `Debug`, and a derived one would bury the message in field syntax.
19#[derive(Clone, PartialEq, Eq)]
20pub struct Violation {
21 clause: &'static str,
22 message: String,
23}
24
25impl Violation {
26 /// A breach of `clause`, described by `message`.
27 #[must_use]
28 pub fn new(clause: &'static str, message: impl Into<String>) -> Self {
29 Self {
30 clause,
31 message: message.into(),
32 }
33 }
34
35 /// The specification clause the peer broke, as `"SY-1"`.
36 #[must_use]
37 pub const fn clause(&self) -> &'static str {
38 self.clause
39 }
40
41 /// What the peer did, in the rule's words.
42 #[must_use]
43 pub fn message(&self) -> &str {
44 &self.message
45 }
46}
47
48impl fmt::Display for Violation {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 write!(f, "{} violated: {}", self.clause, self.message)
51 }
52}
53
54impl fmt::Debug for Violation {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 fmt::Display::fmt(self, f)
57 }
58}
59
60impl core::error::Error for Violation {}
61
62/// `Ok(())` when `holds`, otherwise a [`Violation`] of `clause` whose message
63/// is built only on the failing path.
64pub(crate) fn ensure(
65 holds: bool,
66 clause: &'static str,
67 message: impl FnOnce() -> String,
68) -> Result<(), Violation> {
69 if holds {
70 Ok(())
71 } else {
72 Err(Violation::new(clause, message()))
73 }
74}