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
73
74
75
76
//! Element refs: the `ref_N` names `read_page` and `find` give a tab's
//! elements, which later calls pass back to act on one.
//!
//! A ref keeps its number for as long as the document that gave it does, so
//! a second read names an element as the first did. A new document starts
//! the numbering over: its node ids can repeat the old document's, since it
//! may render in a new process, so an old ref must not reach a new node.
use rho_browser::cdp::BackendNodeId;
use std::collections::HashMap;
/// One tab's refs, for the document its loader names.
#[derive(Debug, Default)]
pub(super) struct Refs {
loader: String,
numbers: HashMap<BackendNodeId, usize>,
/// The node of each ref, by its number less one.
nodes: Vec<BackendNodeId>,
}
/// A ref the tab's current document did not give.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct StaleRef(pub(super) String);
impl std::fmt::Display for StaleRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{} is stale or not found on the current page. Re-read the page to get fresh references.",
self.0
)
}
}
impl Refs {
/// Forgets every ref when the tab's document is no longer the one of
/// `loader`.
pub(super) fn follow(&mut self, loader: &str) {
if self.loader != loader {
*self = Self {
loader: loader.to_owned(),
..Self::default()
};
}
}
/// The ref of `node`, giving it the next number the first time.
pub(super) fn name(&mut self, node: BackendNodeId) -> String {
let number = *self.numbers.entry(node).or_insert_with(|| {
self.nodes.push(node);
self.nodes.len()
});
format!("ref_{number}")
}
/// The node `name`, such as `ref_3`, names in the document of `loader`.
pub(super) fn node(&self, name: &str, loader: &str) -> Result<BackendNodeId, StaleRef> {
let stale = || StaleRef(name.to_owned());
if self.loader != loader {
return Err(stale());
}
let number = name
.strip_prefix("ref_")
.and_then(|number| number.parse::<usize>().ok())
.ok_or_else(stale)?;
number
.checked_sub(1)
.and_then(|index| self.nodes.get(index))
.copied()
.ok_or_else(stale)
}
}
#[cfg(test)]
#[path = "refs_tests.rs"]
mod tests;