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


Rust copy用法及代碼示例

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

用法

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

count * size_of::<T>() 字節從 src 複製到 dst 。源和目標可能重疊。

如果源和目的地絕不重疊,std::ptr::copy_nonoverlapping可以用它代替。

copy 在語義上等同於 C 的 memmove ,但交換了參數順序。複製就像將字節從 src 複製到臨時數組,然後從數組複製到 dst 一樣。

安全性

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

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

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

  • srcdst 都必須正確對齊。

read 一樣,copy 創建 T 的按位副本,無論 T 是否為 Copy 。如果 T 不是 Copy ,則使用從 *src 開始的區域和從 *dst 開始的區域中的值可以 violate memory safety

請注意,即使有效複製的大小 ( count * size_of::<T>() ) 是 0 ,指針也必須非空且正確對齊。

例子

從不安全的緩衝區高效地創建 Rust 向量:

use std::ptr;

/// # Safety
///
/// * `ptr` must be correctly aligned for its type and non-zero.
/// * `ptr` must be valid for reads of `elts` contiguous elements of type `T`.
/// * Those elements must not be used after calling this function unless `T: Copy`.
unsafe fn from_buf_raw<T>(ptr: *const T, elts: usize) -> Vec<T> {
    let mut dst = Vec::with_capacity(elts);

    // SAFETY: Our precondition ensures the source is aligned and valid,
    // and `Vec::with_capacity` ensures that we have usable space to write them.
    ptr::copy(ptr, dst.as_mut_ptr(), elts);

    // SAFETY: We created it with this much capacity earlier,
    // and the previous `copy` has initialized these elements.
    dst.set_len(elts);
    dst
}

相關用法


注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Function std::ptr::copy。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。