當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Rust copy_nonoverlapping用法及代碼示例

本文簡要介紹rust語言中 Function std::ptr::copy_nonoverlapping 的用法。

用法

pub unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize)

副本count * size_of::<T>()字節來自srcdst。源和目的地必須不是重疊。

對於可能重疊的內存區域,請改用 copy

copy_nonoverlapping 在語義上等同於 C 的 memcpy ,但交換了參數順序。

安全性

如果違反以下任何條件,則行為未定義:

  • 對於讀取 count * size_of::<T>() 字節,src 必須是 valid

  • 對於 count * size_of::<T>() 字節的寫入,dst 必須是 valid

  • srcdst 都必須正確對齊。

  • 內存區域開始於src大小為count * size_of::<T>()字節必須不是與開始於的內存區域重疊dst具有相同的尺寸。

就像std::ptr::read,copy_nonoverlapping創建一個按位複製T, 不管是否Tstd::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-lang.org大神的英文原創作品 Function std::ptr::copy_nonoverlapping。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。