1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! # 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
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │ 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 (32 B) + Cached Hash + Borrow<str> Lookup │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## 🚀 Quick Start
//!
//! Add to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! domain-key = { version = "0.5.1", features = ["fast"] }
//! ```
//!
//! Define a domain and create keys:
//!
//! ```rust
//! 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!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! 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());
//! # Ok(())
//! # }
//! ```
//!
//! ## Identifier Types
//!
//! domain-key provides four 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`) |
//! | [`Ulid<D>`] | `ulid::Ulid` | Prefixed ULIDs (16 bytes, `Copy`, feature `ulid`) |
//!
//! ```rust
//! 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
//!
//! ```toml
//! # 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
//!
//! ```bash
//! # 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** |
//! | Struct Size | 40 bytes | 32 bytes | **-20% memory** |
//! | `HashMap` lookup | by Key | by `&str` | **zero-alloc via `Borrow<str>`** |
//!
//! ## 📖 Advanced Examples
//!
//! ### Performance-Optimized Usage
//!
//! ```rust
//! 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>;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // 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
//! # Ok(())
//! # }
//! ```
//!
//! ## 🔧 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
//! - `ulid` — enables [`Ulid<D>`] prefixed ULID identifiers and [`UlidDomain`]
//! - `ulid-monotonic` — enables [`MonotonicUlidGenerator`] (requires `ulid`, hence `std`)
//!
//! ### 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
// ============================================================================
// EXTERNAL DEPENDENCIES
// ============================================================================
extern crate alloc;
// ============================================================================
// COMPILE-TIME FEATURE VALIDATION
// ============================================================================
// Improved feature validation that allows testing with --all-features
// but warns about suboptimal configurations
compile_error!;
compile_error!;
compile_error!;
// ============================================================================
// INTERNAL MODULES
// ============================================================================
// IMPORTANT: Macros module must be declared but not re-exported with pub use
// because macros are automatically exported with #[macro_export]
// ============================================================================
// PUBLIC RE-EXPORTS
// ============================================================================
// Core types
pub use UlidDomain;
pub use UuidDomain;
pub use ;
pub use UlidParseError;
pub use UuidParseError;
pub use ;
pub use Id;
pub use Key;
pub use MonotonicUlidGenerator;
pub use Ulid;
pub use Uuid;
/// Error from [`MonotonicUlidGenerator::generate`](crate::MonotonicUlidGenerator::generate) when
/// ULID random bits would overflow within the same millisecond.
pub type UlidMonotonicError = MonotonicError;
// Helper types
pub use ;
pub use IntoKey;
// Utility functions
pub use ;
pub use *;
// Constants
pub use DEFAULT_MAX_KEY_LENGTH;
// Hidden re-exports for macro hygiene (so macros work without caller imports)
// Note: Macros are exported automatically by #[macro_export] in macros.rs
// They don't need to be re-exported here
// ============================================================================
// CONVENIENCE TYPE ALIASES
// ============================================================================
/// Result type for key operations
pub type KeyResult<T> = ;
// ============================================================================
// PRELUDE MODULE
// ============================================================================
/// Prelude module for convenient imports
///
/// This module re-exports the most commonly used types and traits, allowing
/// users to easily import everything they need with a single `use` statement.
///
/// # Examples
///
/// ```rust
/// use domain_key::prelude::*;
///
/// #[derive(Debug)]
/// struct MyDomain;
///
/// impl Domain for MyDomain {
/// const DOMAIN_NAME: &'static str = "my";
/// }
/// impl KeyDomain for MyDomain {}
///
/// type MyKey = Key<MyDomain>;
///
/// let key = MyKey::new("example")?;
/// # Ok::<(), KeyParseError>(())
/// ```