Skip to main content

scon/
value.rs

1use std::fmt;
2
3use indexmap::IndexMap;
4
5use crate::error::{Error, ErrorCode, Result};
6
7#[derive(Clone, Copy, Debug, PartialEq)]
8pub enum Number {
9    I64(i64),
10    U64(u64),
11    F64(f64),
12}
13
14impl Number {
15    pub fn from_i64(value: i64) -> Self {
16        Self::I64(value)
17    }
18
19    pub fn from_u64(value: u64) -> Self {
20        Self::U64(value)
21    }
22
23    pub fn from_f64(value: f64) -> Option<Self> {
24        value.is_finite().then_some(Self::F64(value))
25    }
26
27    pub fn parse(text: &str) -> Result<Self> {
28        if text.contains(['.', 'e', 'E']) {
29            let value = text
30                .parse::<f64>()
31                .map_err(|err| invalid_number(format!("invalid float literal `{text}`: {err}")))?;
32            return Self::from_f64(value)
33                .ok_or_else(|| invalid_number(format!("non-finite float literal `{text}`")));
34        }
35
36        if text == "-0" {
37            Err(invalid_number(
38                "integer negative zero is invalid".to_string(),
39            ))
40        } else if text.starts_with('-') {
41            text.parse::<i64>()
42                .map(Self::I64)
43                .map_err(|err| invalid_number(format!("invalid signed integer `{text}`: {err}")))
44        } else {
45            text.parse::<u64>()
46                .map(Self::U64)
47                .map_err(|err| invalid_number(format!("invalid unsigned integer `{text}`: {err}")))
48        }
49    }
50
51    pub fn is_i64(&self) -> bool {
52        matches!(self, Self::I64(_))
53    }
54
55    pub fn is_u64(&self) -> bool {
56        matches!(self, Self::U64(_))
57    }
58
59    pub fn is_f64(&self) -> bool {
60        matches!(self, Self::F64(_))
61    }
62
63    pub fn as_i64(&self) -> Option<i64> {
64        match self {
65            Self::I64(value) => Some(*value),
66            Self::U64(value) => (*value).try_into().ok(),
67            Self::F64(_) => None,
68        }
69    }
70
71    pub fn as_u64(&self) -> Option<u64> {
72        match self {
73            Self::I64(value) => (*value).try_into().ok(),
74            Self::U64(value) => Some(*value),
75            Self::F64(_) => None,
76        }
77    }
78
79    pub fn as_f64(&self) -> Option<f64> {
80        match self {
81            Self::I64(value) => Some(*value as f64),
82            Self::U64(value) => Some(*value as f64),
83            Self::F64(value) => Some(*value),
84        }
85    }
86}
87
88impl fmt::Display for Number {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match self {
91            Self::I64(value) => write!(f, "{value}"),
92            Self::U64(value) => write!(f, "{value}"),
93            Self::F64(value) => f.write_str(&canonical_f64_text(*value)),
94        }
95    }
96}
97
98fn canonical_f64_text(value: f64) -> String {
99    if value == 0.0 {
100        return if value.is_sign_negative() {
101            "-0.0".to_string()
102        } else {
103            "0.0".to_string()
104        };
105    }
106
107    normalize_shortest_decimal(&value.to_string())
108}
109
110fn normalize_shortest_decimal(text: &str) -> String {
111    let (negative, unsigned) = text
112        .strip_prefix('-')
113        .map_or((false, text), |rest| (true, rest));
114    let exponent_at = unsigned.find(['e', 'E']);
115    let (significand, explicit_exponent) = exponent_at.map_or((unsigned, 0i32), |index| {
116        (
117            &unsigned[..index],
118            unsigned[index + 1..]
119                .parse::<i32>()
120                .expect("native f64 exponent is valid"),
121        )
122    });
123    let point_at = significand.find('.');
124    let integer_digits = point_at.unwrap_or(significand.len());
125    let mut digits = significand.replace('.', "");
126    let mut decimal_position = integer_digits as i32 + explicit_exponent;
127
128    let leading_zeroes = digits.bytes().take_while(|byte| *byte == b'0').count();
129    if leading_zeroes == digits.len() {
130        return if negative { "-0.0" } else { "0.0" }.to_string();
131    }
132    digits.drain(..leading_zeroes);
133    decimal_position -= leading_zeroes as i32;
134    while digits.len() > 1 && digits.ends_with('0') {
135        digits.pop();
136    }
137
138    let scientific_exponent = decimal_position - 1;
139    let mut out = String::new();
140    if negative {
141        out.push('-');
142    }
143    if (-6..=20).contains(&scientific_exponent) {
144        if decimal_position <= 0 {
145            out.push_str("0.");
146            out.push_str(&"0".repeat((-decimal_position) as usize));
147            out.push_str(&digits);
148        } else if decimal_position as usize >= digits.len() {
149            out.push_str(&digits);
150            out.push_str(&"0".repeat(decimal_position as usize - digits.len()));
151            out.push_str(".0");
152        } else {
153            let point = decimal_position as usize;
154            out.push_str(&digits[..point]);
155            out.push('.');
156            out.push_str(&digits[point..]);
157        }
158    } else {
159        out.push(digits.as_bytes()[0] as char);
160        if digits.len() > 1 {
161            out.push('.');
162            out.push_str(&digits[1..]);
163        }
164        out.push('e');
165        if scientific_exponent >= 0 {
166            out.push('+');
167        }
168        out.push_str(&scientific_exponent.to_string());
169    }
170    out
171}
172
173fn invalid_number(message: String) -> Error {
174    Error::new(ErrorCode::InvalidNumber, message)
175}
176
177#[derive(Clone, Debug, PartialEq)]
178pub enum Value {
179    Null,
180    Bool(bool),
181    Number(Number),
182    String(String),
183    Array(Vec<Value>),
184    Object(IndexMap<String, Value>),
185}