Skip to content

Commit d61f70f

Browse files
clubby789tormol
authored andcommitted
Change example to remove UB
The example creates a new `AsciiString::from_raw_parts` using a shared reference casted to a mutable pointer. This changes the example to use an exclusive reference/pointer.
1 parent a6f9372 commit d61f70f

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

src/ascii_string.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ impl AsciiString {
6565
///
6666
/// * The memory at `buf` need to have been previously allocated by the same allocator this
6767
/// library uses.
68+
/// * `buf` must be obtained from a valid `&mut` reference to guarentee exclusive ownership.
6869
/// * `length` needs to be less than or equal to `capacity`.
6970
/// * `capacity` needs to be the correct value.
7071
/// * `buf` must have `length` valid ascii elements and contain a total of `capacity` total,
@@ -81,14 +82,14 @@ impl AsciiString {
8182
/// use std::mem;
8283
///
8384
/// unsafe {
84-
/// let s = AsciiString::from_ascii("hello").unwrap();
85-
/// let ptr = s.as_ptr();
85+
/// let mut s = AsciiString::from_ascii("hello").unwrap();
86+
/// let ptr = s.as_mut_ptr();
8687
/// let len = s.len();
8788
/// let capacity = s.capacity();
8889
///
8990
/// mem::forget(s);
9091
///
91-
/// let s = AsciiString::from_raw_parts(ptr as *mut _, len, capacity);
92+
/// let s = AsciiString::from_raw_parts(ptr, len, capacity);
9293
///
9394
/// assert_eq!(AsciiString::from_ascii("hello").unwrap(), s);
9495
/// }
@@ -98,8 +99,8 @@ impl AsciiString {
9899
pub unsafe fn from_raw_parts(buf: *mut AsciiChar, length: usize, capacity: usize) -> Self {
99100
AsciiString {
100101
// SAFETY: Caller guarantees `buf` was previously allocated by this library,
101-
// that `buf` contains `length` valid ascii elements and has a total
102-
// capacity of `capacity` elements.
102+
// is a unique pointer, `buf` contains `length` valid ascii elements,
103+
// and has a total capacity of `capacity` elements.
103104
vec: unsafe { Vec::from_raw_parts(buf, length, capacity) },
104105
}
105106
}

0 commit comments

Comments
 (0)