MoosicBox Time
A simple time abstraction library providing unified time access with support for both standard system time and simulated time for testing.
Features
- Time Abstraction: Unified
now()function that works with different time backends - Standard Time: Use system time for production scenarios
- Simulated Time: Controllable time simulation for testing and development
- Step Control: Manually advance simulated time in discrete steps
- Epoch Offset: Configurable time offset for simulation scenarios
- Thread Local State: Per-thread time simulation state management
Installation
Add this to your Cargo.toml:
[]
= "0.1.1"
# Choose your backend
= { = "0.1.1", = ["std"] }
# or for testing
= { = "0.1.1", = ["simulator"] }
Usage
Basic Time Access
use now;
use SystemTime;
Simulated Time (Testing)
use ;
Time Simulation Configuration
use ;
Real Time in Simulation Mode
use ;
Testing Time-Dependent Code
use ;
use Duration;
Environment Configuration
The simulator can be configured via environment variables:
# Set a specific epoch offset (milliseconds since Unix epoch)
# Set step multiplier (milliseconds per step)
# Run your application
API Reference
Universal Function
now()- ReturnsSystemTimefrom appropriate backend
Standard Backend (std feature)
- Uses
std::time::SystemTime::now()directly
Simulator Backend (simulator feature)
now()- Returns simulated time based on current stepreset_step()- Reset step counter to 0next_step()- Advance to next step and return new step numberset_step(step)- Set specific step numbercurrent_step()- Get current step numberreset_epoch_offset()- Generate new random epoch offsetepoch_offset()- Get current epoch offsetreset_step_multiplier()- Generate new random step multiplierstep_multiplier()- Get current step multiplierwith_real_time(f)- Execute function with real system time
Time Calculation
In simulator mode, time is calculated as:
time = UNIX_EPOCH + Duration::from_millis(epoch_offset + (step * step_multiplier))
- epoch_offset: Base time offset (randomized or from environment)
- step: Current step counter (controlled by your code)
- step_multiplier: Milliseconds per step (randomized or from environment)
Features
std- Enable standard system time backendsimulator- Enable time simulation backend
Use Cases
- Production: Use
stdfeature for normal time operations - Testing: Use
simulatorfeature for deterministic time testing - Development: Use
simulatorfeature to test time-dependent logic - Benchmarking: Control time advancement for consistent measurements
Thread Safety
Each thread maintains its own simulation state (step, epoch offset, step multiplier) using thread-local storage.