Skip to content

Commit 6ba462e

Browse files
samlichkorken89
authored andcommitted
String: add as_mut_vec
1 parent 0364e05 commit 6ba462e

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/string.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,34 @@ where
178178
unsafe { str::from_utf8_unchecked_mut(self.0.vec.as_mut_slice()) }
179179
}
180180

181+
/// Returns a mutable reference to the contents of this `String`.
182+
///
183+
/// # Safety
184+
///
185+
/// This function is unsafe because it does not check that the bytes passed
186+
/// to it are valid UTF-8. If this constraint is violated, it may cause
187+
/// memory unsafety issues with future users of the `String`, as the rest of
188+
/// the library assumes that `String`s are valid UTF-8.
189+
///
190+
/// # Examples
191+
///
192+
/// Basic usage:
193+
///
194+
/// ```
195+
/// let mut s = String::from("hello");
196+
///
197+
/// unsafe {
198+
/// let vec = s.as_mut_vec();
199+
/// assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);
200+
///
201+
/// vec.reverse();
202+
/// }
203+
/// assert_eq!(s, "olleh");
204+
/// ```
205+
pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8, N> {
206+
&mut *(&mut self.0.vec as *mut crate::i::Vec<GenericArray<u8, N>> as *mut Vec<u8, N>)
207+
}
208+
181209
/// Appends a given string slice onto the end of this `String`.
182210
///
183211
/// # Examples

src/vec.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,8 @@ where
160160
/// }
161161
/// assert_eq!(vec, [7, 1, 2, 3]);
162162
/// ```
163+
// repr(transparent) is needed for [`String::as_mut_vec`]
164+
#[repr(transparent)]
163165
pub struct Vec<T, N>(#[doc(hidden)] pub crate::i::Vec<GenericArray<T, N>>)
164166
where
165167
N: ArrayLength<T>;

0 commit comments

Comments
 (0)