rstm_rules/traits/
rulespace.rs

1/*
2    Appellation: rulespace <module>
3    Created At: 2025.08.30:08:03:10
4    Contrib: @FL03
5*/
6use rstm_core::{Head, Tail};
7use rstm_state::RawState;
8
9/// The [`RawSpace`] trait establishes the basis for all rule spaces within the library.
10pub trait RawSpace {
11    private! {}
12}
13
14pub trait RuleSpace<Q, S>: RawSpace
15where
16    Q: RawState,
17{
18    fn get(&self, head: &Head<Q, S>) -> Option<&Tail<Q, S>>
19    where
20        Q: PartialEq,
21        S: PartialEq;
22}
23
24/*
25 ************* Implementations *************
26*/
27
28#[cfg(feature = "alloc")]
29mod impl_alloc {
30    use super::{RawSpace, RuleSpace};
31    use crate::rule::Rule;
32    use alloc::vec::Vec;
33    use rstm_core::{Head, Tail};
34    use rstm_state::RawState;
35
36    impl<T> RawSpace for Vec<T> {
37        seal! {}
38    }
39
40    impl<Q, A> RuleSpace<Q, A> for Vec<Rule<Q, A>>
41    where
42        Q: RawState + PartialEq,
43        A: PartialEq,
44    {
45        fn get(&self, key: &Head<Q, A>) -> Option<&Tail<Q, A>> {
46            self.iter().find_map(|rule| {
47                if rule.head() == key {
48                    Some(rule.tail())
49                } else {
50                    None
51                }
52            })
53        }
54    }
55}
56
57#[cfg(feature = "std")]
58mod impl_std {
59    use super::{RawSpace, RuleSpace};
60
61    use rstm_core::{Head, Tail};
62    use rstm_state::RawState;
63    use std::collections::HashMap;
64
65    impl<K, V> RawSpace for HashMap<K, V> {
66        seal! {}
67    }
68
69    impl<Q, A> RuleSpace<Q, A> for HashMap<Head<Q, A>, Tail<Q, A>>
70    where
71        Q: RawState + Eq + core::hash::Hash,
72        A: Eq + core::hash::Hash,
73    {
74        fn get(&self, key: &Head<Q, A>) -> Option<&Tail<Q, A>> {
75            self.get(key)
76        }
77    }
78}