Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add intrinsics for numeric parsing #89

Merged
merged 6 commits into from
Nov 23, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion crates/jrsonnet-stdlib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@ pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {
("asciiUpper", builtin_ascii_upper::INST),
("asciiLower", builtin_ascii_lower::INST),
("findSubstr", builtin_find_substr::INST),
("parseInt", builtin_parse_int::INST),
("parseOctal", builtin_parse_octal::INST),
("parseHex", builtin_parse_hex::INST),
// Misc
("length", builtin_length::INST),
("startsWith", builtin_starts_with::INST),
Expand Down Expand Up @@ -312,7 +315,7 @@ impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {
out.build()
}
#[cfg(feature = "legacy-this-file")]
fn initialize(&self, s: State, source: Source) -> jrsonnet_evaluator::Context {
fn initialize(&self, s: State, source: Source) -> Context {
let mut builder = ObjValueBuilder::new();
builder.with_super(self.stdlib_obj.clone());
builder
Expand Down
88 changes: 88 additions & 0 deletions crates/jrsonnet-stdlib/src/strings.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use jrsonnet_evaluator::{
error::{ErrorKind::*, Result},
function::builtin,
throw,
typed::{Either2, VecVal, M1},
val::ArrValue,
Either, IStr, Val,
Expand Down Expand Up @@ -73,3 +74,90 @@ pub fn builtin_find_substr(pat: IStr, str: IStr) -> Result<ArrValue> {
}
Ok(out.into())
}

#[builtin]
pub fn builtin_parse_int(raw: IStr) -> Result<f64> {
if let Some(raw) = raw.strip_prefix('-') {
if raw.is_empty() {
throw!("integer only consists of a minus")
}

parse_nat::<10>(raw).map(|value| -value)
} else {
if raw.is_empty() {
throw!("empty integer")
}

parse_nat::<10>(raw.as_str())
}
}

#[builtin]
pub fn builtin_parse_octal(raw: IStr) -> Result<f64> {
if raw.is_empty() {
throw!("empty octal integer");
}

parse_nat::<8>(raw.as_str())
}

#[builtin]
pub fn builtin_parse_hex(raw: IStr) -> Result<f64> {
if raw.is_empty() {
throw!("empty hexadecimal integer");
}

parse_nat::<16>(raw.as_str())
}

fn parse_nat<const BASE: u32>(raw: &str) -> Result<f64> {
debug_assert!(
1 <= BASE && BASE <= 16,
"integer base should be between 1 and 16"
);

const ZERO_CODE: u32 = '0' as u32;
const UPPER_A_CODE: u32 = 'A' as u32;
const LOWER_A_CODE: u32 = 'a' as u32;

#[inline]
fn checked_sub_if(condition: bool, lhs: u32, rhs: u32) -> Option<u32> {
if condition {
lhs.checked_sub(rhs)
} else {
None
}
}

let base = BASE as f64;

raw.chars().try_fold(0f64, |aggregate, digit| {
let digit = digit as u32;
let digit = if let Some(digit) = checked_sub_if(BASE > 10, digit, LOWER_A_CODE) {
digit + 10
} else if let Some(digit) = checked_sub_if(BASE > 10, digit, UPPER_A_CODE) {
digit + 10
} else {
digit.checked_sub(ZERO_CODE).unwrap_or(BASE)
};

if digit < BASE {
Ok(base * aggregate + digit as f64)
} else {
throw!("{raw:?} is not a base {BASE} integer",);
}
})
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn parse_nat_base_10() {
assert_eq!(parse_nat::<10>("0").unwrap(), 0.);
assert_eq!(parse_nat::<10>("3").unwrap(), 3.);
assert_eq!(parse_nat::<10>("27").unwrap(), 10. * 2. + 7.);
assert_eq!(parse_nat::<10>("123").unwrap(), 10. * (10. * 1. + 2.) + 3.);
JarvisCraft marked this conversation as resolved.
Show resolved Hide resolved
}
}