feat(Str.toNum): support decimal

This commit is contained in:
rvcas 2021-12-02 15:35:34 -05:00
parent d8a3a961bf
commit bc5b1abcba
5 changed files with 34 additions and 1 deletions

View file

@ -1,5 +1,6 @@
const std = @import("std");
const str = @import("str.zig");
const num_ = @import("num.zig");
const utils = @import("utils.zig");
const math = std.math;
@ -1052,6 +1053,14 @@ test "div: 10 / 3" {
// exports
pub fn fromStr(arg: RocStr) callconv(.C) num_.NumParseResult(i128) {
if (@call(.{ .modifier = always_inline }, RocDec.fromStr, .{arg})) |dec| {
return .{ .errorcode = 0, .value = dec.num };
} else {
return .{ .errorcode = 1, .value = 0 };
}
}
pub fn fromF64C(arg: f64) callconv(.C) i128 {
return if (@call(.{ .modifier = always_inline }, RocDec.fromF64, .{arg})) |dec| dec.num else @panic("TODO runtime exception failing convert f64 to RocDec");
}

View file

@ -10,6 +10,7 @@ const STR = "str";
const dec = @import("dec.zig");
comptime {
exportDecFn(dec.fromStr, "from_str");
exportDecFn(dec.fromF64C, "from_f64");
exportDecFn(dec.eqC, "eq");
exportDecFn(dec.neqC, "neq");

View file

@ -302,6 +302,7 @@ pub const LIST_ANY: &str = "roc_builtins.list.any";
pub const LIST_ALL: &str = "roc_builtins.list.all";
pub const LIST_FIND_UNSAFE: &str = "roc_builtins.list.find_unsafe";
pub const DEC_FROM_STR: &str = "roc_builtins.dec.from_str";
pub const DEC_FROM_F64: &str = "roc_builtins.dec.from_f64";
pub const DEC_EQ: &str = "roc_builtins.dec.eq";
pub const DEC_NEQ: &str = "roc_builtins.dec.neq";

View file

@ -5281,7 +5281,7 @@ fn run_low_level<'a, 'ctx, 'env>(
Layout::Builtin(Builtin::Float(float_width)) => {
&bitcode::STR_TO_FLOAT[float_width]
}
Layout::Builtin(Builtin::Decimal) => bitcode::STR_TO_DECIMAL,
Layout::Builtin(Builtin::Decimal) => bitcode::DEC_FROM_STR,
_ => unreachable!(),
};

View file

@ -1331,3 +1331,25 @@ fn str_to_num_float() {
f64
);
}
#[test]
#[cfg(any(feature = "gen-llvm"))]
fn str_to_num_dec() {
use roc_std::RocDec;
assert_evals_to!(
indoc!(
r#"
x : Dec
x = 2.0
when Str.toNum "1.0" is
Ok n -> n + x
Err _ -> 0
"#
),
RocDec::from_str("3.0").unwrap(),
RocDec
);
}