-
Notifications
You must be signed in to change notification settings - Fork 10
Closed
Description
Hi! I was just taking a look at this crate because it seems to be useful for a use-case I am having, where I want to read strings from a Bytes
buffer and have them share the underlying allocation.
What struck me is that some of the methods and impls on String
seem to be inherently unsafe, because they assume things about the sanity of impls on T
which can be easily violated using safe Rust.
As an example, here is a code snippet that leads to a str
which contains invalid utf-8 (playground).
extern crate string;
use std::cell::Cell;
struct Corruptor {
inner: Cell<&'static [u8]>
}
impl AsRef<[u8]> for Corruptor {
fn as_ref(&self) -> &[u8] {
self.inner.replace(b"\xc3\x28".as_ref())
}
}
fn main() {
let corruptor = Corruptor { inner: Cell::new(&[]) };
let string: string::String<Corruptor> = string::TryFrom::try_from(corruptor).unwrap();
println!("BOOM: {}", &*string)
}
There's a couple of ways I can think of how this could be fixed:
- One way to fix this would be to not provide any of the
Deref
andAsRef
impls, but that seems like it would defeat the purpose of this crate. - Another way to fix it would be to mark methods as unsafe where appropriate, and remove or specialize trait impls.
- A third way could be to introduce an
unsafe
marker trait (similar to what theowning_ref
crate does), that is used as a bound forT
to ensure that only "sane" implementations are used.
Here are all the ways to construct a String
that I believe to be currently unsafe:
impl<T> TryFrom<T> for String<T> where T: AsRef<[u8]>
(since 0.1.0)impl<T: Default> Default for String<T>
(since 0.1.0)pub fn from_str<'a>(src: &'a str) -> String<T> where T: From<&'a [u8]>
(since 0.1.2)
Let me know what you think!
Metadata
Metadata
Assignees
Labels
No labels