aboutsummaryrefslogtreecommitdiff
path: root/rprt-engine/src/selection_functions/result_transformation.rs
blob: b437afdd8eaca1d172b7308031a1a116df9c2d37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use crate::{
    buffer::BufferID,
    selection::{Interval, Selection, Vectorisable},
    selection_functions::types::SelectionFunctionError,
    state::EditorState,
};

struct Complement;

impl Vectorisable<(), SelectionFunctionError> for Complement {
    fn rank0(
        &self,
        _param: &(),
        es: &EditorState,
        buffer_id: BufferID,
        pos: usize,
    ) -> Result<Selection, SelectionFunctionError> {
        if let Some(buf) = es.get_buffer(buffer_id) {
            let mut ranges = Vec::new();
            if pos > 0 {
                ranges.push(Interval::new(0, pos));
            }
            let max_pos = buf.max_pos();
            if pos + 1 < max_pos {
                ranges.push(Interval::new(pos + 1, max_pos));
            }
            Ok(Selection::Vectors { buffer_id, ranges })
        } else {
            Err(SelectionFunctionError::BufferNotFound(buffer_id))
        }
    }

    fn rank1(
        &self,
        _param: &(),
        es: &EditorState,
        buffer_id: BufferID,
        interval: &Interval,
    ) -> Result<Selection, SelectionFunctionError> {
        if let Some(buf) = es.get_buffer(buffer_id) {
            let max_pos = buf.max_pos();
            if interval.start == 0 && interval.end >= max_pos {
                return Ok(Selection::empty());
            }

            let mut ranges = Vec::new();
            if interval.start == 0 {
                if interval.end < max_pos {
                    ranges.push(Interval::new(interval.end, max_pos));
                }
            } else if interval.end == max_pos {
                ranges.push(Interval::new(0, interval.start));
            } else {
                ranges.push(Interval::new(0, interval.start));
                ranges.push(Interval::new(interval.end, max_pos));
            }
            Ok(Selection::Vectors { buffer_id, ranges })
        } else {
            Err(SelectionFunctionError::BufferNotFound(buffer_id))
        }
    }
}

pub fn complement_transform(
    es: &EditorState,
    result: Selection,
) -> Result<Selection, SelectionFunctionError> {
    Complement.vectorise(&(), es, &result)
}

pub fn conditional_transform(
    mut result: Selection,
    left: Option<&Selection>,
) -> Result<Selection, SelectionFunctionError> {
    if !result.is_empty() {
        Ok(left.cloned().unwrap_or_else(Selection::empty))
    } else {
        Ok(result)
    }
}