3 unstable releases
Uses new Rust 2024
| 0.2.1 | Dec 2, 2025 |
|---|---|
| 0.2.0 | Dec 2, 2025 |
| 0.1.0 | Dec 1, 2025 |
#1499 in Text processing
66KB
1.5K
SLoC
A safe, memory-safe Rust implementation of C's sscanf function.
This library provides format string parsing functionality similar to C's scanf family, but with Rust's safety guarantees - no buffer overflows, no undefined behavior.
Supported Format Specifiers
Integer Conversions
%d- Signed decimal integer%i- Signed integer with auto-detection (base 10, 8 for '0' prefix, 16 for '0x'/'0X' prefix)%o- Unsigned octal integer%u- Unsigned decimal integer%x,%X- Unsigned hexadecimal integer
Floating-Point Conversions
%f,%F,%e,%E,%g,%G,%a,%A- Floating-point number
Character/String Conversions
%c- Fixed number of characters (default 1)%s- Sequence of non-whitespace characters%[...]- Character set matching%[^...]- Inverted character set matching
Special Conversions
%n- Store number of characters consumed so far%%- Literal percent sign
Modifiers
Assignment Suppression
*- Suppresses assignment; conversion happens but result is discarded
Length Modifiers
hh- char (for integer conversions)h- short int (for integer conversions)l- long int (for integers), double (for floats)ll- long long int (for integer conversions)L- long double (for float conversions)j- intmax_t (for integer conversions)t- ptrdiff_t (for integer conversions)z- size_t (for integer conversions)
Field Width
- Decimal integer between
%and conversion specifier limits maximum bytes scanned
Example
use xj_scanf::{scanf_str, ScanValue};
let values = scanf_str("42 3.14 hello", "%d %f %s").unwrap();
assert_eq!(values.len(), 3);
Error Handling
Unlike C's sscanf which returns magic values, this implementation uses proper
Result types:
Ok((values, count))- Successful parse with assigned values and countErr(ScanError::Eof)- Input exhausted before first conversionErr(ScanError::MatchFailure)- Input doesn't match formatErr(ScanError::InvalidFormat)- Malformed format string
Safety
This implementation avoids all undefined behavior present in C's sscanf:
- No buffer overflows - all bounds are checked
- No null pointer issues - Rust's type system prevents this
- No type mismatches - values are returned as typed enums