// rust/01-clippy-configuration.rs/*Clippy configuration and linting patterns for Rust code quality*/// Clippy configuration in Cargo.toml/*[lints.clippy]# Performance lintsall = "warn"pedantic = "warn"nursery = "warn"cargo = "warn"# Specific lint configurationsclippy::all = "warn"clippy::pedantic = "warn"clippy::nursery = "warn"clippy::cargo = "warn"# Allow some pedantic lints that might be too strictclippy::module_name_repetitions = "allow"clippy::must_use_candidate = "allow"clippy::missing_errors_doc = "allow"*/usestd::collections::HashMap;usestd::fmt;useanyhow::Result;/// A high-quality data structure for managing key-value pairs.////// This structure provides efficient storage and retrieval of string key-value pairs/// with built-in validation and error handling.#[derive(Debug, Clone, PartialEq, Eq)]pubstructKeyValueStore{data:HashMap<String,String>,max_size:usize,}implKeyValueStore{/// Creates a new `KeyValueStore` with the specified maximum size.////// # Arguments////// * `max_size` - Maximum number of key-value pairs that can be stored////// # Examples////// ```/// use my_crate::KeyValueStore;////// let store = KeyValueStore::new(1000);/// ```pubfnnew(max_size:usize)->Self{Self{data:HashMap::new(),max_size,}}/// Inserts a key-value pair into the store.////// # Arguments////// * `key` - The key to insert/// * `value` - The value to associate with the key////// # Returns////// Returns `Ok(())` if the insertion was successful, or an error if:/// - The key is empty/// - The store is at maximum capacity////// # Examples////// ```/// use my_crate::KeyValueStore;////// let mut store = KeyValueStore::new(100);/// store.insert("user_id", "12345").unwrap();/// ```pubfninsert(&mutself,key:&str,value:&str)->Result<()>{ifkey.is_empty(){returnErr(anyhow::anyhow!("Key cannot be empty"));}ifself.data.len()>=self.max_size&&!self.data.contains_key(key){returnErr(anyhow::anyhow!("Store is at maximum capacity"));}self.data.insert(key.to_string(),value.to_string());Ok(())}/// Retrieves a value by its key.////// # Arguments////// * `key` - The key to look up////// # Returns////// Returns `Some(&str)` if the key exists, or `None` if not found.////// # Examples////// ```/// use my_crate::KeyValueStore;////// let mut store = KeyValueStore::new(100);/// store.insert("user_id", "12345").unwrap();/// assert_eq!(store.get("user_id"), Some("12345"));/// ```pubfnget(&self,key:&str)->Option<&str>{self.data.get(key).map(|s|s.as_str())}/// Removes a key-value pair from the store.////// # Arguments////// * `key` - The key to remove////// # Returns////// Returns `Some(String)` if the key existed and was removed, or `None` if not found.////// # Examples////// ```/// use my_crate::KeyValueStore;////// let mut store = KeyValueStore::new(100);/// store.insert("user_id", "12345").unwrap();/// assert_eq!(store.remove("user_id"), Some("12345".to_string()));/// ```pubfnremove(&mutself,key:&str)->Option<String>{self.data.remove(key)}/// Returns the number of key-value pairs in the store.////// # Examples////// ```/// use my_crate::KeyValueStore;////// let mut store = KeyValueStore::new(100);/// store.insert("key1", "value1").unwrap();/// store.insert("key2", "value2").unwrap();/// assert_eq!(store.len(), 2);/// ```pubfnlen(&self)->usize{self.data.len()}/// Returns `true` if the store is empty.////// # Examples////// ```/// use my_crate::KeyValueStore;////// let store = KeyValueStore::new(100);/// assert!(store.is_empty());/// ```pubfnis_empty(&self)->bool{self.data.is_empty()}/// Returns `true` if the store contains the specified key.////// # Arguments////// * `key` - The key to check for////// # Examples////// ```/// use my_crate::KeyValueStore;////// let mut store = KeyValueStore::new(100);/// store.insert("user_id", "12345").unwrap();/// assert!(store.contains_key("user_id"));/// ```pubfncontains_key(&self,key:&str)->bool{self.data.contains_key(key)}/// Clears all key-value pairs from the store.////// # Examples////// ```/// use my_crate::KeyValueStore;////// let mut store = KeyValueStore::new(100);/// store.insert("key", "value").unwrap();/// store.clear();/// assert!(store.is_empty());/// ```pubfnclear(&mutself){self.data.clear();}}implDefaultforKeyValueStore{fndefault()->Self{Self::new(1000)}}implfmt::DisplayforKeyValueStore{fnfmt(&self,f:&mutfmt::Formatter<'_>)->fmt::Result{write!(f,"KeyValueStore({}/{})",self.data.len(),self.max_size)}}// Iterator implementation for better ergonomicsimpl<'a>IntoIteratorfor&'aKeyValueStore{typeItem=(&'aString,&'aString);typeIntoIter=std::collections::hash_map::Iter<'a,String,String>;fninto_iter(self)->Self::IntoIter{self.data.iter()}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_new_store(){letstore=KeyValueStore::new(100);assert_eq!(store.max_size,100);assert!(store.is_empty());}#[test]fntest_insert_and_get(){letmutstore=KeyValueStore::new(100);store.insert("key","value").unwrap();assert_eq!(store.get("key"),Some("value"));}#[test]fntest_empty_key_error(){letmutstore=KeyValueStore::new(100);letresult=store.insert("","value");assert!(result.is_err());}#[test]fntest_capacity_limit(){letmutstore=KeyValueStore::new(1);store.insert("key1","value1").unwrap();letresult=store.insert("key2","value2");assert!(result.is_err());}#[test]fntest_remove(){letmutstore=KeyValueStore::new(100);store.insert("key","value").unwrap();assert_eq!(store.remove("key"),Some("value".to_string()));assert!(store.get("key").is_none());}#[test]fntest_contains_key(){letmutstore=KeyValueStore::new(100);store.insert("key","value").unwrap();assert!(store.contains_key("key"));assert!(!store.contains_key("nonexistent"));}#[test]fntest_clear(){letmutstore=KeyValueStore::new(100);store.insert("key","value").unwrap();store.clear();assert!(store.is_empty());}#[test]fntest_display(){letstore=KeyValueStore::new(100);letdisplay=format!("{}",store);assert!(display.contains("KeyValueStore"));}#[test]fntest_iterator(){letmutstore=KeyValueStore::new(100);store.insert("key1","value1").unwrap();store.insert("key2","value2").unwrap();letmutitems:Vec<_>=store.into_iter().collect();items.sort_by_key(|(k,_)|*k);assert_eq!(items.len(),2);assert_eq!(items[0],(&"key1".to_string(),&"value1".to_string()));assert_eq!(items[1],(&"key2".to_string(),&"value2".to_string()));}}
// rust/02-rustfmt-configuration.rs/*Rustfmt configuration and formatting patterns*/// rustfmt.toml configuration/*# rustfmt.tomledition = "2021"max_width = 100tab_spaces = 4newline_style = "Unix"use_small_heuristics = "Default"indent_style = "Block"wrap_comments = truecomment_width = 80normalize_comments = truenormalize_doc_attributes = trueformat_code_in_doc_comments = trueformat_strings = trueformat_macro_matchers = trueformat_generated_files = falserequired_version = "1.70.0"*/usestd::collections::HashMap;usestd::fmt;useanyhow::Result;/// A well-formatted data structure for managing user sessions.////// This structure provides efficient storage and retrieval of user session data/// with built-in validation and error handling. It follows Rust formatting/// best practices for readability and maintainability.#[derive(Debug, Clone, PartialEq, Eq)]pubstructUserSession{user_id:u64,session_id:String,data:HashMap<String,String>,created_at:std::time::SystemTime,expires_at:std::time::SystemTime,}implUserSession{/// Creates a new `UserSession` with the specified parameters.////// # Arguments////// * `user_id` - The ID of the user/// * `session_id` - The unique session identifier/// * `duration_seconds` - Session duration in seconds////// # Returns////// Returns a new `UserSession` instance.////// # Examples////// ```/// use my_crate::UserSession;////// let session = UserSession::new(12345, "sess_abc123".to_string(), 3600);/// ```pubfnnew(user_id:u64,session_id:String,duration_seconds:u64,)->Self{letnow=std::time::SystemTime::now();letexpires_at=now+std::time::Duration::from_secs(duration_seconds);Self{user_id,session_id,data:HashMap::new(),created_at:now,expires_at,}}/// Adds a key-value pair to the session data.////// # Arguments////// * `key` - The key to add/// * `value` - The value to associate with the key////// # Returns////// Returns `Ok(())` if the addition was successful, or an error if:/// - The key is empty/// - The session has expired////// # Examples////// ```/// use my_crate::UserSession;////// let mut session = UserSession::new(12345, "sess_abc123".to_string(), 3600);/// session.set_data("theme", "dark").unwrap();/// ```pubfnset_data(&mutself,key:&str,value:&str)->Result<()>{ifkey.is_empty(){returnErr(anyhow::anyhow!("Key cannot be empty"));}ifself.is_expired(){returnErr(anyhow::anyhow!("Session has expired"));}self.data.insert(key.to_string(),value.to_string());Ok(())}/// Retrieves a value by its key.////// # Arguments////// * `key` - The key to look up////// # Returns////// Returns `Some(&str)` if the key exists and the session is valid,/// or `None` if not found or expired.////// # Examples////// ```/// use my_crate::UserSession;////// let mut session = UserSession::new(12345, "sess_abc123".to_string(), 3600);/// session.set_data("theme", "dark").unwrap();/// assert_eq!(session.get_data("theme"), Some("dark"));/// ```pubfnget_data(&self,key:&str)->Option<&str>{ifself.is_expired(){returnNone;}self.data.get(key).map(|s|s.as_str())}/// Checks if the session has expired.////// # Returns////// Returns `true` if the session has expired, `false` otherwise.////// # Examples////// ```/// use my_crate::UserSession;////// let session = UserSession::new(12345, "sess_abc123".to_string(), 3600);/// assert!(!session.is_expired());/// ```pubfnis_expired(&self)->bool{std::time::SystemTime::now()>self.expires_at}/// Returns the user ID associated with this session.////// # Returns////// Returns the user ID.////// # Examples////// ```/// use my_crate::UserSession;////// let session = UserSession::new(12345, "sess_abc123".to_string(), 3600);/// assert_eq!(session.user_id(), 12345);/// ```pubfnuser_id(&self)->u64{self.user_id}/// Returns the session ID.////// # Returns////// Returns the session ID.////// # Examples////// ```/// use my_crate::UserSession;////// let session = UserSession::new(12345, "sess_abc123".to_string(), 3600);/// assert_eq!(session.session_id(), "sess_abc123");/// ```pubfnsession_id(&self)->&str{&self.session_id}/// Returns the number of data items in the session.////// # Returns////// Returns the number of data items.////// # Examples////// ```/// use my_crate::UserSession;////// let mut session = UserSession::new(12345, "sess_abc123".to_string(), 3600);/// session.set_data("key1", "value1").unwrap();/// session.set_data("key2", "value2").unwrap();/// assert_eq!(session.len(), 2);/// ```pubfnlen(&self)->usize{self.data.len()}/// Returns `true` if the session has no data.////// # Returns////// Returns `true` if the session is empty, `false` otherwise.////// # Examples////// ```/// use my_crate::UserSession;////// let session = UserSession::new(12345, "sess_abc123".to_string(), 3600);/// assert!(session.is_empty());/// ```pubfnis_empty(&self)->bool{self.data.is_empty()}}implfmt::DisplayforUserSession{fnfmt(&self,f:&mutfmt::Formatter<'_>)->fmt::Result{write!(f,"UserSession(user_id={}, session_id={}, data_count={})",self.user_id,self.session_id,self.data.len())}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_new_session(){letsession=UserSession::new(12345,"sess_abc123".to_string(),3600);assert_eq!(session.user_id(),12345);assert_eq!(session.session_id(),"sess_abc123");assert!(!session.is_expired());assert!(session.is_empty());}#[test]fntest_set_and_get_data(){letmutsession=UserSession::new(12345,"sess_abc123".to_string(),3600);session.set_data("theme","dark").unwrap();assert_eq!(session.get_data("theme"),Some("dark"));}#[test]fntest_empty_key_error(){letmutsession=UserSession::new(12345,"sess_abc123".to_string(),3600);letresult=session.set_data("","value");assert!(result.is_err());}#[test]fntest_session_length(){letmutsession=UserSession::new(12345,"sess_abc123".to_string(),3600);session.set_data("key1","value1").unwrap();session.set_data("key2","value2").unwrap();assert_eq!(session.len(),2);}#[test]fntest_display(){letsession=UserSession::new(12345,"sess_abc123".to_string(),3600);letdisplay=format!("{}",session);assert!(display.contains("UserSession"));assert!(display.contains("12345"));assert!(display.contains("sess_abc123"));}}
// rust/03-module-structure.rs/*Module organization and code structure patterns*/// lib.rs - Main library entry pointpubmodauth;pubmoddata;pubmoderrors;pubmodutils;// Re-export commonly used typespubuseauth::{User,UserService};pubusedata::{DataStore,DataService};pubuseerrors::{Error,Result};// Feature-gated modules#[cfg(feature = "async")]pubmodasync_utils;#[cfg(feature = "serde")]pubmodserialization;// Example module structurepubmodauth{usestd::collections::HashMap;useanyhow::Result;/// Represents a user in the system.#[derive(Debug, Clone, PartialEq, Eq)]pubstructUser{pubid:u64,pubusername:String,pubemail:String,pubis_active:bool,}/// Service for managing user authentication and authorization.pubstructUserService{users:HashMap<u64,User>,sessions:HashMap<String,u64>,}implUserService{pubfnnew()->Self{Self{users:HashMap::new(),sessions:HashMap::new(),}}pubfncreate_user(&mutself,username:String,email:String,)->Result<User>{ifusername.is_empty(){returnErr(anyhow::anyhow!("Username cannot be empty"));}ifemail.is_empty(){returnErr(anyhow::anyhow!("Email cannot be empty"));}letuser=User{id:self.users.len()asu64+1,username,email,is_active:true,};self.users.insert(user.id,user.clone());Ok(user)}pubfnget_user(&self,id:u64)->Option<&User>{self.users.get(&id)}pubfnauthenticate(&mutself,username:&str)->Result<String>{letuser=self.users.values().find(|u|u.username==username).ok_or_else(||anyhow::anyhow!("User not found"))?;if!user.is_active{returnErr(anyhow::anyhow!("User is not active"));}letsession_id=format!("sess_{}",uuid::Uuid::new_v4());self.sessions.insert(session_id.clone(),user.id);Ok(session_id)}pubfnget_user_by_session(&self,session_id:&str)->Option<&User>{letuser_id=self.sessions.get(session_id)?;self.users.get(user_id)}}implDefaultforUserService{fndefault()->Self{Self::new()}}}pubmoddata{usestd::collections::HashMap;useanyhow::Result;/// A data store for managing key-value pairs.pubstructDataStore{data:HashMap<String,String>,}implDataStore{pubfnnew()->Self{Self{data:HashMap::new(),}}pubfnset(&mutself,key:String,value:String)->Result<()>{ifkey.is_empty(){returnErr(anyhow::anyhow!("Key cannot be empty"));}self.data.insert(key,value);Ok(())}pubfnget(&self,key:&str)->Option<&str>{self.data.get(key).map(|s|s.as_str())}pubfnremove(&mutself,key:&str)->Option<String>{self.data.remove(key)}}implDefaultforDataStore{fndefault()->Self{Self::new()}}/// Service for managing data operations.pubstructDataService{store:DataStore,}implDataService{pubfnnew()->Self{Self{store:DataStore::new(),}}pubfnstore_data(&mutself,key:String,value:String)->Result<()>{self.store.set(key,value)}pubfnretrieve_data(&self,key:&str)->Option<&str>{self.store.get(key)}pubfndelete_data(&mutself,key:&str)->Option<String>{self.store.remove(key)}}implDefaultforDataService{fndefault()->Self{Self::new()}}}pubmoderrors{usethiserror::Error;#[derive(Error, Debug)]pubenumError{#[error("Authentication error: {0}")]Authentication(String),#[error("Data error: {0}")]Data(String),#[error("Validation error: {0}")]Validation(String),#[error("IO error: {0}")]Io(#[from]std::io::Error),}pubtypeResult<T>=std::result::Result<T,Error>;}pubmodutils{usestd::time::{Duration,Instant};/// Measures the execution time of a function.pubfnmeasure_time<F,R>(f:F)->(R,Duration)whereF:FnOnce()->R,{letstart=Instant::now();letresult=f();letduration=start.elapsed();(result,duration)}/// Formats a duration as a human-readable string.pubfnformat_duration(duration:Duration)->String{ifduration.as_secs()>0{format!("{:.2}s",duration.as_secs_f64())}else{format!("{:.2}ms",duration.as_millis())}}}#[cfg(feature = "async")]pubmodasync_utils{usetokio::time::{sleep,Duration};/// Performs an async operation with a delay.pubasyncfnasync_operation()->Result<(),Box<dynstd::error::Error>>{sleep(Duration::from_millis(100)).await;Ok(())}}#[cfg(feature = "serde")]pubmodserialization{useserde::{Deserialize,Serialize};#[derive(Debug, Serialize, Deserialize)]pubstructSerializableData{pubid:u64,pubname:String,pubvalue:f64,}implSerializableData{pubfnto_json(&self)->Result<String,serde_json::Error>{serde_json::to_string(self)}pubfnfrom_json(json:&str)->Result<Self,serde_json::Error>{serde_json::from_str(json)}}}