Expand description
Β§domain-key π
High-performance, type-safe, domain-agnostic key system for Rust applications.
domain-key provides a flexible and efficient foundation for creating domain-specific keys with compile-time type safety, runtime validation, and extensive performance optimizations. This library focuses on zero-cost abstractions and maximum performance through feature-based optimization profiles.
Β§β¨ Key Features
- π Type Safety: Different key types cannot be mixed at compile time
- ποΈ High Performance: Up to 75% performance improvements through advanced optimizations
- π― Domain Agnostic: No built-in assumptions about specific domains
- πΎ Memory Efficient: Smart string handling with stack allocation for short keys
- π‘οΈ
DoSResistant: Optional protection againstHashDoSattacks - π§ Extensible: Easy to add new domains and validation rules
- π¦ Zero-Cost Abstractions: No runtime overhead for type separation
Β§ποΈ Architecture Overview
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β APPLICATION LAYER β
β Business Logic β Domain Models β API Endpoints β
βββββββββββββββββββ¬ββββββββββββββββββββ¬ββββββββββββββββββββββββββββ
β β
βΌ βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TYPE SAFETY LAYER β
β Key<UserDomain> β Key<SessionDomain> β Key<CacheDomain> β
βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PERFORMANCE LAYER β
β Stack Alloc β Caching β Specialized Ops β Thread-Local β
βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STORAGE LAYER β
β SmartString + Cached Hash + Cached Length + Optimizations β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββΒ§π Quick Start
Add to your Cargo.toml:
[dependencies]
domain-key = { version = "0.2", features = ["fast"] }Define a domain and create keys:
use domain_key::{Key, Domain, KeyDomain};
// 1. Define your domain
#[derive(Debug)]
struct UserDomain;
impl Domain for UserDomain {
const DOMAIN_NAME: &'static str = "user";
}
impl KeyDomain for UserDomain {
const MAX_LENGTH: usize = 32;
const TYPICALLY_SHORT: bool = true; // Optimization hint
}
// 2. Create a type alias
type UserKey = Key<UserDomain>;
// 3. Use it!
let user_key = UserKey::new("john_doe")?;
let composed_key = UserKey::from_parts(&["user", "123", "profile"], "_")?;
println!("Domain: {}", user_key.domain());
println!("Length: {}", user_key.len()); // O(1) with optimizations
println!("Key: {}", user_key.as_str());Β§Identifier Types
domain-key provides three typed identifier wrappers:
| Type | Storage | Use case |
|---|---|---|
Key<D> | SmartString | Human-readable keys with validation |
Id<D> | NonZeroU64 | Numeric database IDs (8 bytes, Copy) |
Uuid<D> | uuid::Uuid | UUID identifiers (16 bytes, Copy, feature uuid) |
use domain_key::prelude::*;
// Numeric IDs
define_id_domain!(UserIdDomain, "user");
id_type!(UserId, UserIdDomain);
let id = UserId::new(42).unwrap();
assert_eq!(id.get(), 42);
// Or use the shorthand:
define_id!(OrderIdDomain => OrderId);
let order = OrderId::new(1).unwrap();All three types are domain-typed: UserId and OrderId are incompatible
at compile time even though both wrap a NonZeroU64.
Β§Performance Features
Β§Feature-Based Optimization Profiles
# Maximum performance (modern CPUs with AES-NI)
features = ["fast"]
# DoS protection + good performance
features = ["secure"]
# Cryptographic security
features = ["crypto"]
# All optimizations enabled
features = ["fast", "std", "serde"]Β§Build for Maximum Performance
# Enable CPU-specific optimizations
RUSTFLAGS="-C target-cpu=native" cargo build --release --features="fast"Β§Performance Improvements
| Operation | Standard | Optimized | Improvement |
|---|---|---|---|
| Key Creation (short) | 100% | 128% | 28% faster |
| String Operations | 100% | 175% | 75% faster |
| Hash Operations | 100% | 140% | 40% faster |
| Length Access | O(n) | O(1) | Constant time |
Β§π Advanced Examples
Β§Performance-Optimized Usage
use domain_key::{Key, Domain, KeyDomain};
#[derive(Debug)]
struct OptimizedDomain;
impl Domain for OptimizedDomain {
const DOMAIN_NAME: &'static str = "optimized";
}
impl KeyDomain for OptimizedDomain {
const EXPECTED_LENGTH: usize = 16; // Optimization hint
const TYPICALLY_SHORT: bool = true; // Enable stack allocation
}
type OptimizedKey = Key<OptimizedDomain>;
// Basic optimized key creation
let user_key = OptimizedKey::new("user_12345")?;
let session_key = OptimizedKey::new("session_abc123")?;
// Batch operations with from_parts
let user_ids = vec![1, 2, 3, 4, 5];
let user_keys: Result<Vec<_>, _> = user_ids.iter()
.map(|&id| OptimizedKey::from_parts(&["user", &id.to_string()], "_"))
.collect();
let user_keys = user_keys?;
// Optimized operations for repeated use
let key = OptimizedKey::new("user_profile_settings_theme")?;
let parts: Vec<&str> = key.split('_').collect(); // Uses optimizations when availableΒ§π§ Feature Flags Reference
Β§Hash Algorithm Features (choose one for best results)
fast-GxHash(40% faster, requires modern CPU with AES-NI)secure-AHash(DoSprotection, balanced performance)crypto- Blake3 (cryptographically secure)- Default - Standard hasher (good compatibility)
Β§Identifier Features
uuidβ enablesUuid<D>typed UUID identifiersuuid-v4β enablesUuid::new()random UUID v4 generationuuid-v7β enablesUuid::now_v7()time-ordered generation
Β§Core Features
std- Standard library support (enabled by default)serde- Serialization support (enabled by default)no_std- No standard library (disables std-dependent features)
Β§π‘οΈ Security Considerations
domain-key provides multiple levels of security depending on your needs:
DoSProtection: Usesecurefeature forAHashwithDoSresistance- Cryptographic Security: Use
cryptofeature for Blake3 cryptographic hashing - Input Validation: Comprehensive validation pipeline with custom rules
- Type Safety: Compile-time prevention of key type mixing
- Memory Safety: Rustβs ownership system + additional optimizations
Re-exportsΒ§
pub use domain::UuidDomain;pub use domain::domain_info;pub use domain::DefaultDomain;pub use domain::Domain;pub use domain::DomainInfo;pub use domain::IdDomain;pub use domain::IdentifierDomain;pub use domain::KeyDomain;pub use domain::PathDomain;pub use error::UuidParseError;pub use error::ErrorCategory;pub use error::IdParseError;pub use error::KeyParseError;pub use id::Id;pub use key::Key;pub use uuid::Uuid;pub use key::KeyValidationInfo;pub use key::SplitCache;pub use key::SplitIterator;pub use validation::IntoKey;pub use utils::hash_algorithm;pub use utils::new_split_cache;pub use key::DEFAULT_MAX_KEY_LENGTH;pub use validation::*;
ModulesΒ§
- domain
- Domain trait and related functionality for domain-key
- error
- Error types and error handling for domain-key
- id
- Typed numeric identifier for domain-key
- key
- Core Key implementation for domain-key
- prelude
- Prelude module for convenient imports
- utils
- Utility functions and helper types for domain-key
- uuid
- Typed UUID identifier for domain-key
- validation
- Validation utilities and helper traits for domain-key
MacrosΒ§
- batch_
keys - Create multiple keys at once with error handling
- define_
domain - Define a key domain with minimal boilerplate
- define_
id - Define an Id domain and type alias in one step
- define_
id_ domain - Define an ID domain with minimal boilerplate
- define_
uuid - Define a Uuid domain and type alias in one step
- define_
uuid_ domain - Define a UUID domain with minimal boilerplate
- id_type
- Create an Id type alias
- key_
type - Create a key type alias
- static_
key - Create a validated static key
- test_
domain - Generate test cases for key domains
- uuid_
type - Create a Uuid type alias
Type AliasesΒ§
- KeyResult
- Result type for key operations