From 3eb3c97698ff69e72a720aaf5cdaa2e8ff2e5c39 Mon Sep 17 00:00:00 2001 From: Maarten van Gompel Date: Mon, 19 Feb 2024 22:42:27 +0100 Subject: [PATCH] implemented a better API to get a textselection of a whole resource, e.g. using From trait --- src/api/resources.rs | 29 +++++++++++++++++++++++++++++ src/api/textselection.rs | 6 ++++++ 2 files changed, 35 insertions(+) diff --git a/src/api/resources.rs b/src/api/resources.rs index 6f7bb5b..925d928 100644 --- a/src/api/resources.rs +++ b/src/api/resources.rs @@ -19,6 +19,7 @@ use crate::datakey::DataKey; use crate::datavalue::DataOperator; use crate::error::*; use crate::resources::{TextResource, TextResourceHandle}; +use crate::selector::Offset; use crate::store::*; use crate::textselection::{ResultTextSelection, TextSelectionOperator, TextSelectionSet}; use crate::{Filter, FilterMode}; @@ -80,6 +81,34 @@ impl<'store> ResultItem<'store, TextResource> { )) } + /// Get a text selection pointing to the whole resource, you can also call this implicitly via the `From` trait (`resource.into()`). + pub fn to_textselection(self) -> ResultTextSelection<'store> { + self.textselection_by_offset(&Offset::whole()) + .expect("to_textselection() should never fail") + } + + /// Return a textselection by offset + /// If you want the whole text as a ResultTextSelection, just use call `into()` instead. + pub fn textselection_by_offset( + &self, + offset: &Offset, + ) -> Result, StamError> { + let textselection = self.as_ref().textselection_by_offset(offset)?; + if let Some(handle) = textselection.handle() { + Ok(self + .as_ref() + .get(handle)? + .as_resultitem(self.as_ref(), self.store()) + .as_resulttextselection()) + } else { + Ok(ResultTextSelection::Unbound( + self.store(), + self.as_ref(), + textselection, + )) + } + } + /// Returns a sorted double-ended iterator over a range of all textselections and returns all /// textselections that either start or end in this range (depending on the direction you're /// iterating in) diff --git a/src/api/textselection.rs b/src/api/textselection.rs index 8f03980..363da28 100644 --- a/src/api/textselection.rs +++ b/src/api/textselection.rs @@ -1065,3 +1065,9 @@ where self.inner.next().map(|ts| ts.text()) } } + +impl<'store> From> for ResultTextSelection<'store> { + fn from(resource: ResultItem<'store, TextResource>) -> Self { + resource.to_textselection() + } +}