Skip to content

std::slice::from_raw_buf is very unergonomic #20748

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

Closed
tomaka opened this issue Jan 8, 2015 · 4 comments
Closed

std::slice::from_raw_buf is very unergonomic #20748

tomaka opened this issue Jan 8, 2015 · 4 comments

Comments

@tomaka
Copy link
Contributor

tomaka commented Jan 8, 2015

The signature of from_raw_buf is:

fn from_raw_buf<T>(p: &'a *const T, len: uint) -> &'a [T]

The fact that the lifetime of the returned slice is the same as the lifetime of the pointer is a very bad idea. And now that CVec is gone, this is the only way to build a slice from a raw pointer.

I can see many potential problems, but the ones that I've encountered while removing CVec is that you can't cast your pointers, not even from mut to const: (http://is.gd/eW1KmQ)

struct Foo { data: *mut i8, len: uint }
impl Foo {
    fn as_slice(&self) -> &[i8] {
        unsafe {
            // value "self.data as *const i8" does not live long enough
            std::slice::from_raw_buf(&(self.data as *const i8), self.len)
        }
    }
}

And that you can't use raw pointers in iterators anymore: (http://is.gd/UsePsX)

struct Iter<'a> { data: *const u8, marker: ContravariantLifetime<'a> }
impl<'a> Iterator for Iter<'a> {
    type Item = &'a [u8];
    fn next(&mut self) -> Option<&'a [u8]> {
        Some(unsafe {
            // cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
            std::slice::from_raw_buf(&self.data, 1)
        })
    }
}

If I'm manipulating raw pointers which are unsafe by nature, please let me be unsafe!

The first example can be bypassed by using from_raw_mut_buf and casting the returned &mut [i8] to a &[i8], which means that the unsafe API is more restrictive than the safe API!

@lifthrasiir
Copy link
Contributor

Same issue with std::ffi::c_str_to_bytes[_with_nul].

@aturon
Copy link
Member

aturon commented Jan 8, 2015

Thanks for this feedback! I will look into making an improvement here ASAP.

cc @alexcrichton

@Gankra
Copy link
Contributor

Gankra commented Jan 8, 2015

Duplicate of #20031

@Gankra Gankra closed this as completed Jan 8, 2015
@aturon
Copy link
Member

aturon commented Jan 8, 2015

@gankro @tomaka can we cross-post the examples to the other issue, please?

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

4 participants