atoi

    Portable decimal byte-to-integer parsing with SIMD, prefix parsing, and 128-bit results, ported from atoi_simd

    atoi
    integer
    parsing
    simd
    atoi_simd
    Download zip
    Author
    Version
    0.1.0
    License
    MIT
    Last updated
    58 minutes ago
    Downloads
    2

    No dependencies

    #Checked examples

    ///|
    test "signed limits and prefix byte counts" {
    let minimum : Int64 = @atoi.parse(b"-9223372036854775808")
    assert_eq(minimum, -9223372036854775808L)
    let prefix : (UInt64, Int32) = @atoi.parse_prefix(
    b"+000000000000000000001234tail",
    skip_zeroes=true,
    skip_plus=true,
    )
    assert_eq(prefix, (1234UL, 25))
    }

    ///|
    test "exact 128-bit decimal output" {
    let maximum : @atoi.UInt128 = @atoi.parse(
    b"340282366920938463463374607431768211455",
    )
    assert_eq(maximum.to_words(), (0xFFFFFFFFFFFFFFFFUL, 0xFFFFFFFFFFFFFFFFUL))
    let minimum : @atoi.Int128 = @atoi.parse(
    b"-170141183460469231731687303715884105728",
    )
    assert_eq(minimum.to_string(), "-170141183460469231731687303715884105728")
    }

    Parse

    pub(open) trait Parse {
    fn parse_decimal(BytesView, positive_only~ : Bool, prefix~ : Bool, skip_zeroes~ : Bool, skip_plus~ : Bool, simd~ : Bool) -> (Self, Int) raise ParseError
    }

    A fixed-width decimal result supported by the generic parsing functions.

    Implemented for Byte, Int8, UInt16, Int16, UInt, Int, UInt64, Int64, UInt128, and Int128. Type annotations select the result type. Implementations must enforce their integer range before returning a value.
    impl Parse for Byte
    impl Parse for Int
    impl Parse for Int16
    impl Parse for Int64
    impl Parse for UInt
    impl Parse for UInt16
    impl Parse for UInt64

    ParseNeg

    pub(open) trait ParseNeg {
    fn parse_negative_decimal(BytesView, prefix~ : Bool, skip_zeroes~ : Bool, simd~ : Bool) -> (Self, Int) raise ParseError
    }

    A signed decimal result supported by the sign-free negative parsers.

    Implemented only for Int8, Int16, Int, Int64, and Int128, so an unsigned result cannot be requested from parse_neg or parse_prefix_neg.
    impl ParseNeg for Int
    impl ParseNeg for Int16
    impl ParseNeg for Int64

    ParseError

    pub(all) suberror ParseError {
    Empty
    Size(Int, BytesView)
    Overflow(BytesView)
    Invalid64(UInt64, Int, BytesView)
    Invalid128(UInt128, Int, BytesView)
    } derive(Eq,
    Debug
    )

    Decimal validation failures, retaining immutable snapshots of input views.

    Empty means no digit follows the optional sign, including an invalid first byte. Size(length, input) reports the observed digit prefix when it first exceeds a 64/128-bit digit budget; length includes skipped zeroes. Overflow(input) means a permitted-length prefix exceeds the result range. Invalid64(magnitude, index, input) and Invalid128(...) report a non-digit suffix in a complete parse, retaining the unsigned prefix magnitude.

    Stored input excludes an accepted sign and preserves its original byte view even when zeroes were skipped. index is relative to that stored view, not its backing buffer. Error precedence is size, overflow, then invalid suffix. No error mutates the input; retaining an error may retain its backing bytes.

    Int128

    pub struct Int128 {
    // private fields
    } derive(Eq,
    Debug
    )

    An immutable signed 128-bit result stored privately in two's complement.

    Values range from -170141183460469231731687303715884105728 to 170141183460469231731687303715884105727. Assignments are safe snapshots of immutable state; parsing supports the minimum value without signed overflow.
    impl Parse for Int128
    impl ParseNeg for Int128

    Int128::from_bits

    fn Int128::from_bits(bits : UInt128) -> Int128

    Interprets all 128 bits as a signed two's-complement value, without mutation. Every bit pattern is valid; the top bit of the high word is the sign bit.

    Int128::is_negative

    fn Int128::is_negative(self : Int128) -> Bool

    Reports whether the value is strictly negative, without mutation or failure. Zero has a clear sign bit and returns false.

    Int128::to_bits

    fn Int128::to_bits(self : Int128) -> UInt128

    Returns the exact two's-complement bit pattern as an immutable UInt128. Negative values retain their sign bit; this is not an absolute magnitude.

    Int128::to_string

    fn Int128::to_string(self : Int128) -> String

    Returns the exact signed decimal representation, including the minimum value. Positive values have no +; zero is "0". Formatting allocates a string and never changes the value or narrows it to a 64-bit or floating-point type.

    Int8

    pub struct Int8 {
    // private fields
    } derive(Eq,
    Debug
    )

    An immutable signed eight-bit parsing result in the range -128 through 127.

    MoonBit has no built-in signed eight-bit integer on the validated toolchain. The representation is private and only range-checked parsing constructs it. Shared assignments are safe because this type has no mutable state.
    impl Parse for Int8
    impl ParseNeg for Int8

    Int8::to_int

    fn Int8::to_int(self : Int8) -> Int

    Returns the exact signed value as MoonBit's 32-bit Int, without mutation. All possible Int8 values are representable and this conversion cannot fail.

    Int8::to_string

    fn Int8::to_string(self : Int8) -> String

    Returns the signed base-ten representation without leading zeroes or +. Zero is "0"; conversion allocates a string and never mutates the value.

    UInt128

    pub struct UInt128 {
    // private fields
    } derive(Eq,
    Debug
    )

    An immutable unsigned 128-bit result, represented privately by two words.

    Values range from zero to 340282366920938463463374607431768211455. Word access and decimal formatting are exact on all four supported backends; assignments share only immutable state and require no independent copy.
    impl Parse for UInt128

    UInt128::from_words

    fn UInt128::from_words(high~ : UInt64, low~ : UInt64) -> UInt128

    Constructs the exact unsigned value high * 2^64 + low from two words. Every word pair is valid. The new value is immutable and owns no byte view.

    UInt128::to_string

    fn UInt128::to_string(self : UInt128) -> String

    Returns the exact unsigned decimal representation without leading zeroes. Zero is "0". Formatting allocates strings but does not mutate this value; no arbitrary-precision dependency or backend-specific representation is used.

    UInt128::to_words

    fn UInt128::to_words(self : UInt128) -> (UInt64, UInt64)

    Returns (high, low) in decreasing significance, without changing the value. This exposes exact bits rather than a lossy floating-point conversion.

    parse

    fn[T : Parse] parse(data : BytesView, skip_zeroes? : Bool, skip_plus? : Bool, simd? : Bool) -> T raise ParseError

    Parses all of data as a decimal integer of the annotated result type.

    Signed types accept one leading -; unsigned types reject it, including -0. skip_plus=true permits one leading +. Only ASCII 0 through 9 are digits: whitespace, separators, radix prefixes, and Unicode digits are rejected. skip_zeroes=true permits unlimited leading zeroes for 64/128-bit results; otherwise their digit budgets are 19/20 and 39 respectively. Narrower results always permit unlimited leading zeroes and check overflow.

    Raises ParseError for an empty digit prefix, excessive size, overflow, or a non-digit suffix. Error indices are relative to the stored input view, which excludes an accepted sign. The immutable view is never materialized. simd=true requests vectors for complete sixteen-byte blocks on native and linear-memory Wasm; short inputs, Wasm GC, and JavaScript use scalar/SWAR. Leading-zero removal uses scalar/SWAR even when vectors are requested.

    test {
    let value : Int64 = @atoi.parse(b"-9223372036854775808")
    assert_eq(value, -9223372036854775808L)
    }

    parse_neg

    fn[T : ParseNeg] parse_neg(data : BytesView, skip_zeroes? : Bool, simd? : Bool) -> T raise ParseError

    Parses sign-free ASCII digits as a negative integer of a signed result type.

    A leading - or + is rejected. Zero returns zero; the minimum signed value is accepted without first converting its magnitude to a signed type. skip_zeroes, range/size failures, immutable views, and SIMD fallbacks match parse. The entire view must be digits; otherwise ParseError is raised.

    parse_pos

    fn[T : Parse] parse_pos(data : BytesView, skip_zeroes? : Bool, simd? : Bool) -> T raise ParseError

    Parses all of data as a nonnegative decimal integer, rejecting both signs.

    The annotated result may be signed or unsigned. Digits, range checks, leading-zero budgets, failures, view ownership, and SIMD fallback match parse. skip_zeroes permits unlimited leading zeroes for 64/128-bit types. No whitespace, sign, radix prefix, or suffix is accepted; failure raises ParseError without changing the input.

    parse_prefix

    fn[T : Parse] parse_prefix(data : BytesView, skip_zeroes? : Bool, skip_plus? : Bool, simd? : Bool) -> (T, Int) raise ParseError

    Parses a decimal prefix and returns its value and consumed byte count.

    Sign handling, leading-zero budgets, range checks, and SIMD fallback match parse. Consumption includes an accepted sign and every leading zero; the first non-digit and remaining suffix are excluded. At least one digit is required. The complete digit prefix is checked: overflow or excessive size raises ParseError rather than returning a truncated integer. No input is mutated or materialized, and indices are byte offsets.

    test {
    let result : (UInt64, Int32) = @atoi.parse_prefix(b"+123rest", skip_plus=true)
    assert_eq(result, (123UL, 4))
    }

    parse_prefix_neg

    fn[T : ParseNeg] parse_prefix_neg(data : BytesView, skip_zeroes? : Bool, simd? : Bool) -> (T, Int) raise ParseError

    Parses sign-free digits as a negative prefix and returns consumed bytes.

    The result type must be signed; both literal signs are rejected. Zero and the minimum signed value are accepted. Consumption includes skipped zeroes and excludes the first non-digit. An empty prefix, overflow, or excessive size raises ParseError. skip_zeroes, immutable view ownership, and SIMD fallback match parse_prefix; the entire digit prefix is range checked.

    parse_prefix_pos

    fn[T : Parse] parse_prefix_pos(data : BytesView, skip_zeroes? : Bool, simd? : Bool) -> (T, Int) raise ParseError

    Parses a sign-free nonnegative decimal prefix and returns consumed bytes.

    Both signs are rejected, including + and -0. The first non-digit ends the prefix, but an empty digit prefix, overflow, or excessive size raises ParseError. Consumption includes skipped zeroes. skip_zeroes, result ranges, immutable view ownership, and SIMD fallback match parse_prefix.