aboutsummaryrefslogtreecommitdiff
path: root/azalea-brigadier/src/suggestion/mod.rs
blob: 592c674cbc777b326abe5ed0168177fc5b69c187 (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
mod suggestions;

use crate::context::StringRange;
#[cfg(feature = "azalea-buf")]
use azalea_buf::McBufWritable;
#[cfg(feature = "azalea-buf")]
use azalea_chat::FormattedText;
#[cfg(feature = "azalea-buf")]
use std::io::Write;
pub use suggestions::*;

/// A suggestion given to the user for what they might want to type next.
///
/// The `M` generic is the type of the tooltip, so for example a `String` or
/// just `()` if you don't care about it.
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct Suggestion<M = String> {
    pub text: String,
    pub range: StringRange,
    pub tooltip: Option<M>,
}

impl<M: Clone> Suggestion<M> {
    pub fn apply(&self, input: &str) -> String {
        if self.range.start() == 0 && self.range.end() == input.len() {
            return input.to_string();
        }
        let mut result = String::with_capacity(self.text.len());
        if self.range.start() > 0 {
            result.push_str(&input[0..self.range.start()]);
        }
        result.push_str(&self.text);
        if self.range.end() < input.len() {
            result.push_str(&input[self.range.end()..]);
        }

        result
    }

    pub fn expand(&self, command: &str, range: &StringRange) -> Suggestion<M> {
        if range == &self.range {
            return self.clone();
        }
        let mut result = String::new();
        if range.start() < self.range.start() {
            result.push_str(&command[range.start()..self.range.start()]);
        }
        result.push_str(&self.text);
        if range.end() > self.range.end() {
            result.push_str(&command[self.range.end()..range.end()]);
        }
        Suggestion {
            range: range.clone(),
            text: result,
            tooltip: self.tooltip.clone(),
        }
    }
}

#[cfg(feature = "azalea-buf")]
impl McBufWritable for Suggestion<FormattedText> {
    fn write_into(&self, buf: &mut impl Write) -> Result<(), std::io::Error> {
        self.text.write_into(buf)?;
        self.tooltip.write_into(buf)?;
        Ok(())
    }
}