BoundedStr: No-Std, Zero-Heap strings with compile-time constraints
BoundedStr are secure string types for Rust that implement the "parse, don't validate" approach. Parsing immediately converts raw data into types with guaranteed correctness (length, format), eliminating repeated checks in business logic.
Basic concept
Crate creates generalized string types with compile-time parameters: MIN, MAX, MAX_BYTES. The check takes place in new() or deserialization — success means full validity. Storing in [u8; MAX_BYTES] on the stack provides zero-heap and #![no_std] compatibility.
Key Features
-Compile-time constraints: MIN ≤ MAX ≤ MAX_BYTES are checked by the compiler.
-Runtime parsing: BoundedStr::new(&str) validates length/format, returns Result<Self, BoundedStrError>.
- Policies (Traits):
LengthPolicy:Bytes(by bytes, O(1)) orChars(Unicode characters, O(n)).
-FormatPolicy: AllowAll, AsciiOnly + expandable (e.g. AlphaNumeric).
-Security: debug_assert! in as_str(), features zeroize (zeroing at Drop), constant-time (ct_eq against timing attacks).
- Integration:
Deref<Target=str>,Display,FromStr,TryFrom<&str>,serdewith auto-parsing.
Usage
use ;
use Deserialize;
// Matrix spec-compliant types — showcase ALL crate features:
// 1. Bytes (O(1)) — Room IDs, technical strings
type RoomId = ;
// 2. Chars (Unicode) — usernames with Cyrillic/emoji
type Username = ;
// 3. Bytes + AsciiOnly — device IDs, technical strings
type DeviceId = ;
// 4. Passwords — short, zeroize-enabled
type Password = ;
// 5. JWT tokens — large buffer (2KiB)
type Token = ;
// 6. HTML content — large, auto heap (up to 64KiB)
type HtmlBody = ;
// JSON auto-validation! (parse, don't validate)
// Real usage — invalid JSON fails automatically!
let json = r#"{
"username": "alexey",
"device_id": "DEV123",
"password": "MySecurePass123",
"html_body": "<p>Matrix <b>rich content</b> up to 64KiB</p>"
}"#;
let req: = from_str;
// Short password or oversized HTML → serde fails instantly! No manual if-checks needed.
Cargo Features
[]
= { = "0.1", = ["serde", "zeroize", "constant-time"] }
-serde: Deserialization with parsing.
-zeroize: Auto-zeroing the buffer (passwords/tokens).
constant-time:ct_eq(&self, other).
Restrictions
-Chars — O(n) time.
-MAX_BYTES ≤ 4KiB (stack).
- No
Copy(large buffers).