scon-core 0.1.0

Strict, deterministic configuration parsing and Serde support for SCON
Documentation
use std::fmt;

use indexmap::IndexMap;

use crate::error::{Error, ErrorCode, Result};

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Number {
    I64(i64),
    U64(u64),
    F64(f64),
}

impl Number {
    pub fn from_i64(value: i64) -> Self {
        Self::I64(value)
    }

    pub fn from_u64(value: u64) -> Self {
        Self::U64(value)
    }

    pub fn from_f64(value: f64) -> Option<Self> {
        value.is_finite().then_some(Self::F64(value))
    }

    pub fn parse(text: &str) -> Result<Self> {
        if text.contains(['.', 'e', 'E']) {
            let value = text
                .parse::<f64>()
                .map_err(|err| invalid_number(format!("invalid float literal `{text}`: {err}")))?;
            return Self::from_f64(value)
                .ok_or_else(|| invalid_number(format!("non-finite float literal `{text}`")));
        }

        if text == "-0" {
            Err(invalid_number(
                "integer negative zero is invalid".to_string(),
            ))
        } else if text.starts_with('-') {
            text.parse::<i64>()
                .map(Self::I64)
                .map_err(|err| invalid_number(format!("invalid signed integer `{text}`: {err}")))
        } else {
            text.parse::<u64>()
                .map(Self::U64)
                .map_err(|err| invalid_number(format!("invalid unsigned integer `{text}`: {err}")))
        }
    }

    pub fn is_i64(&self) -> bool {
        matches!(self, Self::I64(_))
    }

    pub fn is_u64(&self) -> bool {
        matches!(self, Self::U64(_))
    }

    pub fn is_f64(&self) -> bool {
        matches!(self, Self::F64(_))
    }

    pub fn as_i64(&self) -> Option<i64> {
        match self {
            Self::I64(value) => Some(*value),
            Self::U64(value) => (*value).try_into().ok(),
            Self::F64(_) => None,
        }
    }

    pub fn as_u64(&self) -> Option<u64> {
        match self {
            Self::I64(value) => (*value).try_into().ok(),
            Self::U64(value) => Some(*value),
            Self::F64(_) => None,
        }
    }

    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Self::I64(value) => Some(*value as f64),
            Self::U64(value) => Some(*value as f64),
            Self::F64(value) => Some(*value),
        }
    }
}

impl fmt::Display for Number {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::I64(value) => write!(f, "{value}"),
            Self::U64(value) => write!(f, "{value}"),
            Self::F64(value) => f.write_str(&canonical_f64_text(*value)),
        }
    }
}

fn canonical_f64_text(value: f64) -> String {
    if value == 0.0 {
        return if value.is_sign_negative() {
            "-0.0".to_string()
        } else {
            "0.0".to_string()
        };
    }

    normalize_shortest_decimal(&value.to_string())
}

fn normalize_shortest_decimal(text: &str) -> String {
    let (negative, unsigned) = text
        .strip_prefix('-')
        .map_or((false, text), |rest| (true, rest));
    let exponent_at = unsigned.find(['e', 'E']);
    let (significand, explicit_exponent) = exponent_at.map_or((unsigned, 0i32), |index| {
        (
            &unsigned[..index],
            unsigned[index + 1..]
                .parse::<i32>()
                .expect("native f64 exponent is valid"),
        )
    });
    let point_at = significand.find('.');
    let integer_digits = point_at.unwrap_or(significand.len());
    let mut digits = significand.replace('.', "");
    let mut decimal_position = integer_digits as i32 + explicit_exponent;

    let leading_zeroes = digits.bytes().take_while(|byte| *byte == b'0').count();
    if leading_zeroes == digits.len() {
        return if negative { "-0.0" } else { "0.0" }.to_string();
    }
    digits.drain(..leading_zeroes);
    decimal_position -= leading_zeroes as i32;
    while digits.len() > 1 && digits.ends_with('0') {
        digits.pop();
    }

    let scientific_exponent = decimal_position - 1;
    let mut out = String::new();
    if negative {
        out.push('-');
    }
    if (-6..=20).contains(&scientific_exponent) {
        if decimal_position <= 0 {
            out.push_str("0.");
            out.push_str(&"0".repeat((-decimal_position) as usize));
            out.push_str(&digits);
        } else if decimal_position as usize >= digits.len() {
            out.push_str(&digits);
            out.push_str(&"0".repeat(decimal_position as usize - digits.len()));
            out.push_str(".0");
        } else {
            let point = decimal_position as usize;
            out.push_str(&digits[..point]);
            out.push('.');
            out.push_str(&digits[point..]);
        }
    } else {
        out.push(digits.as_bytes()[0] as char);
        if digits.len() > 1 {
            out.push('.');
            out.push_str(&digits[1..]);
        }
        out.push('e');
        if scientific_exponent >= 0 {
            out.push('+');
        }
        out.push_str(&scientific_exponent.to_string());
    }
    out
}

fn invalid_number(message: String) -> Error {
    Error::new(ErrorCode::InvalidNumber, message)
}

#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    Null,
    Bool(bool),
    Number(Number),
    String(String),
    Array(Vec<Value>),
    Object(IndexMap<String, Value>),
}