aboutsummaryrefslogtreecommitdiff
path: root/examples/statetracker/src/formatter.rs
blob: dc818879736c9c55be3423ce931da51215a71e69 (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
use druid::text::{Formatter, Validation, ValidationError};

pub struct U16Formatter;

impl Formatter<u16> for U16Formatter {
    fn format(&self, value: &u16) -> String {
        value.to_string()
    }

    fn validate_partial_input(&self, input: &str, _sel: &druid::text::Selection) -> Validation {
        if input.is_empty() {
            return Validation::success();
        }

        if input.len() > 6 {
            return Validation::failure(U16ValidationError::WrongNumberOfCharacters);
        }

        match input.parse::<u16>() {
            Ok(_) => Validation::success(),
            Err(err) => Validation::failure(err),
        }
    }

    fn value(&self, input: &str) -> Result<u16, ValidationError> {
        if input.is_empty() || input.len() > 5 {
            return Err(ValidationError::new(
                U16ValidationError::WrongNumberOfCharacters,
            ));
        }

        input.parse().map_err(|err| ValidationError::new(err))
    }
}

#[derive(Debug, Clone)]
pub enum U16ValidationError {
    WrongNumberOfCharacters,
}

impl std::fmt::Display for U16ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // TODO set correct display based on actual value
        write!(f, "U16ValidationError::WrongNumberOfCharacters")
    }
}

impl std::error::Error for U16ValidationError {}