######封装策略主要包括安全抽象、接口设计和错误处理三个方面
安全抽象封装举例:
use std::ops::Deref;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::marker::PhantomData;
pub struct MyArc<T> {
ptr: *const T,
ref_count: *const AtomicUsize, // 原子引用计数
_marker: PhantomData<T>,
}
impl<T> MyArc<T> {
// 创建一个新的MyArc实例
pub fn new(data: T) -> Self {
let ref_count = Box::new(AtomicUsize::new(1));
let ptr = Box::into_raw(Box::new(data));
let ref_count_ptr = Box::into_raw(ref_count);
Self {
ptr,
ref_count: ref_count_ptr,
_marker: PhantomData,
}
}
// 实现克隆操作,增加引用计数
pub fn clone(&self) -> Self {
unsafe {
(*self.ref_count).fetch_add(1, Ordering::SeqCst);
}
Self {
ptr: self.ptr,
ref_count: self.ref_count,
_marker: PhantomData,
}
}
}
impl<T> Deref for MyArc<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &*self.ptr } }}
impl<T> Drop for MyArc<T> {
fn drop(&mut self) {
unsafe {
if (*self.ref_count).fetch_sub(1, Ordering::SeqCst) == 1 {
Box::from_raw(self.ptr as *mut T);
Box::from_raw(self.ref_count as *mut AtomicUsize);
}
}
}
}
接口设计:
extern "C" {
fn memcpy(dest: *mut u8, src: *const u8, n: usize) -> *mut u8;}
pub fn safe_memcpy(dest: &mut [u8], src: &[u8]) {
assert!(dest.len() >= src.len(), "Destination buffer is too small");
unsafe {
memcpy(dest.as_mut_ptr(), src.as_ptr(), src.len());
}
}
错误处理:
use std::ffi::CStr;
use std::os::raw::c_char;
extern "C" {
fn strerror(errnum: i32) -> *const c_char;
}
pub fn safe_strerror(errnum: i32) -> Result<String, std::str::Utf8Error> {
let c_str = unsafe { CStr::from_ptr(strerror(errnum)) };
c_str.to_str().map(|s| s.to_owned())
}