🦀

Rust AI Coding

Memory-Safe Systems Programming with Autonomous Agents

Master memory-safe systems programming with syntax.ai's specialized Rust AI agents. Our autonomous programming system understands Rust's ownership model, borrowing checker, and zero-cost abstractions to deliver intelligent assistance for safe, high-performance applications.

From ownership and borrowing to WebAssembly compilation, our AI agents provide context-aware code generation that leverages Rust's guarantees of memory safety without sacrificing performance.

Rust Expertise Areas

Memory Safety

Ownership, borrowing, and lifetime management

Systems Programming

Operating systems, drivers, and embedded development

WebAssembly

High-performance web applications and WASM modules

Async Programming

Tokio, async/await, and concurrent programming

Performance

Zero-cost abstractions and optimization techniques

Cross-Platform

Multi-target compilation and platform-specific code

Example AI-Generated Rust Code

See how our AI agents generate memory-safe, high-performance Rust code:

// AI-Generated Production-Ready Async Web Service with Advanced Patterns
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{Mutex, RwLock};
use tokio::time::{Duration, Instant};
use serde::{Deserialize, Serialize};
use regex::Regex;
use once_cell::sync::Lazy;
use thiserror::Error;
use tracing::{info, instrument, warn};
use prometheus::{IntCounter, HistogramVec, Registry};
use governor::{Quota, RateLimiter, DefaultKeyedRateLimiter};
use std::num::NonZeroU32;

// Production-ready error handling with thiserror
#[derive(Error, Debug, Clone)]
pub enum UserError {
    #[error("Name cannot be empty")]
    EmptyName,
    #[error("Invalid email format")]
    InvalidEmail,
    #[error("Email already exists")]
    DuplicateEmail,
    #[error("User not found")]
    NotFound,
    #[error("Rate limit exceeded")]
    RateLimitExceeded,
}

#[derive(Error, Debug)]
pub enum DatabaseError {
    #[error("Connection failed: {0}")]
    Connection(String),
    #[error("Query failed: {0}")]
    Query(String),
}

// Compile-time email validation with regex
static EMAIL_REGEX: Lazy = Lazy::new(|| {
    Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap()
});

fn validate_email(email: &str) -> Result<(), UserError> {
    if email.trim().is_empty() {
        return Err(UserError::InvalidEmail);
    }
    if !EMAIL_REGEX.is_match(email) {
        return Err(UserError::InvalidEmail);
    }
    Ok(())
}

fn validate_name(name: &str) -> Result<(), UserError> {
    if name.trim().is_empty() {
        return Err(UserError::EmptyName);
    }
    Ok(())
}

// Enhanced data structures with better indexing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
    pub id: u64,
    pub name: String,
    pub email: String,
    pub created_at: Instant,
    pub updated_at: Option,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateUserRequest {
    pub name: String,
    pub email: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateUserRequest {
    pub name: Option,
    pub email: Option,
}

// Optimized repository with O(1) email lookups and observability
#[derive(Clone)]
pub struct UserRepository {
    users: Arc>>,
    email_index: Arc>>, // O(1) email -> user_id
    next_id: Arc>,
    metrics: RepositoryMetrics,
}

#[derive(Clone)]
struct RepositoryMetrics {
    create_counter: IntCounter,
    operation_duration: HistogramVec,
}

impl RepositoryMetrics {
    fn new(registry: &Registry) -> prometheus::Result {
        let create_counter = IntCounter::new(
            "users_created_total",
            "Total number of users created"
        )?;
        
        let operation_duration = HistogramVec::new(
            prometheus::HistogramOpts::new(
                "user_operation_duration_seconds",
                "Duration of user operations"
            ),
            &["operation"]
        )?;
        
        registry.register(Box::new(create_counter.clone()))?;
        registry.register(Box::new(operation_duration.clone()))?;
        
        Ok(Self {
            create_counter,
            operation_duration,
        })
    }
}

impl UserRepository {
    pub fn new(registry: &Registry) -> Result> {
        let metrics = RepositoryMetrics::new(registry)?;
        
        Ok(Self {
            users: Arc::new(RwLock::new(HashMap::new())),
            email_index: Arc::new(RwLock::new(HashMap::new())),
            next_id: Arc::new(Mutex::new(1)),
            metrics,
        })
    }
    
    #[instrument(skip(self), fields(user_email = %request.email))]
    pub async fn create_user(&self, request: CreateUserRequest) -> Result {
        let _timer = self.metrics.operation_duration
            .with_label_values(&["create_user"])
            .start_timer();
        
        // Validate input with proper error types
        validate_name(&request.name)?;
        validate_email(&request.email)?;
        
        // O(1) email duplicate check using index
        {
            let email_index = self.email_index.read().await;
            if email_index.contains_key(&request.email) {
                warn!("Duplicate email attempted: {}", request.email);
                return Err(UserError::DuplicateEmail);
            }
        }
        
        // Generate new ID with minimal lock scope
        let id = {
            let mut next_id = self.next_id.lock().await;
            let current_id = *next_id;
            *next_id += 1;
            current_id
        };
        
        let user = User {
            id,
            name: request.name.trim().to_string(),
            email: request.email.to_lowercase(), // Normalize email
            created_at: Instant::now(),
            updated_at: None,
        };
        
        // Atomic insert: both user and email index
        {
            let mut users = self.users.write().await;
            let mut email_index = self.email_index.write().await;
            
            users.insert(id, user.clone());
            email_index.insert(user.email.clone(), id);
        }
        
        self.metrics.create_counter.inc();
        info!("User created successfully: {} ({})", user.name, user.email);
        
        Ok(user)
    }
    
    #[instrument(skip(self))]
    pub async fn get_user(&self, id: u64) -> Result, DatabaseError> {
        let _timer = self.metrics.operation_duration
            .with_label_values(&["get_user"])
            .start_timer();
        
        let users = self.users.read().await;
        Ok(users.get(&id).cloned())
    }
    
    #[instrument(skip(self))]
    pub async fn get_user_by_email(&self, email: &str) -> Result, DatabaseError> {
        let normalized_email = email.to_lowercase();
        
        // O(1) lookup using email index
        let user_id = {
            let email_index = self.email_index.read().await;
            email_index.get(&normalized_email).copied()
        };
        
        match user_id {
            Some(id) => self.get_user(id).await,
            None => Ok(None),
        }
    }
    
    #[instrument(skip(self))]
    pub async fn update_user(&self, id: u64, request: UpdateUserRequest) -> Result {
        let _timer = self.metrics.operation_duration
            .with_label_values(&["update_user"])
            .start_timer();
        
        // Validate inputs if provided
        if let Some(ref name) = request.name {
            validate_name(name)?;
        }
        if let Some(ref email) = request.email {
            validate_email(email)?;
        }
        
        let mut users = self.users.write().await;
        let mut email_index = self.email_index.write().await;
        
        let user = users.get_mut(&id).ok_or(UserError::NotFound)?;
        
        // Handle email change with index update
        if let Some(new_email) = request.email {
            let normalized_email = new_email.to_lowercase();
            
            // Check if new email is already taken
            if email_index.contains_key(&normalized_email) && user.email != normalized_email {
                return Err(UserError::DuplicateEmail);
            }
            
            // Update email index
            email_index.remove(&user.email);
            email_index.insert(normalized_email.clone(), id);
            user.email = normalized_email;
        }
        
        if let Some(new_name) = request.name {
            user.name = new_name.trim().to_string();
        }
        
        user.updated_at = Some(Instant::now());
        
        info!("User updated: {} ({})", user.name, user.email);
        Ok(user.clone())
    }
    
    #[instrument(skip(self))]
    pub async fn list_users(&self, limit: usize, offset: usize) -> Result, DatabaseError> {
        let _timer = self.metrics.operation_duration
            .with_label_values(&["list_users"])
            .start_timer();
        
        let users = self.users.read().await;
        let mut user_list: Vec<_> = users.values().cloned().collect();
        
        // Sort by creation time (newest first)
        user_list.sort_by(|a, b| b.created_at.cmp(&a.created_at));
        
        // Apply pagination
        let end = std::cmp::min(offset + limit, user_list.len());
        let paginated = if offset < user_list.len() {
            user_list[offset..end].to_vec()
        } else {
            Vec::new()
        };
        
        Ok(paginated)
    }
    
    #[instrument(skip(self))]
    pub async fn delete_user(&self, id: u64) -> Result {
        let _timer = self.metrics.operation_duration
            .with_label_values(&["delete_user"])
            .start_timer();
        
        let mut users = self.users.write().await;
        let mut email_index = self.email_index.write().await;
        
        if let Some(user) = users.remove(&id) {
            email_index.remove(&user.email);
            info!("User deleted: {} ({})", user.name, user.email);
            Ok(true)
        } else {
            Ok(false)
        }
    }
}

// Enhanced API error types
#[derive(Error, Debug)]
pub enum ApiError {
    #[error("Resource not found")]
    NotFound,
    #[error("Bad request: {0}")]
    BadRequest(String),
    #[error("Internal server error: {0}")]
    InternalError(String),
    #[error("Rate limit exceeded")]
    TooManyRequests,
    #[error("Validation failed: {0}")]
    ValidationError(String),
}

impl From for ApiError {
    fn from(err: UserError) -> Self {
        match err {
            UserError::NotFound => ApiError::NotFound,
            UserError::RateLimitExceeded => ApiError::TooManyRequests,
            _ => ApiError::ValidationError(err.to_string()),
        }
    }
}

impl From for ApiError {
    fn from(err: DatabaseError) -> Self {
        ApiError::InternalError(err.to_string())
    }
}

// Rate-limited service wrapper
#[derive(Clone)]
pub struct RateLimitedUserService {
    inner: UserService,
    rate_limiter: Arc>,
}

impl RateLimitedUserService {
    pub fn new(service: UserService) -> Self {
        // 10 requests per minute per IP
        let quota = Quota::per_minute(NonZeroU32::new(10).unwrap());
        let rate_limiter = Arc::new(RateLimiter::keyed(quota));
        
        Self {
            inner: service,
            rate_limiter,
        }
    }
    
    #[instrument(skip(self))]
    pub async fn create_user(&self, client_ip: String, request: CreateUserRequest) -> Result {
        // Check rate limit
        self.rate_limiter
            .check_key(&client_ip)
            .map_err(|_| {
                warn!("Rate limit exceeded for IP: {}", client_ip);
                ApiError::TooManyRequests
            })?;
        
        self.inner.create_user(request).await
    }
    
    pub async fn get_user(&self, id: u64) -> Result {
        self.inner.get_user(id).await
    }
    
    pub async fn list_users(&self, limit: usize, offset: usize) -> Result, ApiError> {
        self.inner.list_users(limit, offset).await
    }
}

// Core service with enhanced error handling
#[derive(Clone)]
pub struct UserService {
    repository: UserRepository,
}

impl UserService {
    pub fn new(repository: UserRepository) -> Self {
        Self { repository }
    }
    
    #[instrument(skip(self))]
    pub async fn create_user(&self, request: CreateUserRequest) -> Result {
        self.repository.create_user(request).await.map_err(Into::into)
    }
    
    #[instrument(skip(self))]
    pub async fn get_user(&self, id: u64) -> Result {
        self.repository
            .get_user(id)
            .await?
            .ok_or(ApiError::NotFound)
    }
    
    #[instrument(skip(self))]
    pub async fn update_user(&self, id: u64, request: UpdateUserRequest) -> Result {
        self.repository.update_user(id, request).await.map_err(Into::into)
    }
    
    #[instrument(skip(self))]
    pub async fn list_users(&self, limit: usize, offset: usize) -> Result, ApiError> {
        self.repository.list_users(limit, offset).await.map_err(Into::into)
    }
    
    #[instrument(skip(self))]
    pub async fn delete_user(&self, id: u64) -> Result {
        self.repository.delete_user(id).await.map_err(Into::into)
    }
}

// Production-ready concurrent task processor
pub struct TaskProcessor 
where
    T: Send + Sync + 'static,
{
    sender: tokio::sync::mpsc::UnboundedSender,
    worker_count: usize,
}

impl TaskProcessor
where
    T: Send + Sync + 'static,
{
    pub fn new(worker_count: usize, processor: F) -> Self
    where
        F: Fn(T) -> Fut + Send + Sync + Clone + 'static,
        Fut: std::future::Future>> + Send,
    {
        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
        let receiver = Arc::new(Mutex::new(receiver));
        
        // Spawn multiple worker tasks
        for worker_id in 0..worker_count {
            let receiver = receiver.clone();
            let processor = processor.clone();
            
            tokio::spawn(async move {
                info!("Worker {} started", worker_id);
                
                loop {
                    let task = {
                        let mut recv = receiver.lock().await;
                        recv.recv().await
                    };
                    
                    match task {
                        Some(task) => {
                            if let Err(e) = processor(task).await {
                                warn!("Worker {} task failed: {}", worker_id, e);
                            }
                        }
                        None => {
                            info!("Worker {} shutting down", worker_id);
                            break;
                        }
                    }
                }
            });
        }
        
        Self {
            sender,
            worker_count,
        }
    }
    
    pub fn submit(&self, task: T) -> Result<(), String> {
        self.sender
            .send(task)
            .map_err(|_| "Task processor is closed".to_string())
    }
    
    pub fn worker_count(&self) -> usize {
        self.worker_count
    }
}

// Example usage with comprehensive error handling and observability
#[tokio::main]
async fn main() -> Result<(), Box> {
    // Initialize tracing
    tracing_subscriber::fmt::init();
    
    // Initialize metrics
    let registry = Registry::new();
    
    // Initialize repository and services
    let repository = UserRepository::new(®istry)?;
    let service = UserService::new(repository);
    let rate_limited_service = RateLimitedUserService::new(service);
    
    // Create task processor with error handling
    let processor = TaskProcessor::new(4, |user: User| async move {
        info!("Processing user: {} ({})", user.name, user.email);
        
        // Simulate some work
        tokio::time::sleep(Duration::from_millis(100)).await;
        
        // Simulate potential failure
        if user.name.len() < 2 {
            return Err("Name too short for processing".into());
        }
        
        Ok(())
    });
    
    // Create test users with proper error handling
    let users = vec![
        CreateUserRequest {
            name: "Alice Johnson".to_string(),
            email: "[email protected]".to_string(),
        },
        CreateUserRequest {
            name: "Bob Smith".to_string(),
            email: "[email protected]".to_string(),
        },
        CreateUserRequest {
            name: "Carol Davis".to_string(),
            email: "[email protected]".to_string(),
        },
    ];
    
    let mut created_users = Vec::new();
    
    for user_request in users {
        match rate_limited_service.create_user("127.0.0.1".to_string(), user_request).await {
            Ok(user) => {
                info!("Created user: {} (ID: {})", user.name, user.id);
                processor.submit(user.clone())?;
                created_users.push(user);
            }
            Err(e) => {
                warn!("Failed to create user: {}", e);
            }
        }
    }
    
    // Test pagination
    let page1 = rate_limited_service.list_users(2, 0).await?;
    info!("Page 1: {} users", page1.len());
    
    let page2 = rate_limited_service.list_users(2, 2).await?;
    info!("Page 2: {} users", page2.len());
    
    // Test user update
    if let Some(user) = created_users.first() {
        let update_request = UpdateUserRequest {
            name: Some("Alice Updated".to_string()),
            email: None,
        };
        
        match rate_limited_service.inner.update_user(user.id, update_request).await {
            Ok(updated_user) => {
                info!("Updated user: {}", updated_user.name);
            }
            Err(e) => {
                warn!("Failed to update user: {}", e);
            }
        }
    }
    
    // Give background tasks time to complete
    tokio::time::sleep(Duration::from_secs(2)).await;
    
    info!("Application completed successfully with {} workers", processor.worker_count());
    
    Ok(())
}
          

Rust-Specific AI Features

Memory Safety Mastery

  • Ownership and borrowing patterns for safe memory management
  • Lifetime annotations and reference management
  • Smart pointers (Box, Rc, Arc) for shared ownership
  • Zero-cost abstractions without runtime overhead

Concurrency & Async

  • Tokio runtime and async/await patterns
  • Thread-safe data structures with Arc and Mutex
  • Channel-based communication between tasks
  • Fearless concurrency without data races

Performance Optimization

  • Compile-time optimizations and inlining
  • SIMD and vectorization support
  • Profile-guided optimization techniques
  • WebAssembly compilation for web performance

Real-World Rust Benefits

Safety & Reliability

  • Memory safety: Eliminate segfaults, buffer overflows, and memory leaks
  • Thread safety: Prevent data races at compile time
  • Type safety: Catch errors before they reach production
  • Fearless refactoring: Compiler ensures correctness during changes

Performance Excellence

  • Zero-cost abstractions: High-level code with C-like performance
  • Predictable performance: No garbage collection pauses
  • Efficient compilation: Aggressive optimizations at compile time
  • Small binaries: Minimal runtime overhead

Get Started with Rust AI Coding

Transform your systems programming with AI agents that understand Rust's ownership model and safety guarantees. Our autonomous programming system helps you write fast, safe code without the traditional trade-offs.

Ready to experience memory-safe AI development? Start with a free trial and see how our specialized Rust agents can revolutionize your systems programming and performance-critical applications.

← Back to Languages ← Back to syntax.ai