Skip to main content

cranpose_core/
recycled_node.rs

1use crate::{Node, NodeError, NodeId};
2
3/// Which recycle path a pooled node came from.
4#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5pub enum RecycleOrigin {
6    /// A node created fresh, or one kept from before the last pass.
7    #[default]
8    Cold,
9    /// A node kept warm from the last pass.
10    Warm,
11}
12
13/// A removed node kept in a pool with its old id, so that a later node of the same type can reuse
14/// it.
15pub struct RecycledNode {
16    stable_id: NodeId,
17    pub(crate) node: Box<dyn Node>,
18    origin: RecycleOrigin,
19}
20
21impl RecycledNode {
22    /// A removed node as a pool shell: the node cleared where it lies, so it
23    /// keeps its box and takes no new one.
24    pub(crate) fn new(stable_id: NodeId, mut node: Box<dyn Node>, origin: RecycleOrigin) -> Self {
25        node.prepare_for_recycle();
26        Self {
27            stable_id,
28            node,
29            origin,
30        }
31    }
32
33    pub(crate) fn from_shell(
34        stable_id: NodeId,
35        node: Box<dyn Node>,
36        origin: RecycleOrigin,
37    ) -> Self {
38        Self {
39            stable_id,
40            node,
41            origin,
42        }
43    }
44
45    /// Returns the id the node had before it was recycled.
46    pub fn stable_id(&self) -> NodeId {
47        self.stable_id
48    }
49
50    pub(crate) fn origin(&self) -> RecycleOrigin {
51        self.origin
52    }
53
54    pub(crate) fn set_origin(&mut self, origin: RecycleOrigin) {
55        self.origin = origin;
56    }
57
58    /// Returns the pooled node, so that it can be reset before reuse.
59    pub fn node_mut(&mut self) -> &mut dyn Node {
60        self.node.as_mut()
61    }
62
63    /// Splits the shell into its stable id, its node and the recycle path it came from.
64    pub fn into_parts(self) -> (NodeId, Box<dyn Node>, RecycleOrigin) {
65        (self.stable_id, self.node, self.origin)
66    }
67}
68
69/// The result of putting a recycled node back into an applier.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct RecycledNodeInsertion {
72    /// The id the node has now.
73    pub id: NodeId,
74    /// Whether the node got its old stable id back.
75    pub stable_id_reused: bool,
76    /// The error that forced a new id, or `None` if the old id was reused.
77    pub fallback_error: Option<NodeError>,
78}
79
80impl RecycledNodeInsertion {
81    pub(crate) fn reused(stable_id: NodeId) -> Self {
82        Self {
83            id: stable_id,
84            stable_id_reused: true,
85            fallback_error: None,
86        }
87    }
88
89    pub(crate) fn fresh(id: NodeId, fallback_error: Option<NodeError>) -> Self {
90        Self {
91            id,
92            stable_id_reused: false,
93            fallback_error,
94        }
95    }
96}