Function std::ptr::write_bytes 1.0.0[−][src]
pub unsafe extern "rust-intrinsic" fn write_bytes<T>(
dst: *mut T,
val: u8,
count: usize
)
Sets count * size_of::<T>() bytes of memory starting at dst to
val.
write_bytes is semantically equivalent to C's memset.
Safety
Behavior is undefined if any of the following conditions are violated:
-
The region of memory which begins at
dstand has a length ofcountbytes must be valid. -
dstmust be properly aligned.
Additionally, the caller must ensure that writing count bytes to the
given region of memory results in a valid value of T. Creating an
invalid value of T can result in undefined behavior. An example is
provided below.
Examples
Basic usage:
use std::ptr; let mut vec = vec![0; 4]; unsafe { let vec_ptr = vec.as_mut_ptr(); ptr::write_bytes(vec_ptr, b'a', 2); } assert_eq!(vec, [b'a', b'a', 0, 0]);Run
Creating an invalid value:
use std::{mem, ptr}; let mut v = Box::new(0i32); unsafe { // Leaks the previously held value by overwriting the `Box<T>` with // a null pointer. ptr::write_bytes(&mut v, 0, mem::size_of::<Box<i32>>()); } // At this point, using or dropping `v` results in undefined behavior. // v = Box::new(0i32); // ERRORRun