A Rust crate providing an sscanf-like macro (inverse of format!()), with near unlimited parsing capabilities
sscanf is originally a C function that takes a string, a format string with placeholders, and
several variables. It parses the input and writes matched values into those variables. In Rust,
this crate returns a tuple instead. You can think of it as reversing a call to format!():
// format: takes format string and values, returns String
let msg = format!;
assert_eq!;
// sscanf: takes string, format string and types, returns tuple
let parsed = sscanf!;
// parsed is Option<(&str, usize)>
assert_eq!;
// alternative syntax:
let parsed2 = sscanf!;
assert_eq!;
sscanf!() takes a format string like format!(), but instead of writing values into {} placeholders,
it extracts the values at those positions into the returned tuple.
If matching the format string fails, None is returned:
let msg = "Text that doesn't match the format string";
let parsed = sscanf!;
assert!;
Types in Placeholders:
The types can either be given as a separate parameter after the format string, or directly
inside the {} placeholder.
The first allows for autocomplete while typing, syntax highlighting and better compiler errors
generated by sscanf in case that the wrong types are given.
The second mirrors the captured identifiers in format strings.
This option has less helpful compiler errors on stable Rust, but is otherwise identical to the first.
More examples of the capabilities of sscanf:
use sscanf;
use NonZeroUsize;
let input = "<x=3, y=-6, z=6>";
let parsed = sscanf!;
assert_eq!;
let input = "Move to N36E21";
let parsed = sscanf!;
assert_eq!;
let input = "Escape literal { } as {{ and }}";
let parsed = sscanf!;
assert_eq!;
let input = "Indexing types: N36E21";
let parsed = sscanf!;
// output is in the order of the placeholders
assert_eq!;
let input = "A Sentence with Spaces. Another Sentence.";
// &str and String do the same, but String clones from the input string
// to take ownership instead of borrowing.
let = sscanf!.unwrap;
assert_eq!;
assert_eq!;
// Number format options
let input = "ab01 127 101010 1Z";
let parsed = sscanf!;
let = parsed.unwrap;
assert_eq!; // Hexadecimal
assert_eq!; // Octal
assert_eq!; // Binary
assert_eq!; // any radix (r36 = Radix 36)
assert_eq!;
let input = "color: #D4AF37";
// Number types take their size into account, and hexadecimal u8 can
// have at most 2 digits => only possible match is 2 digits each.
let = sscanf!.unwrap;
assert_eq!;
The input here is a &'static str, but it can be String, &str, &String, ...
Basically anything that auto-derefs to str without taking ownership. See input examples
for a few examples of possible inputs.
The parsing part of this macro has very few limitations, since it replaces the {} with a
Regular Expression that corresponds to that type.
For example:
charis just one character (regex".")stris any sequence of characters (regex".+?")- Numbers are any sequence of digits (regex
"[-+]?\d+")
And so on. The actual implementation for numbers tries to take the size of the type into account and some other details, but that is the gist of the parsing.
This means that any sequence of replacements is possible as long as the regex finds a
combination that works. In the char, usize, char, usize example above it manages to assign
the N and E to the chars because they cannot be matched by the usizes.
Format Options
All options are inside '{' '}' and after a :, so either as {<type>:<option>} or
as {:<option>}. Note: The type might still have a path that contains ::. Any double
colons are ignored and only single colons are used to separate the options.
Custom Regex:
{:/.../}: Match according to the regex between the//
For example:
let input = "random Text";
let parsed = sscanf!;
// regex [^m]+ matches anything that isn't an 'm'
// => stops at the 'm' in 'random'
assert_eq!;
The regex uses the same escaping logic as JavaScripts /.../ syntax,
meaning that the normal regex escaping with \d for digits etc. is in effect, with the addition
that any / need to be escaped as \/ since they are used to end the regex.
NOTE: You should use raw strings for a format string containing a regex, since otherwise you
need to escape any \ as \\:
use sscanf;
let input = "1234";
let parsed = sscanf!; // regex \d{2} matches 2 digits
let _ = sscanf!; // the same with a non-raw string
assert_eq!;
See trait AcceptsRegexOverride for types supporting this option and instructions for adding support to
custom types.
Radix Options:
Generally only work on primitive integer types (u8, ..., u128, i8, ..., i128, usize, isize).
x: hexadecimal Number (Digits 0-9 and a-f or A-F), optional prefix0xor0Xo: octal Number (Digits 0-7), optional prefix0oor0Ob: binary Number (Digits 0-1), optional prefix0bor0Br2-r36: any radix Number (Digits 0-9 and a-z or A-Z for higher radices)
If used alongside a #: makes the number require a prefix (0x, 0o, 0b).
A note on prefixes: r2, r8 and r16 match the same numbers as b, o and x respectively,
but without a prefix. Thus:
{:x}may have a prefix, matching numbers like0xaborab{:r16}has no prefix and would only matchab{:#x}must have a prefix, matching only0xab{:#r16}gives a compile error
Custom Types
sscanf works with most primitive Types from std as well as String by default. The
full list can be seen here: Implementations of FromScanf.
To add more types there are two options:
- Derive
FromScanffor your type (simple, readable, fool proof (mostly)) - Manually implement
FromScanfSimple(more flexible, more code) - Manually implement
FromScanffor your type (flexible, but requires more code)
The simplest option is to use derive:
// The derive macro
// additional traits for assert_eq below. Not required for sscanf
// Format string for the type, using the field names.
let parsed = sscanf!.unwrap;
assert_eq!;
Also works for enums:
let input = "Your file has not changed since your last visit!";
let parsed = sscanf!.unwrap;
assert!;
let input = "Your file received 325 additions and 15 deletions since your last visit!";
let parsed = sscanf!.unwrap;
assert!;
More details can be found in the trait FromScanf and derive FromScanf documentations.
Changelog
See Changelog.md
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.