Expand description
§Gladius - High-Performance Typing Trainer Library
Gladius is a comprehensive Rust library for building typing trainer applications. It provides real-time typing analysis, flexible rendering systems, and detailed performance statistics with a focus on accuracy, performance, and ease of use.
§Quick Start
use gladius::TypingSession;
// Create a typing session
let mut session = TypingSession::new("Hello, world!").unwrap();
// Process user input
while let Some((char, result)) = session.input(Some('H')) {
println!("Typed '{}': {:?}", char, result);
break; // Just for demo
}
// Get progress and statistics
println!("Progress: {:.1}%", session.completion_percentage());
println!("WPM: {:.1}", session.statistics().measurements.last()
.map(|m| m.wpm.raw).unwrap_or(0.0));§Key Features
§🚀 High Performance
- Fast character processing - Amortized O(1) keystroke handling
- O(1) word lookups - Efficient character-to-word mapping
- Optimized statistics - Welford’s algorithm for numerical stability
- Memory efficient - Minimal allocations during typing
§📊 Comprehensive Statistics
- Words per minute (raw, corrected, actual)
- Input per minute (raw, actual)
- Accuracy percentages (raw, actual)
- Consistency analysis with standard deviation
- Detailed error tracking by character and word
- Real-time measurements at configurable intervals
§🎯 Flexible Rendering
- Character-level rendering with typing state information
- Line-based rendering with intelligent word wrapping
- Cursor position tracking across line boundaries
- Unicode support for international characters and emojis
- Generic renderer interface for any UI framework
§⚙️ Configurable Behavior
- Measurement intervals for statistics collection
- Line wrapping options (word boundaries vs. character wrapping)
- Newline handling (respect or ignore paragraph breaks)
- Performance tuning for different use cases
§Architecture Overview
Gladius is built with a modular architecture where each component has a specific responsibility:
graph TB
A[TypingSession
Coordinator] --> B[Buffer
Text Storage]
A --> C[Input Handler
Keystroke Processing]
A --> D[Statistics Tracker
Performance Data]
A --> E[Config
Runtime Settings]
F[Your App
UI Layer] --> A
A --> G[Render System
Display Interface]
G --> H[Character Rendering
Individual Chars]
G --> I[Line Rendering
Text Wrapping]
D --> J[Math Functions
WPM, Accuracy, etc.]
subgraph "Core Components"
B
C
D
E
end
subgraph "Rendering Pipeline"
G
H
I
end
§Core Modules
| Module | Purpose | Key Types |
|---|---|---|
session | Session coordination and main API | TypingSession |
buffer | Text storage and word/character management | Buffer |
input_handler | Keystroke processing and validation | InputHandler |
statistics | Performance data collection and analysis | Statistics, TempStatistics |
statistics_tracker | Real-time statistics coordination | StatisticsTracker |
render | Text display and line management | RenderingContext, LineContext |
math | Performance calculation algorithms | Wpm, Accuracy, Consistency |
config | Runtime behavior configuration | Configuration |
§Usage Examples
§Basic Typing Session
use gladius::TypingSession;
use gladius::CharacterResult;
let mut session = TypingSession::new("The quick brown fox").unwrap();
// Process typing input
match session.input(Some('T')) {
Some((ch, CharacterResult::Correct)) => println!("Correct: {}", ch),
Some((ch, CharacterResult::Wrong)) => println!("Wrong: {}", ch),
Some((ch, CharacterResult::Corrected)) => println!("Corrected: {}", ch),
Some((ch, CharacterResult::Deleted(state))) => println!("Deleted: {} (was {:?})", ch, state),
None => println!("No input processed"),
}§Custom Configuration
use gladius::{TypingSession, config::Configuration};
let config = Configuration {
measurement_interval_seconds: 0.5, // More frequent measurements
};
let session = TypingSession::new("Hello, world!")
.unwrap()
.with_configuration(config);§Character-level Rendering
use gladius::TypingSession;
let session = TypingSession::new("hello").unwrap();
let rendered: Vec<String> = session.render(|ctx| {
let cursor = if ctx.has_cursor { " |" } else { "" };
let state = match ctx.character.state {
gladius::State::Correct => "✓",
gladius::State::Wrong => "✗",
gladius::State::None => "·",
_ => "?",
};
format!("{}{}{}", ctx.character.char, state, cursor)
});§Line-based Rendering
use gladius::{TypingSession, render::LineRenderConfig};
let session = TypingSession::new("The quick brown fox jumps over the lazy dog").unwrap();
let config = LineRenderConfig::new(20).with_word_wrapping(false);
let lines: Vec<String> = session.render_lines(|line_ctx| {
Some(line_ctx.contents.iter()
.map(|ctx| ctx.character.char)
.collect())
}, config);
// Results in word-wrapped lines of ~20 characters each§Complete Session with Statistics
use gladius::{TypingSession, CharacterResult};
let mut session = TypingSession::new("rust").unwrap();
let text_chars = ['r', 'u', 's', 't'];
// Type the complete text
for ch in text_chars {
session.input(Some(ch));
}
// Get final statistics
if session.is_fully_typed() {
let stats = session.finalize();
println!("Final WPM: {:.1}", stats.wpm.raw);
println!("Accuracy: {:.1}%", stats.accuracy.raw);
println!("Total time: {:.2}s", stats.duration.as_secs_f64());
println!("Character errors: {:?}", stats.counters.char_errors);
}§Performance Characteristics
| Operation | Time Complexity | Notes |
|---|---|---|
| Character input | O(1) amortized, O(w) worst case | Usually constant, worst case when recalculating word state |
| Character lookup | O(1) | Direct vector indexing |
| Word lookup | O(1) | Pre-computed mapping |
| Statistics update | O(1) typical, O(m) when measuring | Most updates are constant, measurements scan history |
| Rendering | O(n) | Linear in text length |
| Line wrapping | O(n) with O(w) lookahead | Linear with word boundary lookahead |
| Session creation | O(n) | One-time text parsing |
§Thread Safety
Gladius types are not thread-safe by design for maximum performance. Each typing session should be used on a single thread. Multiple sessions can run concurrently on different threads.
§Memory Usage
- Text storage: O(n) where n is text length
- Statistics history: O(k) where k is number of measurements
- Input history: O(m) where m is number of keystrokes
- Word mapping: O(n) pre-computed character-to-word index
Memory usage is optimized for typing trainer use cases with efficient data structures and minimal allocations during active typing.
§Minimum Supported Rust Version (MSRV)
Gladius supports Rust 1.88.0 and later.
Re-exports§
pub use session::TypingSession;
Modules§
- buffer
- Buffer Module - Text Storage and Word/Character Management
- config
- Configuration Module - Runtime Behavior Settings
- input_
handler - Input Handler Module - Keystroke Processing and Validation
- math
- Math Module - Typing Performance Calculations
- render
- Render Module - Text Display and Line Management
- session
- Session Module - Complete Typing Session Management
- statistics
- Statistics Module - Typing Performance Data Collection and Analysis
- statistics_
tracker - Statistics Tracker Module - Session Timing and Statistics Coordination
Structs§
- Character
- Represents a single character in the text with its typing state
- Word
- Represents a word in the text with its boundaries and typing state
Enums§
- Character
Result - Result of processing a character input during typing
- State
- Represents the current typing state of a character or word