Skip to main content

sb3_decoder/model/code/
value.rs

1use std::cmp::Ordering;
2
3/// A value in Scratch.
4///
5/// The [`PartialEq`] implementation for this enum is created with [`derive`], so it is not
6/// the same as the `<a = b>` block in Scratch which is case-insensitive and treats text that
7/// look like numbers as numbers. For that, you should use [`Value::scratch_eq`] which matches the
8/// equation implementation of Scratch. For `<a > b>` and `<a < b>` you should use
9/// [`Value::scratch_cmp`] which returns [`Ordering`].
10#[derive(Debug, Clone, PartialEq)]
11pub enum Value {
12    Number(f64),
13    Text(String),
14    Boolean(bool),
15}
16
17impl Value {
18    /// Compares a [`Value`] with another [`Value`] like how Scratch would.
19    pub fn scratch_cmp(&self, other: &Value) -> Ordering {
20        let (a, b) = (self.compare_number(), other.compare_number());
21        if a.is_nan() || b.is_nan() {
22            return self.compare_string().cmp(&other.compare_string());
23        }
24        a.partial_cmp(&b).unwrap()
25    }
26
27    /// Equates a [`Value`] with another [`Value`] like how Scratch would.
28    pub fn scratch_eq(&self, other: &Self) -> bool {
29        self.scratch_cmp(other) == Ordering::Equal
30    }
31
32    fn compare_number(&self) -> f64 {
33        match self {
34            Value::Number(n) => *n,
35            Value::Boolean(b) => f64::from(u8::from(*b)),
36            Value::Text(s) if s.trim().is_empty() => f64::NAN,
37            Value::Text(s) => parse_js_number(s),
38        }
39    }
40
41    fn compare_string(&self) -> String {
42        match self {
43            Value::Text(s) => s.to_lowercase(),
44            Value::Boolean(b) => b.to_string(),
45            Value::Number(n) => js_number_to_string(*n).to_lowercase(),
46        }
47    }
48}
49
50fn js_number_to_string(n: f64) -> String {
51    if n == 0.0 { "0".into() } else { n.to_string() }
52}
53
54fn parse_js_number(s: &str) -> f64 {
55    let s = s.trim();
56    if s.is_empty() {
57        return 0.0;
58    }
59
60    // no sign allowed, integers only for different bases
61    let radix = match s.get(..2) {
62        Some("0x" | "0X") => Some(16),
63        Some("0b" | "0B") => Some(2),
64        Some("0o" | "0O") => Some(8),
65        _ => None,
66    };
67    if let Some(radix) = radix {
68        return u64::from_str_radix(&s[2..], radix).map_or(f64::NAN, |n| n as f64);
69    }
70
71    match s {
72        "Infinity" | "+Infinity" => return f64::INFINITY,
73        "-Infinity" => return f64::NEG_INFINITY,
74        _ => {}
75    }
76
77    if !s
78        .bytes()
79        .all(|b| matches!(b, b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-'))
80    {
81        return f64::NAN;
82    }
83    s.parse().unwrap_or(f64::NAN)
84}