Parse
Parses invariant decimal text into the selected numeric type.
Module std.text
import std.text;Public declaration contracts and authored examples. A page can document several related symbols. Implementation bodies are excluded.
fn
pub const fn TryParse<T>(Text: str) -> Result<T, ParseError> where T: NumberParser, Copyable, DefaultableParses invariant decimal text into the selected numeric type. T: Supported numeric destination; all built-in integer and IEEE floating-point types are admitted. Text: UTF-8 view borrowed only for this call; no input storage is retained. Return: Exact value, InvalidSyntax, or OutOfRange; never allocates or logs. @details Integer grammar is [+-]?[0-9]+. Leading zeros are allowed, while whitespace, radix prefixes, separators and Unicode digits are rejected. Negative unsigned text, including -0, is OutOfRange. The first detected syntax or range failure is returned. Work is linear in the input length. Floating-point grammar and nearest-even rounding are documented in
Example
module example.integer_parsing;
from std.text import TryParse, ParseError;
fn Main() -> i32 {
switch TryParse<i128>("-170141183460469231731687303715884105728") {
case .Ok { Value = Value } => {
if Value != -170141183460469231731687303715884105728_i128 { return 1; }
}
case .Err { Error = _ } => return 2;
}
switch TryParse<u128>("340282366920938463463374607431768211455") {
case .Ok { Value = Value } => {
if Value != 340282366920938463463374607431768211455_u128 { return 3; }
}
case .Err { Error = _ } => return 4;
}
switch TryParse<u8>("256") {
case .Ok { Value = _ } => return 5;
case .Err { Error = Error } => { if Error != ParseError.OutOfRange { return 6; } }
}
switch TryParse<i32>(" 42") {
case .Ok { Value = _ } => return 7;
case .Err { Error = Error } => { if Error != ParseError.InvalidSyntax { return 8; } }
}
return 0;
}