sealed_typestate/lib.rs
1#![warn(missing_docs)]
2// #![doc(html_playground_url = "https://play.rust-lang.org/")]
3//! Declare enum-based typestates easily
4
5#[macro_export]
6/// # Example
7/// In this example, a typestate called `State` is declared with two states: `State1` and `State2`.
8/// ```
9/// mod private {
10/// # pub trait Sealed {}
11/// # }
12/// # use std::marker::PhantomData;
13/// # use sealed_typestate::sealed_typestate;
14/// use private::Sealed;
15/// #
16/// sealed_typestate!(State<Sealed> {
17/// State1,
18/// State2
19/// });
20/// #
21/// struct Foo<S: State> {
22/// _marker: PhantomData<S>,
23/// }
24/// # impl Foo<State1> {
25/// # fn new() -> Self {
26/// # Self {
27/// # _marker: PhantomData
28/// # }
29/// # }
30/// # }
31/// impl Foo<State1> { fn state1_only(&self) {} }
32/// #
33/// impl Foo<State2> { fn state2_only(&self) {} }
34/// let foo = Foo::new();
35/// // This will compile
36/// foo.state1_only();
37/// ```
38/// While this will not:
39/// ```compile_fail
40/// # mod private {
41/// # pub trait Sealed {}
42/// # }
43/// # use std::marker::PhantomData;
44/// # use sealed_typestate::sealed_typestate;
45/// # use private::Sealed;
46/// #
47/// # sealed_typestate!(State<Sealed> {
48/// # State1,
49/// # State2
50/// # });
51/// #
52/// # struct Foo<S: State> {
53/// # _marker: PhantomData<S>,
54/// # }
55/// # impl Foo<State1> {
56/// # fn new() -> Self {
57/// # Self {
58/// # _marker: PhantomData
59/// # }
60/// # }
61/// # }
62/// # impl Foo<State1> { fn state1_only(&self) {} }
63/// # impl Foo<State2> { fn state2_only(&self) {} }
64/// # let foo = Foo::new();
65/// foo.state2_only();
66/// ```
67///
68macro_rules! sealed_typestate {
69 ($state:ident<_> { $($states:ident),* }) => {
70 sealed_typestate!($state<crate::private::Sealed> { $($states),* });
71 };
72 ($state:ident<$sealed:path> { $($states:ident),* }) => {
73 pub trait $state: $sealed {}
74 $(
75 pub enum $states {}
76 impl $sealed for $states {}
77 impl $state for $states {}
78 )*
79 };
80 ($state:ident { $($states:ident),* }) => {
81 sealed_typestate!($state<private::Sealed> { $($states),* });
82 mod private {
83 pub trait Sealed {}
84 }
85 };
86}
87
88#[cfg(test)]
89mod tests {
90 use trybuild::TestCases;
91
92 #[test]
93 fn test_compiles() {
94 let t = TestCases::new();
95 t.pass("tests/compile-tests/01-default-sealed-trait.rs");
96 t.pass("tests/compile-tests/02-specified-sealed-trait.rs");
97 t.pass("tests/compile-tests/03-in-place-declared-sealed-trait.rs");
98 t.compile_fail("tests/compile-tests/04-default-sealed-trait-does-not-exist.rs");
99 t.compile_fail("tests/compile-tests/05-specified-sealed-trait-does-not-exist.rs");
100 }
101}