Skip to main content

euv_core/scene/selection/
impl.rs

1use super::*;
2
3/// Character-range queries and text extraction helpers for `SelectionState`.
4impl SelectionState {
5    /// Returns the normalized `(start_char, end_char)` range with `start_char <= end_char`.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Selection state reference.
10    ///
11    /// # Returns
12    ///
13    /// - `(usize, usize)` - Ordered character index bounds.
14    #[must_use]
15    #[inline(always)]
16    pub const fn ordered_range(&self) -> (usize, usize) {
17        let Self {
18            anchor_char,
19            focus_char,
20            ..
21        } = *self;
22        if anchor_char <= focus_char {
23            (anchor_char, focus_char)
24        } else {
25            (focus_char, anchor_char)
26        }
27    }
28
29    /// Returns `true` when the selection is collapsed (zero selected characters).
30    ///
31    /// # Arguments
32    ///
33    /// - `&Self` - Selection state reference.
34    ///
35    /// # Returns
36    ///
37    /// - `bool` - Whether `anchor_char == focus_char`.
38    #[must_use]
39    #[inline(always)]
40    pub const fn is_empty(&self) -> bool {
41        let Self {
42            anchor_char,
43            focus_char,
44            ..
45        } = *self;
46        anchor_char == focus_char
47    }
48
49    /// Extracts the selected UTF-8 slice from `text`, safely clamping to valid character boundaries.
50    ///
51    /// # Arguments
52    ///
53    /// - `&Self` - Selection state reference.
54    /// - `&'a str` - Source UTF-8 text string of the selected node.
55    ///
56    /// # Returns
57    ///
58    /// - `&'a str` - Selected substring slice (empty when collapsed).
59    #[must_use]
60    pub fn extract_from<'a>(&self, text: &'a str) -> &'a str {
61        let (start_char, end_char): (usize, usize) = self.ordered_range();
62        if start_char >= end_char || text.is_empty() {
63            return "";
64        }
65        let mut start_byte: usize = text.len();
66        let mut end_byte: usize = text.len();
67        for (char_idx, (byte_idx, _)) in text.char_indices().enumerate() {
68            if char_idx == start_char {
69                start_byte = byte_idx;
70            }
71            if char_idx == end_char {
72                end_byte = byte_idx;
73                break;
74            }
75        }
76        if start_byte >= end_byte {
77            ""
78        } else {
79            &text[start_byte..end_byte]
80        }
81    }
82}