Skip to main content

io_pass/
lib.rs

1//! The logic of passing values through named stages.
2//!
3//! `io-pass` keeps ownership explicit: every stage either passes a value onward
4//! or blocks it while returning the value and a reason. A [`Passage`] records a
5//! trace, stops at the first block, and never silently discards input.
6//!
7//! # Example
8//!
9//! ```
10//! use io_pass::{PassResult, Passage, Stage};
11//!
12//! let mut passage = Passage::<String, &'static str>::new();
13//! passage.push(Stage::inspect("not empty", |value: &String| {
14//!     if value.is_empty() { Err("empty") } else { Ok(()) }
15//! })?)?;
16//! passage.push(Stage::transform("normalize", |value: String| value.trim().to_lowercase())?)?;
17//!
18//! let result = passage.run("  PASS  ".to_owned());
19//! match result {
20//!     PassResult::Passed(done) => assert_eq!(done.value(), "pass"),
21//!     PassResult::Blocked(_) => unreachable!(),
22//! }
23//! # Ok::<(), io_pass::Error>(())
24//! ```
25
26#![forbid(unsafe_code)]
27#![warn(missing_docs)]
28
29use std::error::Error as StdError;
30use std::fmt;
31use std::sync::Arc;
32
33/// Whether one pipeline stage passed or blocked a value.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub enum TraceStatus {
36    /// The value continued to the next stage.
37    Passed,
38    /// The value stopped at this stage.
39    Blocked,
40}
41
42/// One immutable entry in a passage trace.
43#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44pub struct TraceEntry {
45    stage: String,
46    status: TraceStatus,
47}
48
49impl TraceEntry {
50    fn new(stage: String, status: TraceStatus) -> Self {
51        Self { stage, status }
52    }
53
54    /// Returns the stage name.
55    pub fn stage(&self) -> &str {
56        &self.stage
57    }
58
59    /// Returns whether the stage passed or blocked.
60    pub const fn status(&self) -> TraceStatus {
61        self.status
62    }
63}
64
65/// A stage's ownership-preserving decision.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub enum StageOutcome<T, E> {
68    /// Pass the value onward.
69    Pass(T),
70    /// Stop and return both value and reason.
71    Block {
72        /// Value at the point it was blocked.
73        value: T,
74        /// Application-defined block reason.
75        reason: E,
76    },
77}
78
79impl<T, E> StageOutcome<T, E> {
80    /// Creates a passing outcome.
81    pub const fn pass(value: T) -> Self {
82        Self::Pass(value)
83    }
84
85    /// Creates a blocking outcome without discarding the value.
86    pub const fn block(value: T, reason: E) -> Self {
87        Self::Block { value, reason }
88    }
89
90    /// Returns whether this outcome passes.
91    pub const fn is_pass(&self) -> bool {
92        matches!(self, Self::Pass(_))
93    }
94
95    /// Consumes the outcome and returns its value regardless of decision.
96    pub fn into_value(self) -> T {
97        match self {
98            Self::Pass(value) | Self::Block { value, .. } => value,
99        }
100    }
101}
102
103type StageFn<T, E> = dyn Fn(T) -> StageOutcome<T, E> + Send + Sync + 'static;
104
105/// A named, cloneable, thread-safe pass-or-block stage.
106pub struct Stage<T, E> {
107    name: String,
108    operation: Arc<StageFn<T, E>>,
109}
110
111impl<T, E> Clone for Stage<T, E> {
112    fn clone(&self) -> Self {
113        Self {
114            name: self.name.clone(),
115            operation: Arc::clone(&self.operation),
116        }
117    }
118}
119
120impl<T, E> fmt::Debug for Stage<T, E> {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        f.debug_struct("Stage").field("name", &self.name).finish()
123    }
124}
125
126impl<T: 'static, E: 'static> Stage<T, E> {
127    /// Creates a fully custom stage.
128    pub fn new(
129        name: impl Into<String>,
130        operation: impl Fn(T) -> StageOutcome<T, E> + Send + Sync + 'static,
131    ) -> Result<Self, Error> {
132        let name = valid_name(name.into())?;
133        Ok(Self {
134            name,
135            operation: Arc::new(operation),
136        })
137    }
138
139    /// Creates a read-only gate from an inspection returning `Ok` or a reason.
140    ///
141    /// The value is returned unchanged in both branches.
142    pub fn inspect(
143        name: impl Into<String>,
144        inspection: impl Fn(&T) -> Result<(), E> + Send + Sync + 'static,
145    ) -> Result<Self, Error> {
146        Self::new(name, move |value| match inspection(&value) {
147            Ok(()) => StageOutcome::Pass(value),
148            Err(reason) => StageOutcome::Block { value, reason },
149        })
150    }
151
152    /// Creates an infallible same-type transformation stage.
153    pub fn transform(
154        name: impl Into<String>,
155        transformation: impl Fn(T) -> T + Send + Sync + 'static,
156    ) -> Result<Self, Error> {
157        Self::new(name, move |value| StageOutcome::Pass(transformation(value)))
158    }
159
160    /// Returns the stage name.
161    pub fn name(&self) -> &str {
162        &self.name
163    }
164
165    /// Applies only this stage.
166    pub fn apply(&self, value: T) -> StageOutcome<T, E> {
167        (self.operation)(value)
168    }
169}
170
171/// A value that passed every stage.
172#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct Passed<T> {
174    value: T,
175    trace: Vec<TraceEntry>,
176}
177
178impl<T> Passed<T> {
179    /// Borrows the final value.
180    pub const fn value(&self) -> &T {
181        &self.value
182    }
183
184    /// Returns the complete all-passed trace.
185    pub fn trace(&self) -> &[TraceEntry] {
186        &self.trace
187    }
188
189    /// Consumes the result and returns the final value.
190    pub fn into_value(self) -> T {
191        self.value
192    }
193}
194
195/// A value stopped at one stage with an application-defined reason.
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct Blocked<T, E> {
198    value: T,
199    reason: E,
200    trace: Vec<TraceEntry>,
201}
202
203impl<T, E> Blocked<T, E> {
204    /// Borrows the value as it existed at the blocking stage.
205    pub const fn value(&self) -> &T {
206        &self.value
207    }
208
209    /// Borrows the reason.
210    pub const fn reason(&self) -> &E {
211        &self.reason
212    }
213
214    /// Returns passed stages followed by the blocking stage.
215    pub fn trace(&self) -> &[TraceEntry] {
216        &self.trace
217    }
218
219    /// Returns the blocking stage name.
220    pub fn blocked_at(&self) -> &str {
221        self.trace
222            .last()
223            .expect("blocked results always contain one trace entry")
224            .stage()
225    }
226
227    /// Consumes the block and returns value and reason.
228    pub fn into_parts(self) -> (T, E) {
229        (self.value, self.reason)
230    }
231}
232
233/// The final result of running a [`Passage`].
234#[derive(Debug, Clone, PartialEq, Eq)]
235pub enum PassResult<T, E> {
236    /// Every stage passed.
237    Passed(Passed<T>),
238    /// One stage blocked and later stages were not called.
239    Blocked(Blocked<T, E>),
240}
241
242impl<T, E> PassResult<T, E> {
243    /// Returns whether all stages passed.
244    pub const fn is_passed(&self) -> bool {
245        matches!(self, Self::Passed(_))
246    }
247
248    /// Returns the trace for either result.
249    pub fn trace(&self) -> &[TraceEntry] {
250        match self {
251            Self::Passed(value) => value.trace(),
252            Self::Blocked(value) => value.trace(),
253        }
254    }
255
256    /// Consumes the result and returns its value, preserving no hidden copy.
257    pub fn into_value(self) -> T {
258        match self {
259            Self::Passed(value) => value.into_value(),
260            Self::Blocked(value) => value.into_parts().0,
261        }
262    }
263}
264
265/// An ordered pipeline that stops at the first block.
266#[derive(Debug, Clone)]
267pub struct Passage<T, E> {
268    stages: Vec<Stage<T, E>>,
269}
270
271impl<T: 'static, E: 'static> Passage<T, E> {
272    /// Creates an empty identity passage.
273    pub const fn new() -> Self {
274        Self { stages: Vec::new() }
275    }
276
277    /// Adds a stage, rejecting duplicate names so traces remain unambiguous.
278    pub fn push(&mut self, stage: Stage<T, E>) -> Result<(), Error> {
279        if self
280            .stages
281            .iter()
282            .any(|existing| existing.name == stage.name)
283        {
284            return Err(Error::DuplicateStage(stage.name));
285        }
286        self.stages.push(stage);
287        Ok(())
288    }
289
290    /// Adds a stage and returns the updated passage for builder-style use.
291    pub fn with_stage(mut self, stage: Stage<T, E>) -> Result<Self, Error> {
292        self.push(stage)?;
293        Ok(self)
294    }
295
296    /// Returns stages in execution order.
297    pub fn stages(&self) -> &[Stage<T, E>] {
298        &self.stages
299    }
300
301    /// Passes an owned value through stages until completion or first block.
302    pub fn run(&self, mut value: T) -> PassResult<T, E> {
303        let mut trace = Vec::with_capacity(self.stages.len());
304        for stage in &self.stages {
305            match stage.apply(value) {
306                StageOutcome::Pass(next) => {
307                    trace.push(TraceEntry::new(stage.name.clone(), TraceStatus::Passed));
308                    value = next;
309                }
310                StageOutcome::Block {
311                    value: blocked,
312                    reason,
313                } => {
314                    trace.push(TraceEntry::new(stage.name.clone(), TraceStatus::Blocked));
315                    return PassResult::Blocked(Blocked {
316                        value: blocked,
317                        reason,
318                        trace,
319                    });
320                }
321            }
322        }
323        PassResult::Passed(Passed { value, trace })
324    }
325
326    /// Redeems a single-use token into this passage.
327    pub fn run_token(&self, token: PassToken<T>) -> PassResult<T, E> {
328        self.run(token.redeem())
329    }
330}
331
332impl<T: 'static, E: 'static> Default for Passage<T, E> {
333    fn default() -> Self {
334        Self::new()
335    }
336}
337
338/// A value wrapper that can be redeemed only by consuming the token.
339#[derive(Debug, PartialEq, Eq, Hash)]
340pub struct PassToken<T> {
341    value: T,
342}
343
344impl<T> PassToken<T> {
345    /// Issues a token holding one value.
346    pub const fn issue(value: T) -> Self {
347        Self { value }
348    }
349
350    /// Consumes the token and returns its value.
351    pub fn redeem(self) -> T {
352        self.value
353    }
354
355    /// Consumes the token through a one-time handoff function.
356    pub fn pass_to<U>(self, handoff: impl FnOnce(T) -> U) -> U {
357        handoff(self.value)
358    }
359}
360
361/// Pipeline definition errors.
362#[derive(Debug, Clone, PartialEq, Eq)]
363#[non_exhaustive]
364pub enum Error {
365    /// A stage name contained only whitespace.
366    EmptyStageName,
367    /// The same stage name was inserted twice.
368    DuplicateStage(String),
369}
370
371impl fmt::Display for Error {
372    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373        match self {
374            Self::EmptyStageName => f.write_str("stage name cannot be empty"),
375            Self::DuplicateStage(name) => write!(f, "duplicate stage name: {name}"),
376        }
377    }
378}
379
380impl StdError for Error {}
381
382fn valid_name(name: String) -> Result<String, Error> {
383    if name.trim().is_empty() {
384        Err(Error::EmptyStageName)
385    } else {
386        Ok(name)
387    }
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393    use std::sync::atomic::{AtomicUsize, Ordering};
394
395    #[test]
396    fn value_passes_and_transforms_in_order() {
397        let passage = Passage::new()
398            .with_stage(Stage::<String, &str>::transform("trim", |v| v.trim().to_owned()).unwrap())
399            .unwrap()
400            .with_stage(Stage::transform("uppercase", |v: String| v.to_uppercase()).unwrap())
401            .unwrap();
402        let result = passage.run("  pass  ".to_owned());
403        assert!(result.is_passed());
404        assert_eq!(result.trace().len(), 2);
405        assert_eq!(result.into_value(), "PASS");
406    }
407
408    #[test]
409    fn block_preserves_value_reason_and_trace() {
410        let passage = Passage::new()
411            .with_stage(
412                Stage::inspect("positive", |value: &i32| {
413                    if *value > 0 {
414                        Ok(())
415                    } else {
416                        Err("not positive")
417                    }
418                })
419                .unwrap(),
420            )
421            .unwrap();
422        let result = passage.run(-7);
423        let PassResult::Blocked(blocked) = result else {
424            panic!("expected block");
425        };
426        assert_eq!(*blocked.value(), -7);
427        assert_eq!(*blocked.reason(), "not positive");
428        assert_eq!(blocked.blocked_at(), "positive");
429        assert_eq!(blocked.trace()[0].status(), TraceStatus::Blocked);
430    }
431
432    #[test]
433    fn stages_after_block_are_not_called() {
434        let calls = Arc::new(AtomicUsize::new(0));
435        let later_calls = Arc::clone(&calls);
436        let passage = Passage::new()
437            .with_stage(
438                Stage::new("block", |value| {
439                    StageOutcome::<i32, &str>::block(value, "stop")
440                })
441                .unwrap(),
442            )
443            .unwrap()
444            .with_stage(
445                Stage::transform("later", move |value| {
446                    later_calls.fetch_add(1, Ordering::SeqCst);
447                    value + 1
448                })
449                .unwrap(),
450            )
451            .unwrap();
452        assert!(!passage.run(1).is_passed());
453        assert_eq!(calls.load(Ordering::SeqCst), 0);
454    }
455
456    #[test]
457    fn empty_passage_is_identity() {
458        let passage = Passage::<Vec<u8>, ()>::new();
459        let result = passage.run(vec![1, 2, 3]);
460        assert!(result.is_passed());
461        assert!(result.trace().is_empty());
462        assert_eq!(result.into_value(), [1, 2, 3]);
463    }
464
465    #[test]
466    fn duplicate_and_empty_stage_names_are_rejected() {
467        assert!(matches!(
468            Stage::<i32, ()>::transform("  ", |value| value),
469            Err(Error::EmptyStageName)
470        ));
471        let mut passage = Passage::<i32, ()>::new();
472        passage
473            .push(Stage::transform("same", |value| value).unwrap())
474            .unwrap();
475        assert!(matches!(
476            passage.push(Stage::transform("same", |value| value).unwrap()),
477            Err(Error::DuplicateStage(_))
478        ));
479    }
480
481    #[test]
482    fn custom_stage_can_transform_before_blocking() {
483        let stage = Stage::new("cap", |value: String| {
484            let value = value.to_uppercase();
485            if value.len() <= 4 {
486                StageOutcome::Pass(value)
487            } else {
488                StageOutcome::Block {
489                    value,
490                    reason: "too long",
491                }
492            }
493        })
494        .unwrap();
495        let passage = Passage::new().with_stage(stage).unwrap();
496        let PassResult::Blocked(blocked) = passage.run("passes".to_owned()) else {
497            panic!("expected block");
498        };
499        assert_eq!(blocked.value(), "PASSES");
500    }
501
502    #[test]
503    fn passage_and_stages_are_cloneable_for_shared_rules() {
504        let passage = Passage::new()
505            .with_stage(
506                Stage::<i32, &str>::inspect("even", |value| {
507                    if value % 2 == 0 { Ok(()) } else { Err("odd") }
508                })
509                .unwrap(),
510            )
511            .unwrap();
512        let cloned = passage.clone();
513        let handle = std::thread::spawn(move || cloned.run(4).is_passed());
514        assert!(handle.join().unwrap());
515        assert!(!passage.run(3).is_passed());
516    }
517
518    #[test]
519    fn pass_token_is_consumed_by_pipeline_or_handoff() {
520        let passage = Passage::<String, ()>::new();
521        let result = passage.run_token(PassToken::issue("once".to_owned()));
522        assert_eq!(result.into_value(), "once");
523        let length = PassToken::issue("handoff").pass_to(str::len);
524        assert_eq!(length, 7);
525    }
526}