| Crates.io | reinhardt-utils |
| lib.rs | reinhardt-utils |
| version | 0.1.0-alpha.1 |
| created_at | 2026-01-23 04:35:31.275994+00 |
| updated_at | 2026-01-23 04:35:31.275994+00 |
| description | Utility functions aggregator for Reinhardt |
| homepage | |
| repository | https://github.com/kent8192/reinhardt-rs |
| max_upload_size | |
| id | 2063429 |
| size | 797,499 |
Common utilities and helper functions
Collection of utility functions and helpers used throughout the framework.
Includes date/time utilities, string manipulation, encoding/decoding, and other common operations.
Add reinhardt to your Cargo.toml:
[dependencies]
reinhardt = { version = "0.1.0-alpha.1", features = ["utils"] }
# Or use a preset:
# reinhardt = { version = "0.1.0-alpha.1", features = ["standard"] } # Recommended
# reinhardt = { version = "0.1.0-alpha.1", features = ["full"] } # All features
Then import utility features:
use reinhardt::utils::cache::{Cache, InMemoryCache};
use reinhardt::utils::logging::{Logger, LogLevel};
use reinhardt::utils::storage::{Storage, LocalStorage};
use reinhardt::utils::core::html::{escape, unescape};
Note: Utility features are included in the standard and full feature presets.
html module)escape(): Escapes HTML special characters (<, >, &, ", ')unescape(): Unescapes HTML entitiesconditional_escape(): Conditional escaping with autoescape flag supportescape_attr(): HTML attribute value escaping (handles newlines and tabs)strip_tags(): Removes HTML tagsstrip_spaces_between_tags(): Removes whitespace between tagstruncate_html_words(): Truncates by word count while preserving HTML tagsformat_html(): HTML generation via placeholder replacementSafeString: Safe string type for bypassing automatic escapingencoding module)urlencode(): URL encoding (spaces converted to +)urldecode(): URL decodingescapejs(): JavaScript string escaping (handles quotes, control characters, special characters)slugify(): URL slug generation (lowercase, special character removal, hyphen-separated)truncate_chars(): Truncate by character count (appends ...)truncate_words(): Truncate by word count (appends ...)wrap_text(): Wrap text at specified widthforce_str(): Safely convert byte sequences to UTF-8 stringsforce_bytes(): Convert strings to byte sequenceslinebreaks(): Convert line breaks to <br> tags (with paragraph support)linebreaksbr(): Convert line breaks to <br> tags (simple version)dateformat module)format(): Date/time formatting with format stringsY (4-digit), y (2-digit)m (zero-padded), n (no padding), F (full name), M (abbreviated)d (zero-padded), j (no padding), l (day name), D (day abbreviated)H (24-hour), h (12-hour), G/g (unpadded versions)i, Second: sA (uppercase), a (lowercase)shortcuts submodule)
iso_date(): YYYY-MM-DD formatiso_datetime(): YYYY-MM-DD HH:MM:SS formatus_date(): MM/DD/YYYY formateu_date(): DD/MM/YYYY formatfull_date(): "Monday, January 1, 2025" formatshort_date(): "Jan 1, 2025" formattime_24(): 24-hour format timetime_12(): 12-hour format time (with AM/PM)text module)capfirst(): Capitalize first letter of each wordtitle(): Title case conversion (first letter uppercase, rest lowercase)intcomma(): Add comma separators to integers (every 3 digits)floatcomma(): Add comma separators to floating-point numbersordinal(): Add ordinal suffixes (1st, 2nd, 3rd, 4th, etc.)pluralize(): Toggle singular/plural based on countljust(): Left-justify (right padding)rjust(): Right-justify (left padding)center(): Center-align (both-side padding)phone_format(): Convert 10/11-digit phone numbers to (XXX) XXX-XXXX formattimezone module)now(): Current UTC timelocaltime(): Current local timeto_local(): UTC to local timezone conversionto_utc(): Local to UTC conversionto_timezone(): Timezone conversion by IANA name (currently UTC only)make_aware_utc(): Convert naive datetime to UTC timezone-awaremake_aware_local(): Convert naive datetime to local timezone-awareis_aware(): Check for timezone information presence (always true in Rust)parse_datetime(): Parse ISO 8601 datetime stringsformat_datetime(): Output datetime in ISO 8601 format (RFC 3339)get_timezone_name_utc(): Get timezone name for UTC datetime
get_timezone_name_local(): Get timezone name for local datetime
Cache trait: Async-first trait for cache operations with generic type support
get<T>(): Retrieve values from cache with automatic deserializationset<T>(): Store values with optional TTL (Time-To-Live)delete(): Remove individual cache entrieshas_key(): Check cache key existenceclear(): Remove all entries from cacheget_many(): Batch retrieval of multiple cache keysset_many(): Batch storage of multiple valuesdelete_many(): Batch deletion of multiple keysincr(): Atomic increment for numeric valuesdecr(): Atomic decrement for numeric valuesInMemoryCache: Thread-safe in-memory cache backend
Arc<RwLock<HashMap>> for concurrent accesswith_default_ttl(): Configure default expiration timecleanup_expired(): Manual cleanup of expired entriesRedisCache: Redis-backed distributed cache (requires redis-backend feature)
ConnectionManager for efficient connection reusewith_default_ttl(): Default TTL configurationwith_key_prefix(): Namespace support for multi-tenant scenariosget_many, set_many, delete_many) for improved performanceincr, decr) using Redis native commandsnew(): Create builder with custom prefixwith_version(): Version-based cache invalidationbuild(): Generate prefixed and versioned keysbuild_many(): Batch key generation{prefix}:{version}:{key}CacheMiddleware: Automatic HTTP response caching
cache_get_only)cache_success_only)CacheMiddlewareConfigCacheMiddlewareConfig: Middleware configuration
with_default_timeout(): Set default cache durationwith_key_prefix(): Configure cache namespacecache_all_methods(): Enable caching for non-GET requestscache_all_responses(): Cache non-2xx responsesCacheService: High-level service with DI integration
reinhardt-diCacheKeyBuilder for automatic key prefixingget(), set(), delete() with automatic key buildingcache() methodkey_builder() methodRedisConfig: Redis configuration for DI (requires redis-backend feature)
new(): Custom Redis URL configurationlocalhost(): Quick localhost setupInjectable trait implementations:
InMemoryCache: Uses default singleton-based injectionCacheKeyBuilder: Custom default ("app" prefix, version 1)RedisCache: Injects with RedisConfig dependencyCacheService: Composes cache and key builder via DIredis-backend: Enable Redis support (optional dependency)
memcached-backend: Enable Memcached support (optional dependency)
all-backends: Enable all backend implementations
Logger struct with warning level loggingLoggerHandle: Wrapper around Arc<Logger> for thread-safe logger accessinit_global_logging() for one-time setupget_logger(name) returns LoggerHandle for retrieving named loggersonce_cellLoggingConfig: Main configuration containerHandlerConfig: Handler-specific settingsLoggerConfig: Logger-specific settingsescape_control_chars() utility for safe log outputRequireDebugTrue: Only log when debug mode is enabledRequireDebugFalse: Only log when debug mode is disabledrepr_params(): Truncate arrays, objects, and nested structurestruncate_param(): Truncate individual string valuesReprParamsConfig: Configurable truncation behavioremit_warning(): Quick warning emissionattach_memory_handler(): Easy test handler attachmentAuthenticationFailed, AuthorizationFailed, InvalidTokenRateLimitExceeded, SuspiciousActivity, CsrfViolationInvalidInput, AccessDenied, DisallowedHostUsage Example:
use reinhardt::utils::logging::security::{SecurityLogger, SecurityError};
let logger = SecurityLogger::new();
// Log authentication events
logger.log_auth_event(true, "user@example.com"); // INFO level
logger.log_auth_event(false, "attacker@evil.com"); // WARNING level
// Log security errors
logger.log_security_error(&SecurityError::CsrfViolation); // ERROR level
// Log CSRF violation with details
logger.log_csrf_violation("http://evil.com");
// Log rate limit exceeded
logger.log_rate_limit_exceeded("192.168.1.1", 100);
// Log suspicious file operations
logger.log_suspicious_file_operation("delete", Path::new("/etc/passwd"));
// Log disallowed host access
logger.log_disallowed_host("malicious.com");
Log Level Mapping:
| Event | Log Level |
|---|---|
| Authentication success | INFO |
| Authentication failure | WARNING |
| CSRF violation | ERROR |
| Rate limit exceeded | WARNING |
| Authorization failure | WARNING |
| Suspicious activity | ERROR |
Static File Configuration (StaticFilesConfig)
STATICFILES_DIRSStorage Backends (Storage trait)
FileSystemStorage - Local file system storageMemoryStorage - In-memory storage for testingStatic File Finder (StaticFilesFinder)
find_all() - Recursively discover all static files across configured directoriesHashed File Storage (HashedFileStorage)
Manifest System (ManifestStaticFilesStorage)
Media Asset Management (Media, HasMedia)
<link> and <script> tagsStatic File Handler (StaticFileHandler)
mime_guessStaticError and StaticResult types["index.html"]) via with_index_files()If-None-Match headershandler.rs (StaticFile::etag() method)Configuration Validation (checks module)
static.E001 - STATIC_ROOT not setstatic.E002 - STATIC_ROOT in STATICFILES_DIRSstatic.E003 - STATIC_URL is emptystatic.E004 - STATICFILES_DIRS entry is not a directorystatic.W001 - STATIC_ROOT is subdirectory of STATICFILES_DIRSstatic.W002 - STATIC_URL doesn't start with '/'static.W003 - STATIC_URL doesn't end with '/'static.W004 - STATICFILES_DIRS is emptystatic.W005 - Directory doesn't existstatic.W006 - Duplicate STATICFILES_DIRS entriesstatic.W007 - MEDIA_URL doesn't start with '/'static.W008 - MEDIA_URL doesn't end with '/'static.W009 - MEDIA_URL prefix conflict with STATIC_URLHealth Check System (health module)
async_traitCacheHealthCheck - Cache-related health checksDatabaseHealthCheck - Database-related health checksMetrics Collection (metrics module)
RequestTimer)RequestMetrics)MetricsCollector)Middleware (StaticFilesMiddleware)
Dependency Resolution (DependencyGraph)
collectstatic Command (implemented in reinhardt-commands)
GZip Compression (implemented in reinhardt-middleware)
Brotli Compression (implemented in reinhardt-middleware)
Cache-Control Header Management
CDN Integration
Advanced Storage Backends (storage module)
S3Storage - S3-compatible storage backend (AWS S3, MinIO, LocalStack)
AzureBlobStorage - Azure Blob Storage backend
GcsStorage - Google Cloud Storage backend
StorageRegistry - Custom storage backend registration system
Pages/SSR Integration (template_integration module)
TemplateStaticConfig - Configuration for static file generation in SSR contextsFile Processing Pipeline (processing module)
processing (default: disabled)Development Server Features (dev_server module)
notify cratedev-server (default: disabled)Advanced File Processing
image-optimizationsource-mapscompressionAdvanced Minification (OXC-powered)
Variable renaming (mangling) - Feature flag: advanced-minification
Dead code elimination
Production-grade compression
Console.log removal option
Debugger statement removal
with_content_type, with_checksum)Re-exports of commonly used types for convenient importing