Skip to main content

Crate domain_key

Crate domain_key 

Source
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
  • πŸ›‘οΈ DoS Resistant: Optional protection against HashDoS attacks
  • πŸ”§ 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:

TypeStorageUse case
Key<D>SmartStringHuman-readable keys with validation
Id<D>NonZeroU64Numeric database IDs (8 bytes, Copy)
Uuid<D>uuid::UuidUUID 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

OperationStandardOptimizedImprovement
Key Creation (short)100%128%28% faster
String Operations100%175%75% faster
Hash Operations100%140%40% faster
Length AccessO(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 (DoS protection, balanced performance)
  • crypto - Blake3 (cryptographically secure)
  • Default - Standard hasher (good compatibility)

Β§Identifier Features

  • uuid β€” enables Uuid<D> typed UUID identifiers
  • uuid-v4 β€” enables Uuid::new() random UUID v4 generation
  • uuid-v7 β€” enables Uuid::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:

  • DoS Protection: Use secure feature for AHash with DoS resistance
  • Cryptographic Security: Use crypto feature 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