Skip to content

Commit

Permalink
implemented TextSelections.textual_order()
Browse files Browse the repository at this point in the history
  • Loading branch information
proycon committed Oct 14, 2023
1 parent bc0ef60 commit 16617e3
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/textselection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,32 @@ impl PyTextSelections {
iterparams.evaluate_to_pytextselections(iter, store, &self.store)
})
}

fn textual_order(mut pyself: PyRefMut<'_, Self>) -> PyRefMut<'_, Self> {
pyself
.map_mut(|textselections, store| {
textselections.sort_unstable_by(|(a_res, a_tsel), (b_res, b_tsel)| {
let resource = store.get(*a_res).expect("resource must exist");
let a = resource
.get(*a_tsel)
.unwrap()
.as_resultitem(resource, store);
let resource = if a_res == b_res {
resource
} else {
store.get(*b_res).expect("resource must exist")
};
let b = resource
.get(*b_tsel)
.unwrap()
.as_resultitem(resource, store);
a.cmp(&b)
});
Ok(())
})
.unwrap();
pyself
}
}

impl PyTextSelections {
Expand All @@ -547,6 +573,23 @@ impl PyTextSelections {
))
}
}

fn map_mut<T, F>(&mut self, f: F) -> Result<T, PyErr>
where
F: FnOnce(
&mut Vec<(TextResourceHandle, TextSelectionHandle)>,
&AnnotationStore,
) -> Result<T, StamError>,
{
if let Ok(store) = self.store.read() {
f(&mut self.textselections, &store)
.map_err(|err| PyStamError::new_err(format!("{}", err)))
} else {
Err(PyRuntimeError::new_err(
"Unable to obtain store (should never happen)",
))
}
}
}

impl<'py> IterParams<'py> {
Expand Down
6 changes: 6 additions & 0 deletions stam.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -780,6 +780,12 @@ class TextSelections:
See :meth:`Annotation.related_text` for allowed keyword arguments.
"""

def textual_order(self) -> TextSelections:
"""
Sorts the annotations in textual order.
This has some performance cost, so prevent calling this method on methods that already promise to return textual order (which most textselection methods do!)
"""

class Selector:
"""
Expand Down

0 comments on commit 16617e3

Please sign in to comment.