// rust/01-basic-ownership.rs/*Basic ownership patterns and best practices for Rust*/usestd::collections::HashMap;usestd::rc::Rc;usestd::sync::Arc;/// A data structure that demonstrates ownership patterns.pubstructDataContainer{data:Vec<String>,metadata:HashMap<String,String>,}implDataContainer{pubfnnew()->Self{Self{data:Vec::new(),metadata:HashMap::new(),}}/// Takes ownership of a string and stores it.pubfnadd_data(&mutself,item:String){self.data.push(item);}/// Returns ownership of data at the specified index.pubfntake_data(&mutself,index:usize)->Option<String>{ifindex<self.data.len(){Some(self.data.remove(index))}else{None}}/// Borrows data without taking ownership.pubfnget_data(&self,index:usize)->Option<&String>{self.data.get(index)}/// Borrows data mutably without taking ownership.pubfnget_data_mut(&mutself,index:usize)->Option<&mutString>{self.data.get_mut(index)}/// Returns the number of items.pubfnlen(&self)->usize{self.data.len()}/// Returns true if the container is empty.pubfnis_empty(&self)->bool{self.data.is_empty()}/// Clears all data, taking ownership of the cleared items.pubfnclear(&mutself)->Vec<String>{std::mem::take(&mutself.data)}/// Adds metadata with ownership transfer.pubfnadd_metadata(&mutself,key:String,value:String){self.metadata.insert(key,value);}/// Gets metadata by borrowing.pubfnget_metadata(&self,key:&str)->Option<&String>{self.metadata.get(key)}}implDefaultforDataContainer{fndefault()->Self{Self::new()}}/// Demonstrates ownership transfer patterns.pubstructOwnershipDemo{data:Vec<i32>,}implOwnershipDemo{pubfnnew()->Self{Self{data:vec![1,2,3,4,5],}}/// Moves ownership of the entire structure.pubfnmove_ownership(self)->Vec<i32>{self.data}/// Clones data instead of moving.pubfnclone_data(&self)->Vec<i32>{self.data.clone()}/// Borrows data immutably.pubfnborrow_data(&self)->&Vec<i32>{&self.data}/// Borrows data mutably.pubfnborrow_data_mut(&mutself)->&mutVec<i32>{&mutself.data}/// Demonstrates partial move.pubfnpartial_move(self)->(Vec<i32>,usize){letlen=self.data.len();(self.data,len)}}/// Demonstrates reference counting patterns.pubstructReferenceCountedData{data:Rc<String>,count:usize,}implReferenceCountedData{pubfnnew(data:String)->Self{Self{data:Rc::new(data),count:1,}}pubfnclone(&self)->Self{Self{data:Rc::clone(&self.data),count:self.count+1,}}pubfnget_data(&self)->&str{&self.data}pubfnget_count(&self)->usize{Rc::strong_count(&self.data)}}/// Demonstrates atomic reference counting for thread safety.pubstructAtomicReferenceCountedData{data:Arc<String>,count:usize,}implAtomicReferenceCountedData{pubfnnew(data:String)->Self{Self{data:Arc::new(data),count:1,}}pubfnclone(&self)->Self{Self{data:Arc::clone(&self.data),count:self.count+1,}}pubfnget_data(&self)->&str{&self.data}pubfnget_count(&self)->usize{Arc::strong_count(&self.data)}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_data_container(){letmutcontainer=DataContainer::new();assert!(container.is_empty());container.add_data("Hello".to_string());container.add_data("World".to_string());assert_eq!(container.len(),2);assert_eq!(container.get_data(0),Some(&"Hello".to_string()));assert_eq!(container.get_data(1),Some(&"World".to_string()));lettaken=container.take_data(0);assert_eq!(taken,Some("Hello".to_string()));assert_eq!(container.len(),1);}#[test]fntest_ownership_demo(){letdemo=OwnershipDemo::new();letdata=demo.move_ownership();assert_eq!(data,vec![1,2,3,4,5]);}#[test]fntest_reference_counted_data(){letdata=ReferenceCountedData::new("Hello".to_string());assert_eq!(data.get_count(),1);letcloned=data.clone();assert_eq!(data.get_count(),2);assert_eq!(cloned.get_count(),2);assert_eq!(data.get_data(),"Hello");assert_eq!(cloned.get_data(),"Hello");}#[test]fntest_atomic_reference_counted_data(){letdata=AtomicReferenceCountedData::new("Hello".to_string());assert_eq!(data.get_count(),1);letcloned=data.clone();assert_eq!(data.get_count(),2);assert_eq!(cloned.get_count(),2);assert_eq!(data.get_data(),"Hello");assert_eq!(cloned.get_data(),"Hello");}}
// rust/02-borrowing-patterns.rs/*Borrowing patterns and best practices for Rust*/usestd::collections::HashMap;usestd::cell::RefCell;usestd::rc::Rc;/// Demonstrates different borrowing patterns.pubstructBorrowingDemo{data:Vec<String>,cache:HashMap<String,usize>,}implBorrowingDemo{pubfnnew()->Self{Self{data:Vec::new(),cache:HashMap::new(),}}/// Immutable borrowing for reading.pubfnget_data(&self,index:usize)->Option<&String>{self.data.get(index)}/// Mutable borrowing for writing.pubfnadd_data(&mutself,item:String){self.data.push(item);}/// Multiple immutable borrows.pubfnget_multiple_data(&self,indices:&[usize])->Vec<Option<&String>>{indices.iter().map(|&i|self.data.get(i)).collect()}/// Mutable borrowing with lifetime.pubfnupdate_data<F>(&mutself,index:usize,f:F)->boolwhereF:FnOnce(&mutString),{ifletSome(item)=self.data.get_mut(index){f(item);true}else{false}}/// Borrowing with caching.pubfnget_cached_data(&mutself,key:&str)->Option<&String>{ifletSome(&index)=self.cache.get(key){self.data.get(index)}else{None}}/// Borrowing with cache update.pubfnadd_cached_data(&mutself,key:String,value:String){letindex=self.data.len();self.data.push(value);self.cache.insert(key,index);}}/// Demonstrates interior mutability patterns.pubstructInteriorMutabilityDemo{data:RefCell<Vec<String>>,count:Rc<RefCell<usize>>,}implInteriorMutabilityDemo{pubfnnew()->Self{Self{data:RefCell::new(Vec::new()),count:Rc::new(RefCell::new(0)),}}/// Interior mutability for reading.pubfnget_data(&self,index:usize)->Option<String>{self.data.borrow().get(index).cloned()}/// Interior mutability for writing.pubfnadd_data(&self,item:String){self.data.borrow_mut().push(item);*self.count.borrow_mut()+=1;}/// Shared reference counting with interior mutability.pubfnclone_count(&self)->Rc<RefCell<usize>>{Rc::clone(&self.count)}/// Get current count.pubfnget_count(&self)->usize{*self.count.borrow()}}/// Demonstrates borrowing with lifetime parameters.pubstructLifetimeDemo<'a>{data:&'a[String],index:usize,}impl<'a>LifetimeDemo<'a>{pubfnnew(data:&'a[String])->Self{Self{data,index:0}}/// Borrowing with explicit lifetime.pubfnget_current(&self)->Option<&'aString>{self.data.get(self.index)}/// Mutable borrowing with lifetime.pubfnnext(&mutself)->Option<&'aString>{ifself.index<self.data.len(){letresult=&self.data[self.index];self.index+=1;Some(result)}else{None}}/// Borrowing with lifetime and bounds checking.pubfnget_safe(&self,index:usize)->Option<&'aString>{ifindex<self.data.len(){Some(&self.data[index])}else{None}}}/// Demonstrates borrowing with trait objects.pubtraitDataProcessor{fnprocess(&self,data:&str)->String;fnget_name(&self)->&str;}pubstructUpperCaseProcessor;implDataProcessorforUpperCaseProcessor{fnprocess(&self,data:&str)->String{data.to_uppercase()}fnget_name(&self)->&str{"UpperCase"}}pubstructLowerCaseProcessor;implDataProcessorforLowerCaseProcessor{fnprocess(&self,data:&str)->String{data.to_lowercase()}fnget_name(&self)->&str{"LowerCase"}}/// Demonstrates borrowing with trait objects.pubstructProcessorManager{processors:Vec<Box<dynDataProcessor>>,}implProcessorManager{pubfnnew()->Self{Self{processors:Vec::new(),}}pubfnadd_processor(&mutself,processor:Box<dynDataProcessor>){self.processors.push(processor);}pubfnprocess_all(&self,data:&str)->Vec<String>{self.processors.iter().map(|p|p.process(data)).collect()}pubfnget_processor_names(&self)->Vec<&str>{self.processors.iter().map(|p|p.get_name()).collect()}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_borrowing_demo(){letmutdemo=BorrowingDemo::new();demo.add_data("Hello".to_string());demo.add_data("World".to_string());assert_eq!(demo.get_data(0),Some(&"Hello".to_string()));assert_eq!(demo.get_data(1),Some(&"World".to_string()));letindices=vec![0,1];letresults=demo.get_multiple_data(&indices);assert_eq!(results.len(),2);assert_eq!(results[0],Some(&"Hello".to_string()));assert_eq!(results[1],Some(&"World".to_string()));}#[test]fntest_interior_mutability(){letdemo=InteriorMutabilityDemo::new();demo.add_data("Hello".to_string());demo.add_data("World".to_string());assert_eq!(demo.get_data(0),Some("Hello".to_string()));assert_eq!(demo.get_data(1),Some("World".to_string()));assert_eq!(demo.get_count(),2);}#[test]fntest_lifetime_demo(){letdata=vec!["Hello".to_string(),"World".to_string()];letmutdemo=LifetimeDemo::new(&data);assert_eq!(demo.get_current(),Some(&"Hello".to_string()));assert_eq!(demo.next(),Some(&"Hello".to_string()));assert_eq!(demo.next(),Some(&"World".to_string()));assert_eq!(demo.next(),None);}#[test]fntest_processor_manager(){letmutmanager=ProcessorManager::new();manager.add_processor(Box::new(UpperCaseProcessor));manager.add_processor(Box::new(LowerCaseProcessor));letresults=manager.process_all("Hello");assert_eq!(results.len(),2);assert!(results.contains(&"HELLO".to_string()));assert!(results.contains(&"hello".to_string()));letnames=manager.get_processor_names();assert_eq!(names.len(),2);assert!(names.contains(&"UpperCase"));assert!(names.contains(&"LowerCase"));}}
// rust/03-lifetime-management.rs/*Lifetime management patterns and best practices for Rust*/usestd::collections::HashMap;usestd::marker::PhantomData;/// Demonstrates lifetime management with explicit lifetimes.pubstructLifetimeManager<'a>{data:&'a[String],cache:HashMap<String,&'aString>,}impl<'a>LifetimeManager<'a>{pubfnnew(data:&'a[String])->Self{Self{data,cache:HashMap::new(),}}/// Borrowing with explicit lifetime.pubfnget_data(&self,index:usize)->Option<&'aString>{self.data.get(index)}/// Caching with lifetime management.pubfnget_cached_data(&mutself,key:&str)->Option<&'aString>{ifletSome(&value)=self.cache.get(key){Some(value)}else{letvalue=self.data.iter().find(|s|s==key)?;self.cache.insert(key.to_string(),value);Some(value)}}/// Borrowing with lifetime and bounds checking.pubfnget_safe_data(&self,index:usize)->Option<&'aString>{ifindex<self.data.len(){Some(&self.data[index])}else{None}}}/// Demonstrates lifetime management with generic parameters.pubstructGenericLifetimeManager<'a,T>{data:&'a[T],_phantom:PhantomData<T>,}impl<'a,T>GenericLifetimeManager<'a,T>{pubfnnew(data:&'a[T])->Self{Self{data,_phantom:PhantomData,}}pubfnget_data(&self,index:usize)->Option<&'aT>{self.data.get(index)}pubfnget_safe_data(&self,index:usize)->Option<&'aT>{ifindex<self.data.len(){Some(&self.data[index])}else{None}}}/// Demonstrates lifetime management with trait bounds.pubtraitLifetimeTrait<'a>{fnget_data(&self)->&'astr;fnget_mutable_data(&mutself)->&'amutstr;}pubstructLifetimeTraitImpl<'a>{data:&'amutString,}impl<'a>LifetimeTraitImpl<'a>{pubfnnew(data:&'amutString)->Self{Self{data}}}impl<'a>LifetimeTrait<'a>forLifetimeTraitImpl<'a>{fnget_data(&self)->&'astr{self.data}fnget_mutable_data(&mutself)->&'amutstr{self.data}}/// Demonstrates lifetime management with higher-ranked trait bounds.pubstructHigherRankedLifetimeManager{data:Vec<String>,}implHigherRankedLifetimeManager{pubfnnew()->Self{Self{data:Vec::new(),}}pubfnadd_data(&mutself,item:String){self.data.push(item);}/// Higher-ranked trait bound for lifetime management.pubfnprocess_data<F>(&self,processor:F)->Vec<String>whereF:for<'a>Fn(&'astr)->String,{self.data.iter().map(|s|processor(s.as_str())).collect()}/// Borrowing with lifetime management.pubfnget_data(&self,index:usize)->Option<&str>{self.data.get(index).map(|s|s.as_str())}}/// Demonstrates lifetime management with async code.pubstructAsyncLifetimeManager{data:Vec<String>,}implAsyncLifetimeManager{pubfnnew()->Self{Self{data:Vec::new(),}}pubfnadd_data(&mutself,item:String){self.data.push(item);}/// Async function with lifetime management.pubasyncfnprocess_data_async<F,Fut>(&self,processor:F)->Vec<String>whereF:Fn(&str)->Fut,Fut:std::future::Future<Output=String>,{letmutresults=Vec::new();foritemin&self.data{letresult=processor(item.as_str()).await;results.push(result);}results}/// Borrowing with lifetime management in async context.pubasyncfnget_data_async(&self,index:usize)->Option<&str>{self.data.get(index).map(|s|s.as_str())}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_lifetime_manager(){letdata=vec!["Hello".to_string(),"World".to_string()];letmutmanager=LifetimeManager::new(&data);assert_eq!(manager.get_data(0),Some(&"Hello".to_string()));assert_eq!(manager.get_data(1),Some(&"World".to_string()));letcached=manager.get_cached_data("Hello");assert_eq!(cached,Some(&"Hello".to_string()));}#[test]fntest_generic_lifetime_manager(){letdata=vec![1,2,3,4,5];letmanager=GenericLifetimeManager::new(&data);assert_eq!(manager.get_data(0),Some(&1));assert_eq!(manager.get_data(1),Some(&2));assert_eq!(manager.get_safe_data(10),None);}#[test]fntest_higher_ranked_lifetime_manager(){letmutmanager=HigherRankedLifetimeManager::new();manager.add_data("Hello".to_string());manager.add_data("World".to_string());letresults=manager.process_data(|s|s.to_uppercase());assert_eq!(results.len(),2);assert!(results.contains(&"HELLO".to_string()));assert!(results.contains(&"WORLD".to_string()));}#[test]fntest_async_lifetime_manager(){letmutmanager=AsyncLifetimeManager::new();manager.add_data("Hello".to_string());manager.add_data("World".to_string());letresults=futures::executor::block_on(manager.process_data_async(|s|async{s.to_uppercase()}));assert_eq!(results.len(),2);assert!(results.contains(&"HELLO".to_string()));assert!(results.contains(&"WORLD".to_string()));}}