95 lines
2.7 KiB
Plaintext
95 lines
2.7 KiB
Plaintext
#! @file real.sakura
|
|
#! @author John Christman (sorakatadzuma@gmail.com)
|
|
#! @copyright Malunal Studios, LLC.
|
|
#! @license MIT
|
|
#!
|
|
#! Contains the real trait, which the compiler gives every floating-point type.
|
|
|
|
module core;
|
|
|
|
|
|
#! A type of real numbers: `f32` or `f64`, or an alias of either.
|
|
#!
|
|
#! A type parameter bounded by `real` has what numbers have, as `numeric` and
|
|
#! `ordered` give, along with a zero value, and `as` to and from the other
|
|
#! numbers. It is what the functions of `std::math` ask of what they take, as
|
|
#! `math::sqrt<T>(x: T): T where T: real`. The compiler decides what is real, so
|
|
#! no other type can implement it.
|
|
pub trait real {}
|
|
|
|
|
|
#! Reads the text as a real number such as `42`, `-0.5`, `.25`, or `6.02e23`.
|
|
#! @param this The text to read, which may start with `-` or `+`, and may end
|
|
#! with an exponent: `e` or `E`, an optional sign, and digits.
|
|
#! @returns The 64-bit float nearest the number, halfway between two going to
|
|
#! the one whose last bit is zero, or why the text is not one. A number
|
|
#! too large for 64 bits is a failure, and one too small is zero.
|
|
pub def real::parse<T>(text: strview):
|
|
result<T, failure> where T : real
|
|
{
|
|
var at := 0u;
|
|
var neg := false;
|
|
if text.length > 0 {
|
|
neg = text[0] == '-';
|
|
at = (text[0] == '+' || neg) as uint;
|
|
}
|
|
|
|
# The digits, with at most one `.` among them.
|
|
val start := at;
|
|
var digits := 0u;
|
|
var dotted := false;
|
|
while at < text.length {
|
|
val byte := text[at];
|
|
if byte == '.' && !dotted {
|
|
dotted = true;
|
|
} else {
|
|
break if !byte.is_digit;
|
|
digits++;
|
|
}
|
|
at++;
|
|
}
|
|
|
|
return failure { $"`{text}` is not a number" }
|
|
if digits == 0;
|
|
|
|
# The exponent, which is held at a hundred thousand, far past where every number
|
|
# is too large or too small, so a long one cannot overflow it.
|
|
var exponent := 0;
|
|
val written := text.substr(start, at - start);
|
|
if at < text.length && (text[at] == 'e' || text[at] == 'E') {
|
|
at++;
|
|
|
|
var down := false;
|
|
if at < text.length {
|
|
down = text[at] == '-';
|
|
at += (text[at] == '+' || down) as uint;
|
|
}
|
|
|
|
val first := at;
|
|
while at < text.length && text[at].is_digit {
|
|
if exponent < 100000 {
|
|
exponent = exponent * 10 + (text[at].digit_value as i64);
|
|
}
|
|
at++;
|
|
}
|
|
|
|
return failure { $"`{text}` has a malformed exponent" }
|
|
if at == first;
|
|
|
|
if down {
|
|
exponent = -exponent;
|
|
}
|
|
}
|
|
|
|
return failure { $"`{text}` is not a number" }
|
|
if at != text.length;
|
|
|
|
return failure { $"`{text}` is too large for 64 bits" }
|
|
if decimal_digits::nearest(written, exponent)
|
|
is not some(result);
|
|
|
|
return neg
|
|
? -result as T
|
|
: result as T;
|
|
}
|