1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use crate::render::{
  hooks::{
    error::{Error, Result},
    Hook,
  },
  ComponentID,
};

/// Tracks hook usage within a render.
pub struct Cursor {
  pub component_id: ComponentID,

  hooks: Vec<Hook>,
  index: usize,

  writing: bool,
}

impl Cursor {
  /// Creates a reading [`Cursor`].
  pub fn read(component_id: ComponentID, hooks: Vec<Hook>) -> Self {
    Self {
      component_id,
      hooks,
      index: 0,

      writing: false,
    }
  }

  /// Creates a writing [`Cursor`].
  pub fn write(component_id: ComponentID) -> Self {
    Self {
      component_id,
      hooks: Vec::new(),
      index: 0,

      writing: true,
    }
  }

  /// Returns the next hook value, creating it using `f` if necessary.
  ///
  /// # Errors
  ///
  /// Will return an `Err` if type `T` is invalid, or if the cursor's index is invalid.
  pub fn next<F, T>(&mut self, f: F) -> Result<T>
  where
    F: FnOnce(ComponentID) -> Hook,
    T: 'static + Clone,
  {
    if self.writing {
      self.hooks.push(f(self.component_id));
    }

    let value = self.hooks.get(self.index).ok_or(Error::InvalidIndex(self.index))?.downcast_ref()?;

    self.index += 1;

    Ok(value)
  }

  /// Returns whether there is a next hook value.
  pub fn has_hook(&self) -> bool {
    !self.writing
  }

  /// Ends a cursor and returns its hooks.
  pub fn hooks(self) -> Vec<Hook> {
    self.hooks
  }
}