// rust/01-basic-unsafe.rs/*Basic unsafe patterns and best practices for Rust*/usestd::ptr;usestd::mem;usestd::alloc::{alloc,dealloc,Layout};/// Safe wrapper around unsafe memory operations.pubstructSafeBuffer{ptr:*mutu8,len:usize,capacity:usize,}implSafeBuffer{/// Creates a new buffer with the specified capacity.pubfnnew(capacity:usize)->Self{letlayout=Layout::from_size_align(capacity,1).unwrap();letptr=unsafe{alloc(layout)};ifptr.is_null(){panic!("Failed to allocate memory");}Self{ptr,len:0,capacity,}}/// Pushes a byte to the buffer.pubfnpush(&mutself,byte:u8)->Result<(),&'staticstr>{ifself.len>=self.capacity{returnErr("Buffer is full");}unsafe{ptr::write(self.ptr.add(self.len),byte);}self.len+=1;Ok(())}/// Gets a byte from the buffer.pubfnget(&self,index:usize)->Option<u8>{ifindex>=self.len{returnNone;}unsafe{Some(ptr::read(self.ptr.add(index)))}}/// Gets a slice of the buffer.pubfnas_slice(&self)->&[u8]{unsafe{std::slice::from_raw_parts(self.ptr,self.len)}}/// Gets a mutable slice of the buffer.pubfnas_mut_slice(&mutself)->&mut[u8]{unsafe{std::slice::from_raw_parts_mut(self.ptr,self.len)}}}implDropforSafeBuffer{fndrop(&mutself){if!self.ptr.is_null(){letlayout=Layout::from_size_align(self.capacity,1).unwrap();unsafe{dealloc(self.ptr,layout);}}}}/// Safe wrapper around raw pointers.pubstructSafePointer<T>{ptr:*mutT,_phantom:std::marker::PhantomData<T>,}impl<T>SafePointer<T>{/// Creates a new safe pointer from a raw pointer.pubfnnew(ptr:*mutT)->Self{Self{ptr,_phantom:std::marker::PhantomData,}}/// Gets a reference to the value.pubfnget(&self)->Option<&T>{ifself.ptr.is_null(){None}else{unsafe{Some(&*self.ptr)}}}/// Gets a mutable reference to the value.pubfnget_mut(&mutself)->Option<&mutT>{ifself.ptr.is_null(){None}else{unsafe{Some(&mut*self.ptr)}}}/// Sets the value at the pointer.pubfnset(&mutself,value:T){if!self.ptr.is_null(){unsafe{ptr::write(self.ptr,value);}}}}/// Safe wrapper around raw arrays.pubstructSafeArray<T>{ptr:*mutT,len:usize,_phantom:std::marker::PhantomData<T>,}impl<T>SafeArray<T>{/// Creates a new safe array.pubfnnew(len:usize)->Self{letlayout=Layout::array::<T>(len).unwrap();letptr=unsafe{alloc(layout)as*mutT};ifptr.is_null(){panic!("Failed to allocate memory");}Self{ptr,len,_phantom:std::marker::PhantomData,}}/// Gets an element by index.pubfnget(&self,index:usize)->Option<&T>{ifindex>=self.len{None}else{unsafe{Some(&*self.ptr.add(index))}}}/// Gets a mutable element by index.pubfnget_mut(&mutself,index:usize)->Option<&mutT>{ifindex>=self.len{None}else{unsafe{Some(&mut*self.ptr.add(index))}}}/// Sets an element by index.pubfnset(&mutself,index:usize,value:T)->Result<(),&'staticstr>{ifindex>=self.len{Err("Index out of bounds")}else{unsafe{ptr::write(self.ptr.add(index),value);}Ok(())}}}impl<T>DropforSafeArray<T>{fndrop(&mutself){if!self.ptr.is_null(){letlayout=Layout::array::<T>(self.len).unwrap();unsafe{dealloc(self.ptras*mutu8,layout);}}}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_safe_buffer(){letmutbuffer=SafeBuffer::new(10);buffer.push(1).unwrap();buffer.push(2).unwrap();buffer.push(3).unwrap();assert_eq!(buffer.get(0),Some(1));assert_eq!(buffer.get(1),Some(2));assert_eq!(buffer.get(2),Some(3));assert_eq!(buffer.get(3),None);}#[test]fntest_safe_pointer(){letmutvalue=42;letmutpointer=SafePointer::new(&mutvalueas*muti32);assert_eq!(pointer.get(),Some(&42));pointer.set(100);assert_eq!(pointer.get(),Some(&100));}#[test]fntest_safe_array(){letmutarray=SafeArray::new(5);array.set(0,1).unwrap();array.set(1,2).unwrap();array.set(2,3).unwrap();assert_eq!(array.get(0),Some(&1));assert_eq!(array.get(1),Some(&2));assert_eq!(array.get(2),Some(&3));assert_eq!(array.get(5),None);}}
// rust/02-ffi-patterns.rs/*FFI patterns and best practices for Rust*/usestd::ffi::{CString,CStr};usestd::os::raw::{c_char,c_int};/// Safe wrapper around C string operations.pubstructSafeCString{ptr:*mutc_char,}implSafeCString{/// Creates a new safe C string from a Rust string.pubfnnew(s:&str)->Result<Self,std::ffi::NulError>{letc_string=CString::new(s)?;letptr=c_string.into_raw();Ok(Self{ptr})}/// Gets the C string as a Rust string.pubfnto_string(&self)->Result<String,std::str::Utf8Error>{unsafe{letc_str=CStr::from_ptr(self.ptr);Ok(c_str.to_str()?.to_string())}}/// Gets the raw pointer.pubfnas_ptr(&self)->*constc_char{self.ptr}}implDropforSafeCString{fndrop(&mutself){if!self.ptr.is_null(){unsafe{let_=CString::from_raw(self.ptr);}}}}/// Safe wrapper around C function calls.pubstructSafeCFunction;implSafeCFunction{/// Calls a C function with error handling.pubfncall_c_function(input:&str)->Result<i32,String>{letc_string=CString::new(input).map_err(|e|format!("Failed to create C string: {}",e))?;letresult=unsafe{// Simulate C function callc_function_wrapper(c_string.as_ptr())};ifresult<0{Err("C function returned error".to_string())}else{Ok(result)}}}/// Safe wrapper around C struct operations.pubstructSafeCStruct{data:Vec<u8>,}implSafeCStruct{/// Creates a new safe C struct.pubfnnew(size:usize)->Self{Self{data:vec![0;size],}}/// Gets a field from the struct.pubfnget_field(&self,offset:usize,size:usize)->Option<&[u8]>{ifoffset+size<=self.data.len(){Some(&self.data[offset..offset+size])}else{None}}/// Sets a field in the struct.pubfnset_field(&mutself,offset:usize,data:&[u8])->Result<(),&'staticstr>{ifoffset+data.len()>self.data.len(){returnErr("Field would exceed struct bounds");}self.data[offset..offset+data.len()].copy_from_slice(data);Ok(())}/// Gets the raw pointer to the struct.pubfnas_ptr(&self)->*constu8{self.data.as_ptr()}}// External C function declarationextern"C"{fnc_function_wrapper(input:*constc_char)->c_int;}#[cfg(test)]modtests{usesuper::*;#[test]fntest_safe_c_string(){letc_string=SafeCString::new("Hello, World!").unwrap();assert_eq!(c_string.to_string().unwrap(),"Hello, World!");}#[test]fntest_safe_c_struct(){letmutc_struct=SafeCStruct::new(100);letdata=b"Hello";c_struct.set_field(0,data).unwrap();letfield=c_struct.get_field(0,5).unwrap();assert_eq!(field,data);}}
// rust/03-memory-management.rs/*Memory management patterns and best practices for Rust*/usestd::alloc::{alloc,dealloc,Layout};usestd::ptr;/// Safe wrapper around raw memory allocation.pubstructSafeMemory{ptr:*mutu8,size:usize,layout:Layout,}implSafeMemory{/// Allocates memory with the specified size and alignment.pubfnnew(size:usize,align:usize)->Result<Self,&'staticstr>{letlayout=Layout::from_size_align(size,align).map_err(|_|"Invalid layout")?;letptr=unsafe{alloc(layout)};ifptr.is_null(){returnErr("Failed to allocate memory");}Ok(Self{ptr,size,layout})}/// Writes data to the memory.pubfnwrite(&mutself,offset:usize,data:&[u8])->Result<(),&'staticstr>{ifoffset+data.len()>self.size{returnErr("Write would exceed memory bounds");}unsafe{ptr::copy_nonoverlapping(data.as_ptr(),self.ptr.add(offset),data.len());}Ok(())}/// Reads data from the memory.pubfnread(&self,offset:usize,len:usize)->Result<Vec<u8>,&'staticstr>{ifoffset+len>self.size{returnErr("Read would exceed memory bounds");}letmutresult=vec![0;len];unsafe{ptr::copy_nonoverlapping(self.ptr.add(offset),result.as_mut_ptr(),len);}Ok(result)}/// Gets the raw pointer.pubfnas_ptr(&self)->*constu8{self.ptr}/// Gets the mutable raw pointer.pubfnas_mut_ptr(&mutself)->*mutu8{self.ptr}}implDropforSafeMemory{fndrop(&mutself){if!self.ptr.is_null(){unsafe{dealloc(self.ptr,self.layout);}}}}/// Safe wrapper around memory-mapped operations.pubstructSafeMemoryMap{ptr:*mutu8,size:usize,}implSafeMemoryMap{/// Creates a new memory map.pubfnnew(size:usize)->Result<Self,&'staticstr>{letlayout=Layout::from_size_align(size,1).map_err(|_|"Invalid layout")?;letptr=unsafe{alloc(layout)};ifptr.is_null(){returnErr("Failed to allocate memory");}Ok(Self{ptr,size})}/// Maps data to the memory.pubfnmap(&mutself,data:&[u8])->Result<(),&'staticstr>{ifdata.len()>self.size{returnErr("Data too large for memory map");}unsafe{ptr::copy_nonoverlapping(data.as_ptr(),self.ptr,data.len());}Ok(())}/// Unmaps data from the memory.pubfnunmap(&mutself){unsafe{ptr::write_bytes(self.ptr,0,self.size);}}/// Gets a slice of the mapped memory.pubfnas_slice(&self)->&[u8]{unsafe{std::slice::from_raw_parts(self.ptr,self.size)}}}implDropforSafeMemoryMap{fndrop(&mutself){if!self.ptr.is_null(){letlayout=Layout::from_size_align(self.size,1).unwrap();unsafe{dealloc(self.ptr,layout);}}}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_safe_memory(){letmutmemory=SafeMemory::new(100,1).unwrap();letdata=b"Hello, World!";memory.write(0,data).unwrap();letread_data=memory.read(0,data.len()).unwrap();assert_eq!(read_data,data);}#[test]fntest_safe_memory_map(){letmutmemory_map=SafeMemoryMap::new(100).unwrap();letdata=b"Hello, World!";memory_map.map(data).unwrap();letslice=memory_map.as_slice();assert_eq!(&slice[..data.len()],data);}}