domain-key 0.1.1

High-performance, domain-driven, type-safe key system for Rust
Documentation
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
421
422
# domain-key ๐Ÿš€

**High-performance, type-safe, domain-driven key system for Rust applications**

[![Crates.io](https://img.shields.io/crates/v/domain-key.svg)](https://crates.io/crates/domain-key)
[![Documentation](https://docs.rs/domain-key/badge.svg)](https://docs.rs/domain-key)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Build Status](https://github.com/vanyastaff/domain-key/workflows/CI/badge.svg)](https://github.com/vanyastaff/domain-key/actions)
[![Rust Version](https://img.shields.io/badge/rust-1.75+-blue.svg)](https://www.rust-lang.org)

> Never mix up keys from different domains again! ๐ŸŽฏ

## โœจ What is domain-key?

domain-key brings **Domain-Driven Design** principles to key management in Rust. It provides compile-time guarantees that keys from different business domains cannot be accidentally mixed or compared, while delivering exceptional performance through advanced optimizations.

```rust
use domain_key::{Key, KeyDomain};

// Define your business domains
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct UserDomain;

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct OrderDomain;

impl KeyDomain for UserDomain {
    const DOMAIN_NAME: &'static str = "user";
}

impl KeyDomain for OrderDomain {
    const DOMAIN_NAME: &'static str = "order";
}

// Create domain-specific key types
type UserKey = Key<UserDomain>;
type OrderKey = Key<OrderDomain>;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Use them safely
    let user_id = UserKey::new("user_123")?;
    let order_id = OrderKey::new("order_456")?;

    // This won't compile! ๐Ÿ›ก๏ธ
    // let mixed = user_id == order_id; // Compile error!
    
    println!("User: {}", user_id.as_str());
    println!("Order: {}", order_id.as_str());
    Ok(())
}
```

## ๐ŸŽฏ 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
- **๐ŸŒ Cross-Platform**: Works on all major platforms including WebAssembly

## ๐Ÿš€ Quick Start

Add to your `Cargo.toml`:

```toml
[dependencies]
domain-key = "0.1"

# For maximum performance
domain-key = { version = "0.1", features = ["fast"] }

# For security-critical applications  
domain-key = { version = "0.1", features = ["secure"] }
```

Define a domain and create keys:

```rust
use domain_key::{Key, KeyDomain};

// 1. Define your domain
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct UserDomain;

impl KeyDomain for UserDomain {
    const DOMAIN_NAME: &'static str = "user";
    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());
# Ok::<(), domain_key::KeyParseError>(())
```

## ๐ŸŽ๏ธ 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"

# For Apple Silicon Macs
RUSTFLAGS="-C target-cpu=native -C target-feature=+aes,+neon" cargo build --release --features="fast"
```

### Performance Improvements

| Operation | Standard | Optimized | Improvement |
|-----------|----------|-----------|-------------|
| Key Creation (short) | 100ns | 72ns | **28% faster** |
| String Operations | 100% baseline | 175% | **75% faster** |
| Hash Operations | 25ns | 15ns | **40% faster** |
| Length Access | O(n) | O(1) | **Constant time** |
| Collection Lookup | 35ns | 21ns | **40% faster** |

## ๐Ÿ“– Advanced Examples

### E-commerce Domain
```rust
use domain_key::{Key, KeyDomain};

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct ProductDomain;

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct CartDomain;

impl KeyDomain for ProductDomain {
    const DOMAIN_NAME: &'static str = "product";
    const MAX_LENGTH: usize = 32;
}

impl KeyDomain for CartDomain {
    const DOMAIN_NAME: &'static str = "cart";
    const MAX_LENGTH: usize = 64;
}

type ProductKey = Key<ProductDomain>;
type CartKey = Key<CartDomain>;

// Use in your application
let product = ProductKey::new("laptop_dell_xps13")?;
let cart = CartKey::from_parts(&["cart", "user123", "session456"], "_")?;
# Ok::<(), domain_key::KeyParseError>(())
```

### Multi-tenant SaaS
```rust
use domain_key::{Key, KeyDomain, KeyParseError};
use std::borrow::Cow;

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct TenantDomain;

impl KeyDomain for TenantDomain {
    const DOMAIN_NAME: &'static str = "tenant";
    const HAS_CUSTOM_VALIDATION: bool = true;
    const HAS_CUSTOM_NORMALIZATION: bool = true;
    
    fn validate_domain_rules(key: &str) -> Result<(), KeyParseError> {
        if !key.starts_with("tenant_") {
            return Err(KeyParseError::domain_error(
                Self::DOMAIN_NAME,
                "Tenant keys must start with 'tenant_'"
            ));
        }
        Ok(())
    }
    
    fn normalize_domain(key: Cow<'_, str>) -> Cow<'_, str> {
        // Convert to lowercase for consistency
        if key.chars().any(|c| c.is_ascii_uppercase()) {
            Cow::Owned(key.to_ascii_lowercase())
        } else {
            key
        }
    }
}

type TenantKey = Key<TenantDomain>;

let tenant = TenantKey::new("TENANT_acme_corp")?;
assert_eq!(tenant.as_str(), "tenant_acme_corp"); // normalized
# Ok::<(), domain_key::KeyParseError>(())
```

### Advanced Validation
```rust
use domain_key::{Key, KeyDomain, KeyParseError};

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct EmailDomain;

impl KeyDomain for EmailDomain {
    const DOMAIN_NAME: &'static str = "email";
    const MAX_LENGTH: usize = 254;
    const HAS_CUSTOM_VALIDATION: bool = true;

    fn validate_domain_rules(key: &str) -> Result<(), KeyParseError> {
        if !key.contains('@') {
            return Err(KeyParseError::domain_error(
                Self::DOMAIN_NAME,
                "Email must contain @ symbol"
            ));
        }

        let parts: Vec<&str> = key.split('@').collect();
        if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() {
            return Err(KeyParseError::domain_error(
                Self::DOMAIN_NAME,
                "Invalid email format"
            ));
        }

        Ok(())
    }

    fn allowed_characters(c: char) -> bool {
        c.is_ascii_alphanumeric() || "@._+-".contains(c)
    }
}

type EmailKey = Key<EmailDomain>;

let email = EmailKey::new("user@example.com")?;
assert_eq!(email.as_str(), "user@example.com");

// This will fail validation
let invalid = EmailKey::new("not-an-email");
assert!(invalid.is_err());
# Ok::<(), domain_key::KeyParseError>(())
```

## ๐Ÿ”ง 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)

### Core Features

- `std` - Standard library support (enabled by default)
- `serde` - Serialization support (enabled by default)
- `no_std` - No standard library support

## ๐Ÿ›ก๏ธ 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

See [SECURITY.md](SECURITY.md) for detailed security information.

## ๐Ÿ“š Documentation

- **๐Ÿ“– [User Guide]docs/guide.md** - Comprehensive usage guide
- **๐ŸŽ“ [API Documentation]https://docs.rs/domain-key** - Complete API reference
- **๐Ÿš€ [Examples]examples/** - Real-world usage examples
- **๐Ÿ“‹ [Migration Guide]docs/migration.md** - Migrating from string keys
- **๐ŸŽ๏ธ [Performance Guide]docs/performance.md** - Optimization strategies
- **๐Ÿ”’ [Security Policy]SECURITY.md** - Security considerations and reporting

## ๐Ÿงช Testing

Run the comprehensive test suite:

```bash
# All tests with all features
cargo test --all-features

# Property-based tests
cargo test --features std,serde --release -- prop_

# Benchmarks
cargo bench --features fast

# Security audit
cargo audit
```

## ๐Ÿ“ˆ Benchmarks

```bash
# Run realistic benchmarks
cargo bench --features fast

# Memory usage analysis
cargo test --release memory_usage

# Cross-platform performance
cargo test --features fast --target wasm32-unknown-unknown
```

## ๐Ÿ”„ Migration from String Keys

### Before (String-based)
```rust
let user_id: String = "user_123".to_string();
let order_id: String = "order_456".to_string();

// Dangerous - no compile-time protection!
if user_id == order_id {
    // This could be a bug, but compiler won't catch it
}

let cache_key = format!("cache:{}:{}", user_id, order_id);
```

### After (domain-key)
```rust
type UserKey = Key<UserDomain>;
type OrderKey = Key<OrderDomain>;
type CacheKey = Key<CacheDomain>;

let user_id = UserKey::new("user_123")?;
let order_id = OrderKey::new("order_456")?;

// This won't compile - type safety!
// if user_id == order_id { } // Compile error!

let cache_key = CacheKey::from_parts(&[
    "cache", 
    user_id.as_str(), 
    order_id.as_str()
], ":")?;
# Ok::<(), domain_key::KeyParseError>(())
```

## ๐Ÿค Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

### Quick Development Setup

```bash
git clone https://github.com/vanyastaff/domain-key.git
cd domain-key

# Install development dependencies
rustup target add wasm32-unknown-unknown
cargo install cargo-audit cargo-hack

# Run tests
cargo test --all-features
cargo clippy --all-features -- -D warnings
cargo fmt
```

## ๐ŸŒŸ Platform Support

| Platform | Status | Hash Algorithm | Notes |
|----------|--------|---------------|-------|
| Linux x86_64 | โœ… Full | GxHash/AHash | Best performance with AES-NI |
| Windows x86_64 | โœ… Full | GxHash/AHash | Full feature support |
| macOS Intel | โœ… Full | GxHash/AHash | All features supported |
| macOS Apple Silicon | โœ… Full | GxHash/AHash | Requires explicit AES+NEON flags |
| WebAssembly | โœ… Core | DefaultHasher | no_std support |
| ARM64 Linux | โœ… Full | GxHash/AHash | Server deployments |
| ARM Embedded | โœ… Core | FNV-1a | no_std + no_alloc |

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™ Acknowledgments

- Inspired by Domain-Driven Design principles by Eric Evans
- Built on the excellent [`smartstring`]https://crates.io/crates/smartstring crate for memory efficiency
- Performance-focused hash algorithms from the Rust ecosystem:
  - [`ahash`]https://crates.io/crates/ahash for DoS-resistant hashing
  - [`gxhash`]https://crates.io/crates/gxhash for maximum performance
  - [`blake3`]https://crates.io/crates/blake3 for cryptographic security

## ๐Ÿ“Š Project Stats

- **Lines of Code**: ~3,000 (including comprehensive tests)
- **Test Coverage**: >95%
- **Documentation Coverage**: >98%
- **Benchmark Coverage**: 20+ realistic scenarios
- **no_std Support**: โœ…
- **MSRV**: Rust 1.75+
- **Platforms**: 7+ supported targets

---

**domain-key** - Because your keys should know their place in your domain! ๐Ÿ—๏ธ