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

R floats are silently converted into Rust ints #101

Closed
clauswilke opened this issue Dec 28, 2020 · 2 comments
Closed

R floats are silently converted into Rust ints #101

clauswilke opened this issue Dec 28, 2020 · 2 comments

Comments

@clauswilke
Copy link
Member

clauswilke commented Dec 28, 2020

If a Rust function expecting an int is handed a float from R, then the float is silently converted to int, stripping any decimal values in the process. See e.g. here:

expect_equal(.Call(wrap__int_scalar, 4.4), 4L) # is this deliberate? seems dangerous

I think this should instead raise an "unable to convert" error. Silent conversion from float to int is dangerous.

@Ilia-Kosenkov
Copy link
Member

Just a summary of inconsistent conversion behavior. If i32 is expected, numeric is silently converted to i32.
On the other hand, when Option<i32> is expected, numeric become illegal and only pure integer (with literal L) are allowed, as well as NA.

rust_code <- "
#[extendr]
fn slice_test(v : &[i32], i : i32) -> i32 {
    v[i as usize]
}

#[extendr]
fn slice_test_na(v : &[i32], i : Option<i32>) -> Option<i32> {
    match i {
        Some (index) => Some(v[index as usize]),
        None => None
    }
}
"

rextendr::rust_source(code = rust_code)
#> build directory: C:\Users\[redacted]\AppData\Local\Temp\Rtmp2Z8D1v\filea087d24386d
# OK
slice_test(1:10, 1)
#> [1] 2
# Should not be OK
slice_test(1:10, 1.5)
#> [1] 2
# Not OK
slice_test(1:10, NA)
#> Error in slice_test(1:10, NA): unable to convert R object to primitive

# Should be OK but is not?
slice_test_na(1:10, 1)
#> Error in slice_test_na(1:10, 1): expected an integer scalar
# But this is
slice_test_na(1:10, 1L)
#> [1] 2
# This is correct
slice_test_na(1:10, 1.5)
#> Error in slice_test_na(1:10, 1.5): expected an integer scalar
# This is also correct
slice_test_na(1:10, NA)
#> [1] NA

Created on 2021-01-20 by the reprex package (v0.3.0)

@clauswilke clauswilke removed the good first issue Good for newcomers label Jan 31, 2021
@clauswilke
Copy link
Member Author

Removing the "good first issue" label as I think this is a complex and somewhat tricky topic. The problem is not the implementation but the correct conceptual design.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants