#! @file integer.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the integer trait, which the compiler gives every integer type. module core; #! An integer type, signed or unsigned, of any width. #! #! A type parameter bounded by `integer` has what numbers have, as `numeric` and #! `ordered` give, along with bitwise operators, shifts, and indexing, and it is #! `ordinal`. The compiler decides what is an integer, so no other type can #! implement it. pub trait integer {} #! Reads the text as a signed 64-bit integer, in decimal or with a `0x`, `0o`, #! or `0b` prefix, where `_` may separate digits. #! @param this The text to read, which may start with `-` or `+`. #! @returns The integer, or why the text is not one. pub def integer::parse(text: strview): result where T : integer { var at := 0u; var neg := false; if text.length > 0 { neg = text[0] == '-'; at = (text[0] == '+' || neg) as uint; } var base := 10u; if text.length > at + 1 && text[at] == '0' { val marker := text[at + 1]; if marker == 'x' || marker == 'X' { base = 16; } else if marker == 'o' || marker == 'O' { base = 8; } else if marker == 'b' || marker == 'B' { base = 2; } if base != 10 { at += 2; } } return failure { $"`{text}` has no digits" } if at >= text.length; const signed := 0x8000000000000000u; const unsigned := 0x7FFFFFFFFFFFFFFFu; val limit := neg ? signed : unsigned; var magnitude := 0u; for byte in text[at:] { continue if byte == '_'; val digit := byte.digit_value; return failure { $"`{text}` is not a base {base} integer" } if digit >= base; return failure { $"`{text}` does not fit in 64 bits" } if magnitude > (limit - digit) / base; magnitude = magnitude * base + digit; } return neg ? (0 - magnitude) as T : magnitude as T; }