Expand description
Cache key types and construction.
This module provides types for building and representing cache keys:
CacheKey- The complete cache key with prefix, version, and partsKeyPart- A single key-value component of a cache keyKeyParts- Builder for accumulating key parts during extraction
§Key Structure
Cache keys have three components:
- Prefix - Optional namespace for grouping related keys
- Version - Numeric version for cache invalidation
- Parts - List of key-value pairs extracted from requests
§Format
When serialized to string, keys follow this format:
{prefix}:v{version}:key1=value1&key2=value2
- Prefix is omitted if empty
- Version is omitted if zero
use hitbox_core::{CacheKey, KeyPart};
// Full format: prefix + version + parts
let key = CacheKey::new("api", 1, vec![KeyPart::new("id", Some("42"))]);
assert_eq!(format!("{}", key), "api:v1:id=42");
// No prefix
let key = CacheKey::new("", 2, vec![KeyPart::new("id", Some("42"))]);
assert_eq!(format!("{}", key), "v2:id=42");
// No version (v0)
let key = CacheKey::new("cache", 0, vec![KeyPart::new("id", Some("42"))]);
assert_eq!(format!("{}", key), "cache:id=42");
// No prefix, no version
let key = CacheKey::new("", 0, vec![KeyPart::new("id", Some("42"))]);
assert_eq!(format!("{}", key), "id=42");
// KeyPart with None value (key only, no value)
let key = CacheKey::new("", 0, vec![KeyPart::new("flag", None::<&str>)]);
assert_eq!(format!("{}", key), "flag");
// Mixed: Some and None values
let key = CacheKey::new("api", 1, vec![
KeyPart::new("method", Some("GET")),
KeyPart::new("cached", None::<&str>),
]);
assert_eq!(format!("{}", key), "api:v1:method=GET&cached");§Performance
CacheKey uses Arc internally for cheap cloning - copying a key
only increments a reference count rather than cloning all parts.
KeyPart uses SmolStr for small string optimization - short
strings (≤23 bytes) are stored inline without heap allocation.