A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://doc.rust-lang.org/std/ptr/fn.write_bytes.html below:

write_bytes in std::ptr - Rust

Function write_bytes1.0.0 (const: 1.83.0) · Source
pub const unsafe fn write_bytes<T>(dst: *mut T, val: u8, count: usize)
Expand description

Sets count * size_of::<T>() bytes of memory starting at dst to val.

write_bytes is similar to C’s memset, but sets count * size_of::<T>() bytes to val.

§Safety

Behavior is undefined if any of the following conditions are violated:

Note that even if the effectively copied size (count * size_of::<T>()) is 0, the pointer must be properly aligned.

Additionally, note that changing *dst in this way can easily lead to undefined behavior (UB) later if the written bytes are not a valid representation of some T. For instance, the following is an incorrect use of this function:

unsafe {
    let mut value: u8 = 0;
    let ptr: *mut bool = &mut value as *mut u8 as *mut bool;
    let _bool = ptr.read(); ptr.write_bytes(42u8, 1); let _bool = ptr.read(); }
§Examples

Basic usage:

use std::ptr;

let mut vec = vec![0u32; 4];
unsafe {
    let vec_ptr = vec.as_mut_ptr();
    ptr::write_bytes(vec_ptr, 0xfe, 2);
}
assert_eq!(vec, [0xfefefefe, 0xfefefefe, 0, 0]);

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4