hyperast/position/
computing_path.rs

1//! Gather most of the common behaviors used to compute a path from an offset
2use num::ToPrimitive;
3
4use crate::types::{HyperAST, IterableChildren, NodeStore, WithChildren, WithSerialization};
5
6/// must be in a file
7pub fn resolve_range<'store, HAST>(
8    root: HAST::IdN,
9    start: usize,
10    end: Option<usize>,
11    stores: &'store HAST,
12) -> (HAST::IdN, Vec<usize>)
13where
14    HAST: HyperAST<'store>,
15    HAST::T: WithSerialization,
16    HAST::IdN: Copy,
17{
18    let mut offset = 0;
19    let mut x = root;
20    let mut offsets = vec![];
21    'main: loop {
22        let b = stores.node_store().resolve(&x);
23        if let Some(cs) = b.children() {
24            for (y, child_id) in cs.iter_children().enumerate() {
25                let b = stores.node_store().resolve(child_id);
26
27                let len = b.try_bytes_len().unwrap_or(0).to_usize().unwrap();
28                if offset + len < start {
29                    // not yet reached something
30                } else if end.map_or(true, |end| offset + len <= end) {
31                    break 'main;
32                } else {
33                    offsets.push(y);
34                    x = *child_id;
35                    break;
36                }
37                offset += len;
38            }
39        } else {
40            break;
41        }
42    }
43    (x, offsets)
44}