Skip to main content

tilo_actions/tree/
cursor.rs

1//! Where a listing goes on from: the cursor handed out with one page of a
2//! level, which reads the next from the directory page it starts in.
3
4use super::PageMark;
5
6/// How a resume mark with no source cursor is written: the page a level started in when it
7/// was read from the directory's start, which is asked for with no cursor.
8const NO_CURSOR: &str = "~";
9
10/// A cursor a listing issues: how many entries the listing is past, and,
11/// for a resource's listing, the directory page the next one starts in and
12/// how many resources that page holds before it, so the next page reads
13/// from there instead of every page before it. Written
14/// `<offset>` or `<offset>.<skip>.<revision hex>.<cursor hex>[.<after hex>]`,
15/// the cursor hex being `~` when the page is the directory's start.
16#[derive(Debug, PartialEq, Eq)]
17pub struct LsCursor {
18    /// Entries the listing is past.
19    pub offset: usize,
20    /// The directory page the next entry starts in, and how many resources
21    /// that page holds before it.
22    pub resume: Option<(PageMark, usize)>,
23    /// The resource the page before ended at, where the next page resumes in a directory:
24    /// read on from the same row once the directory moved on, a page that finds it again
25    /// starts after it, so what writes put before it never lists a resource twice.
26    pub after: Option<String>,
27}
28
29impl LsCursor {
30    /// The cursor `text` writes ([`Self::write`]); `None` for one it does not.
31    #[must_use]
32    pub fn parse(text: &str) -> Option<Self> {
33        let mut parts = text.split('.');
34        let offset = parts.next()?.parse().ok()?;
35        let Some(skip) = parts.next() else {
36            return Some(Self {
37                offset,
38                resume: None,
39                after: None,
40            });
41        };
42        let skip = skip.parse().ok()?;
43        let revision = String::from_utf8(hex::decode(parts.next()?).ok()?).ok()?;
44        let cursor = match parts.next()? {
45            NO_CURSOR => Vec::new(),
46            written => {
47                let cursor = hex::decode(written).ok()?;
48                if cursor.is_empty() {
49                    return None;
50                }
51                cursor
52            }
53        };
54        let after = match parts.next() {
55            Some(after) => Some(String::from_utf8(hex::decode(after).ok()?).ok()?),
56            None => None,
57        };
58        if parts.next().is_some() {
59            return None;
60        }
61        Some(Self {
62            offset,
63            resume: Some((
64                PageMark {
65                    row: 0,
66                    cursor,
67                    revision,
68                },
69                skip,
70            )),
71            after,
72        })
73    }
74
75    /// The cursor as it is handed out.
76    #[must_use]
77    pub fn write(&self) -> String {
78        match &self.resume {
79            None => self.offset.to_string(),
80            Some((mark, skip)) => {
81                let cursor = if mark.cursor.is_empty() {
82                    NO_CURSOR.to_owned()
83                } else {
84                    hex::encode(&mark.cursor)
85                };
86                let mut written = format!(
87                    "{}.{skip}.{}.{cursor}",
88                    self.offset,
89                    hex::encode(mark.revision.as_bytes()),
90                );
91                if let Some(after) = &self.after {
92                    written.push('.');
93                    written.push_str(&hex::encode(after.as_bytes()));
94                }
95                written
96            }
97        }
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::{LsCursor, PageMark};
104
105    /// A page of the directory's start carries no source cursor, and is written and read back
106    /// as that page: its revision names it, and the skip how far into it the next entry is.
107    #[test]
108    fn a_cursor_naming_the_directorys_start_round_trips() {
109        let cursor = LsCursor {
110            offset: 7,
111            resume: Some((
112                PageMark {
113                    row: 0,
114                    cursor: Vec::new(),
115                    revision: "rev-1".to_owned(),
116                },
117                7,
118            )),
119            after: Some("message 6".to_owned()),
120        };
121        assert_eq!(LsCursor::parse(&cursor.write()), Some(cursor));
122    }
123
124    /// The one resume mark with no cursor is the one this writes `~`: an empty cursor field
125    /// names no page, and is refused with the other cursors this host did not write.
126    #[test]
127    fn an_empty_cursor_field_is_not_a_continuation() {
128        assert_eq!(LsCursor::parse("7.7.7265762d31."), None);
129    }
130}