Examples & Tutorials
Practical examples and real-world usage patterns for CRDTosphere
Example Categories
Domain Applications
Real-world examples for automotive, robotics, IoT, and industrial
View Examples →Basic Examples
Distributed Event Counter
BasicTrack events across multiple nodes with a grow-only counter.
Add to Cargo.toml
[dependencies]
crdtosphere = "0.1.0"
Rust Code
use crdtosphere::prelude::*;
fn main() -> Result<(), CRDTError> {
// Create counters on different nodes
let mut node1_counter = GCounter::<DefaultConfig>::new(1);
let mut node2_counter = GCounter::<DefaultConfig>::new(2);
// Each node tracks local events
node1_counter.increment()?; // Page view
node1_counter.increment()?; // Button click
node2_counter.increment()?; // API call
node2_counter.increment()?; // User action
node2_counter.increment()?; // Background task
println!("Node 1 events: {}", node1_counter.value());
println!("Node 2 events: {}", node2_counter.value());
// Merge counters to get total events
node1_counter.merge(&node2_counter)?;
println!("Total events: {}", node1_counter.value());
Ok(())
}
Expected Output:
Node 1 events: 2 Node 2 events: 3 Total events: 5
Configuration Management
BasicManage distributed configuration with last-writer-wins semantics.
Add to Cargo.toml
[dependencies]
crdtosphere = "0.1.0"
Rust Code
use crdtosphere::prelude::*;
fn main() -> Result<(), CRDTError> {
// Configuration registers on different services
let mut service1_config = LWWRegister::<String, DefaultConfig>::new(1);
let mut service2_config = LWWRegister::<String, DefaultConfig>::new(2);
// Service 1 sets initial configuration
service1_config.set("debug_mode=false".to_string(), 1000)?;
// Service 2 updates configuration later
service2_config.set("debug_mode=true".to_string(), 2000)?;
// Merge configurations - latest timestamp wins
service1_config.merge(&service2_config)?;
if let Some(config) = service1_config.get() {
println!("Current config: {}", config);
}
Ok(())
}
Expected Output:
Current config: debug_mode=true
Device Capability Registry
BasicTrack device capabilities using a grow-only set.
Add to Cargo.toml
[dependencies]
crdtosphere = "0.1.0"
Rust Code
use crdtosphere::prelude::*;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Capability {
WiFi,
Bluetooth,
GPS,
Camera,
Accelerometer,
}
fn main() -> Result<(), CRDTError> {
// Device capability sets
let mut mobile_device = GSet::<Capability, DefaultConfig>::new();
let mut iot_device = GSet::<Capability, DefaultConfig>::new();
// Mobile device capabilities
mobile_device.insert(Capability::WiFi)?;
mobile_device.insert(Capability::Bluetooth)?;
mobile_device.insert(Capability::GPS)?;
mobile_device.insert(Capability::Camera)?;
// IoT device capabilities
iot_device.insert(Capability::WiFi)?;
iot_device.insert(Capability::Accelerometer)?;
// Check capabilities
println!("Mobile has GPS: {}", mobile_device.contains(&Capability::GPS));
println!("IoT has GPS: {}", iot_device.contains(&Capability::GPS));
// Merge to get all capabilities in network
mobile_device.merge(&iot_device)?;
println!("Total capabilities: {}", mobile_device.len());
Ok(())
}
Expected Output:
Mobile has GPS: true IoT has GPS: false Total capabilities: 5
Distributed Configuration Store with Remove
BasicManage distributed key-value configuration with insert, update, and remove operations.
Add to Cargo.toml
[dependencies]
crdtosphere = "0.1.0"
Rust Code
use crdtosphere::prelude::*;
fn main() -> Result<(), CRDTError> {
// Configuration maps on different services
let mut service1_config = LWWMap::<String, String, DefaultConfig>::new(1);
let mut service2_config = LWWMap::<String, String, DefaultConfig>::new(2);
// Service 1 sets initial configuration
service1_config.insert("max_connections".to_string(), "100".to_string(), 1000)?;
service1_config.insert("timeout_ms".to_string(), "5000".to_string(), 1001)?;
service1_config.insert("debug_mode".to_string(), "false".to_string(), 1002)?;
println!("Service 1 initial config:");
for (key, value) in service1_config.iter() {
println!(" {}: {}", key, value);
}
println!("Config entries: {}", service1_config.len());
// Service 2 updates some configuration
service2_config.insert("max_connections".to_string(), "200".to_string(), 2000)?; // Newer
service2_config.insert("buffer_size".to_string(), "8192".to_string(), 2001)?; // New
// Merge configurations
service1_config.merge(&service2_config)?;
println!("\nAfter merge:");
for (key, value) in service1_config.iter() {
println!(" {}: {}", key, value);
}
// Remove debug mode (no longer needed)
let removed = service1_config.remove(&"debug_mode".to_string());
println!("\nRemoved debug_mode: {:?}", removed);
println!("Remaining capacity: {}", service1_config.remaining_capacity());
// Add new configuration in freed space
service1_config.insert("log_level".to_string(), "info".to_string(), 3000)?;
println!("\nFinal configuration:");
for (key, value) in service1_config.iter() {
println!(" {}: {}", key, value);
}
println!("Total entries: {}", service1_config.len());
Ok(())
}
Expected Output:
Service 1 initial config: max_connections: 100 timeout_ms: 5000 debug_mode: false Config entries: 3 After merge: max_connections: 200 timeout_ms: 5000 debug_mode: false buffer_size: 8192 Removed debug_mode: Some("false") Remaining capacity: 5 Final configuration: max_connections: 200 timeout_ms: 5000 buffer_size: 8192 log_level: info Total entries: 4
Atomic Operations
Concurrent Device Registration
AtomicMultiple threads registering device capabilities concurrently. - std is for demo
Add to Cargo.toml
[dependencies]
crdtosphere = { version = "0.1.0", features = ["hardware-atomic"] }
Rust Code
use crdtosphere::prelude::*;
use std::sync::Arc;
use std::thread;
fn main() -> Result<(), CRDTError> {
// Shared capability registry
let capabilities = Arc::new(GSet::<u32, DefaultConfig>::new());
let mut handles = vec![];
// Spawn multiple discovery threads
for thread_id in 0..4 {
let caps = Arc::clone(&capabilities);
let handle = thread::spawn(move || {
// Each thread discovers different capabilities
let capability = match thread_id {
0 => 1, // GPS
1 => 2, // WiFi
2 => 3, // Bluetooth
3 => 4, // Camera
_ => unreachable!(),
};
// Thread-safe insertion
caps.insert(capability).unwrap();
println!("Thread {} registered capability {}", thread_id, capability);
});
handles.push(handle);
}
// Wait for all threads
for handle in handles {
handle.join().unwrap();
}
println!("Total capabilities discovered: {}", capabilities.len());
Ok(())
}
Expected Output:
Thread 0 registered capability 1 Thread 1 registered capability 2 Thread 2 registered capability 3 Thread 3 registered capability 4 Total capabilities discovered: 4
Multi-Core Sensor Processing
AtomicProcess sensor data across multiple CPU cores with atomic coordination. - std is for demo
Add to Cargo.toml
[dependencies]
crdtosphere = { version = "0.1.0", features = ["hardware-atomic"] }
Rust Code
use crdtosphere::prelude::*;
use std::sync::Arc;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
fn get_timestamp() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64
}
fn main() -> Result<(), CRDTError> {
// Shared sensor data register
let sensor_data = Arc::new(LWWRegister::<f32, DefaultConfig>::new(1));
let mut handles = vec![];
// Multiple sensor processing cores
for core_id in 0..3 {
let data = Arc::clone(&sensor_data);
let handle = thread::spawn(move || {
// Simulate sensor reading processing
let reading = match core_id {
0 => 25.5, // Temperature sensor
1 => 60.2, // Humidity sensor
2 => 24.8, // Backup temperature
_ => unreachable!(),
};
// Atomic update with timestamp
let timestamp = get_timestamp() + core_id * 10;
data.set(reading, timestamp).unwrap();
println!("Core {} processed reading: {}", core_id, reading);
});
handles.push(handle);
}
// Wait for processing
for handle in handles {
handle.join().unwrap();
}
if let Some(final_reading) = sensor_data.get() {
println!("Final sensor value: {}", final_reading);
}
Ok(())
}
Expected Output:
Core 0 processed reading: 25.5 Core 1 processed reading: 60.2 Core 2 processed reading: 24.8 Final sensor value: 24.8
Domain Applications
Automotive Sensor Fusion
AutomotiveCombine data from multiple automotive sensors with safety prioritization.
Add to Cargo.toml
[dependencies]
crdtosphere = { version = "0.1.0", features = ["automotive"] }
Rust Code
use crdtosphere::prelude::*;
// Simulated automotive types
#[derive(Debug, Clone, PartialEq)]
enum BrakeStatus { Engaged, Released }
fn main() -> Result<(), CRDTError> {
// Safety-critical brake system data
let mut brake_ecu1 = LWWRegister::<BrakeStatus, DefaultConfig>::new(1);
let mut brake_ecu2 = LWWRegister::<BrakeStatus, DefaultConfig>::new(2);
// ECU 1 detects brake engagement (ASIL-D critical)
brake_ecu1.set(BrakeStatus::Engaged, 1000)?;
// ECU 2 has conflicting reading (lower priority)
brake_ecu2.set(BrakeStatus::Released, 1001)?;
// Merge with safety prioritization (latest wins)
brake_ecu1.merge(&brake_ecu2)?;
if let Some(status) = brake_ecu1.get() {
println!("Final brake status: {:?}", status);
// Safety check
match status {
BrakeStatus::Engaged => println!("✓ Safety system active"),
BrakeStatus::Released => println!("⚠ Brake system released"),
}
}
Ok(())
}
Expected Output:
Final brake status: Released ⚠ Brake system released
IoT Sensor Network
IoTCollect and aggregate data from distributed IoT sensors.
Add to Cargo.toml
[dependencies]
crdtosphere = { version = "0.1.0", features = ["iot"] }
Rust Code
use crdtosphere::prelude::*;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum SensorType { Temperature, Humidity, Pressure }
fn main() -> Result<(), CRDTError> {
// Sensor readings from different nodes
let mut node1_readings = LWWMap::<SensorType, f32, DefaultConfig>::new();
let mut node2_readings = LWWMap::<SensorType, f32, DefaultConfig>::new();
// Node 1 sensor readings
node1_readings.insert(SensorType::Temperature, 25.5, 1000)?;
node1_readings.insert(SensorType::Humidity, 60.0, 1001)?;
// Node 2 sensor readings (some overlap)
node2_readings.insert(SensorType::Temperature, 26.1, 1002)?; // Newer
node2_readings.insert(SensorType::Pressure, 1013.25, 1003)?;
// Merge sensor data
node1_readings.merge(&node2_readings)?;
println!("Aggregated sensor data:");
if let Some(temp) = node1_readings.get(&SensorType::Temperature) {
println!("Temperature: {}°C", temp);
}
if let Some(humidity) = node1_readings.get(&SensorType::Humidity) {
println!("Humidity: {}%", humidity);
}
if let Some(pressure) = node1_readings.get(&SensorType::Pressure) {
println!("Pressure: {} hPa", pressure);
}
println!("Total sensor types: {}", node1_readings.len());
Ok(())
}
Expected Output:
Aggregated sensor data: Temperature: 26.1°C Humidity: 60% Pressure: 1013.25 hPa Total sensor types: 3
Advanced Patterns
Multi-Value Conflict Resolution
AdvancedHandle concurrent updates with application-level conflict resolution.
Add to Cargo.toml
[dependencies]
crdtosphere = "0.1.0"
Rust Code
use crdtosphere::prelude::*;
fn main() -> Result<(), CRDTError> {
// Multi-value register for sensor calibration
let mut calibration1 = MVRegister::<f32, DefaultConfig>::new(1);
let mut calibration2 = MVRegister::<f32, DefaultConfig>::new(2);
let mut calibration3 = MVRegister::<f32, DefaultConfig>::new(3);
// Concurrent calibration updates
calibration1.set(1.05, 1000)?; // Node 1 calibration
calibration2.set(1.03, 1000)?; // Node 2 calibration (same timestamp)
calibration3.set(1.07, 1000)?; // Node 3 calibration (same timestamp)
// Merge all calibrations
calibration1.merge(&calibration2)?;
calibration1.merge(&calibration3)?;
// Get all concurrent values
let values: Vec<f32> = calibration1.values().cloned().collect();
println!("Concurrent calibration values: {:?}", values);
// Application-level conflict resolution: use average
let average = values.iter().sum::<f32>() / values.len() as f32;
println!("Resolved calibration (average): {:.3}", average);
// Alternative: use median
let mut sorted_values = values.clone();
sorted_values.sort_by(|a, b| a.partial_cmp(b).unwrap());
let median = sorted_values[sorted_values.len() / 2];
println!("Resolved calibration (median): {:.3}", median);
Ok(())
}
Expected Output:
Concurrent calibration values: [1.05, 1.03, 1.07] Resolved calibration (average): 1.050 Resolved calibration (median): 1.050
Running the Examples
📦 Clone the Repository
git clone https://github.com/vertexclique/crdtosphere.git
cd crdtosphere
🚀 Run Basic Examples
# Run basic counter example
cargo run --example basic_counter
# Run configuration management example
cargo run --example config_management
# Run device registry example
cargo run --example device_registry
🔧 Run Atomic Examples
# Run atomic examples with hardware-atomic feature
cargo run --example atomic_gset --features hardware-atomic
cargo run --example atomic_counter --features hardware-atomic
cargo run --example atomic_lww_register --features hardware-atomic
🌐 Run Domain Examples
# Run automotive examples
cargo run --example automotive_sensor_fusion --features automotive
# Run robotics examples
cargo run --example robot_swarm --features robotics
# Run IoT examples
cargo run --example iot_sensor_network --features iot
Next Steps
Learn CRDT Types
Explore the different CRDT types available and learn when to use each one.
View CRDT Types →