本文簡要介紹rust語言中 Function std::intrinsics::copy_nonoverlapping
的用法。
用法
pub unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize)
副本count * size_of::<T>()
字節來自src
到dst
。源和目的地必須不是重疊。
對於可能重疊的內存區域,請改用 copy
。
copy_nonoverlapping
在語義上等同於 C 的 memcpy
,但交換了參數順序。
安全性
如果違反以下任何條件,則行為未定義:
-
對於讀取
count * size_of::<T>()
字節,src
必須是 valid。 -
對於
count * size_of::<T>()
字節的寫入,dst
必須是 valid。 -
src
和dst
都必須正確對齊。 -
內存區域開始於
src
大小為count * size_of::<T>()
字節必須不是與開始於的內存區域重疊dst
具有相同的尺寸。
就像std::ptr::read,copy_nonoverlapping
創建一個按位複製T
, 不管是否T
是std::marker::Copy.如果T
不是std::marker::Copy, 使用兩個都該區域中的值始於*src
和區域開始於*dst
能夠違反內存安全.
請注意,即使有效複製的大小 ( count * size_of::<T>()
) 是 0
,指針也必須非空且正確對齊。
例子
手動實現 Vec::append
:
use std::ptr;
/// Moves all the elements of `src` into `dst`, leaving `src` empty.
fn append<T>(dst: &mut Vec<T>, src: &mut Vec<T>) {
let src_len = src.len();
let dst_len = dst.len();
// Ensure that `dst` has enough capacity to hold all of `src`.
dst.reserve(src_len);
unsafe {
// The call to offset is always safe because `Vec` will never
// allocate more than `isize::MAX` bytes.
let dst_ptr = dst.as_mut_ptr().offset(dst_len as isize);
let src_ptr = src.as_ptr();
// Truncate `src` without dropping its contents. We do this first,
// to avoid problems in case something further down panics.
src.set_len(0);
// The two regions cannot overlap because mutable references do
// not alias, and two different vectors cannot own the same
// memory.
ptr::copy_nonoverlapping(src_ptr, dst_ptr, src_len);
// Notify `dst` that it now holds the contents of `src`.
dst.set_len(dst_len + src_len);
}
}
let mut a = vec!['r'];
let mut b = vec!['u', 's', 't'];
append(&mut a, &mut b);
assert_eq!(a, &['r', 'u', 's', 't']);
assert!(b.is_empty());
相關用法
- Rust copy用法及代碼示例
- Rust concat用法及代碼示例
- Rust compile_error用法及代碼示例
- Rust column用法及代碼示例
- Rust compiler_fence用法及代碼示例
- Rust concat_idents用法及代碼示例
- Rust char.is_control用法及代碼示例
- Rust char.is_alphanumeric用法及代碼示例
- Rust char.len_utf16用法及代碼示例
- Rust char.is_digit用法及代碼示例
- Rust char.is_ascii_graphic用法及代碼示例
- Rust char.decode_utf16用法及代碼示例
- Rust char.is_uppercase用法及代碼示例
- Rust catch_unwind用法及代碼示例
- Rust char.to_ascii_lowercase用法及代碼示例
- Rust char.is_ascii_uppercase用法及代碼示例
- Rust canonicalize用法及代碼示例
- Rust create_dir用法及代碼示例
- Rust ctlz用法及代碼示例
- Rust channel用法及代碼示例
- Rust char.escape_unicode用法及代碼示例
- Rust char.is_alphabetic用法及代碼示例
- Rust char.is_ascii_control用法及代碼示例
- Rust char.from_u32_unchecked用法及代碼示例
- Rust char.is_ascii_alphabetic用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Function std::intrinsics::copy_nonoverlapping。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。