Added README, added examples, and updated documentation.

This commit is contained in:
Alex Huszagh
2020-02-06 23:57:55 -06:00
parent fe3c784a0b
commit 28eff5d605
14 changed files with 794 additions and 208 deletions
+4
View File
@@ -0,0 +1,4 @@
/target
**/*.rs.bk
Cargo.lock
/build
+9
View File
@@ -1,4 +1,13 @@
[package]
authors = ["Alex Huszagh <ahuszagh@gmail.com>"]
categories = ["parsing", "no-std"]
description = "Float parsing conversion routines."
edition = "2018"
name = "minimal_lexical"
version = "0.0.1"
readme = "README.md"
repository = "https://github.com/Alexhuszagh/minimal-lexical"
[features]
default = ["std"]
std = []
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+23
View File
@@ -0,0 +1,23 @@
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+27
View File
@@ -0,0 +1,27 @@
minimal_lexical
===============
This is a minimal version of [rust-lexical](https://github.com/Alexhuszagh/rust-lexical), meant to allow efficient round-trip float parsing. This does not implement a correct float parser, however, it will be accurate for round-trip values.
# Getting Started
```rust
extern crate minimal_lexical;
// Let's say we want to parse "1.2345".
// First, we have an external parser parse all the significant digits
// into a u64 (`12345`), and then we have the exponent adjusted to
// the mantissa (`-4`, since the value is `12345e-4`). Finally,
// we store whether digits were truncated from the mantissa during
// parsing (false).
let float = minimal_lexical::parse_float::<f64>(12345, -4, false);
println!("float={:?}", float); // 1.235
```
# License
Lexical is dual licensed under the Apache 2.0 license as well as the MIT license. See the LICENCE-MIT and the LICENCE-APACHE files for the licenses.
# Contributing
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in lexical by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
+3 -1
View File
@@ -1,3 +1,5 @@
//! Cached powers trait for extended-precision floats.
use super::cached_float80;
use super::float::ExtendedFloat;
@@ -65,7 +67,7 @@ impl ModeratePathPowers {
// CACHED EXTENDED POWERS
/// Cached powers as a trait for a floating-point type.
pub(super) trait ModeratePathCache {
pub(crate) trait ModeratePathCache {
/// Get cached powers.
fn get_powers() -> &'static ModeratePathPowers;
}
+1 -150
View File
@@ -7,155 +7,6 @@
//! These values were calculated using Python, using the arbitrary-precision
//! integer to calculate exact extended-representation of each value.
//! These values are all normalized.
//!
//! This files takes ~ 26KB of storage.
//!
//! This file is mostly automatically generated, do not change values
//! manually, unless you know what you are doing. The script to generate
//! the values is as follows:
//!
//! ```text
//! import math
//! from collections import deque
//!
//! STEP_STR = "const BASE{0}_STEP: i32 = {1};"
//! SMALL_MANTISSA_STR = "const BASE{0}_SMALL_MANTISSA: [u64; {1}] = ["
//! SMALL_EXPONENT_STR = "const BASE{0}_SMALL_EXPONENT: [i32; {1}] = ["
//! LARGE_MANTISSA_STR = "const BASE{0}_LARGE_MANTISSA: [u64; {1}] = ["
//! LARGE_EXPONENT_STR = "const BASE{0}_LARGE_EXPONENT: [i32; {1}] = ["
//! SMALL_INT_STR = "const BASE{0}_SMALL_INT_POWERS: [u64; {1}] = {2};"
//! BIAS_STR = "const BASE{0}_BIAS: i32 = {1};"
//! EXP_STR = "// {}^{}"
//! POWER_STR = """pub(crate) const BASE{0}_POWERS: ModeratePathPowers<u64> = ModeratePathPowers {{
//! small: ExtendedFloatArray {{ mant: &BASE{0}_SMALL_MANTISSA, exp: &BASE{0}_SMALL_EXPONENT }},
//! large: ExtendedFloatArray {{ mant: &BASE{0}_LARGE_MANTISSA, exp: &BASE{0}_LARGE_EXPONENT }},
//! small_int: &BASE{0}_SMALL_INT_POWERS,
//! step: BASE{0}_STEP,
//! bias: BASE{0}_BIAS,
//! }};\n"""
//!
//! def calculate_bitshift(base, exponent):
//! '''
//! Calculate the bitshift required for a given base. The exponent
//! is the absolute value of the max exponent (log distance from 1.)
//! '''
//!
//! return 63 + math.ceil(math.log2(base**exponent))
//!
//!
//! def next_fp(fp, base, step = 1):
//! '''Generate the next extended-floating point value.'''
//!
//! return (fp[0] * (base**step), fp[1])
//!
//!
//! def prev_fp(fp, base, step = 1):
//! '''Generate the previous extended-floating point value.'''
//!
//! return (fp[0] // (base**step), fp[1])
//!
//!
//! def normalize_fp(fp):
//! '''Normalize a extended-float so the MSB is the 64th bit'''
//!
//! while fp[0] >> 64 != 0:
//! fp = (fp[0] >> 1, fp[1] + 1)
//! return fp
//!
//!
//! def generate_small(base, count):
//! '''Generate the small powers for a given base'''
//!
//! bitshift = calculate_bitshift(base, count)
//! fps = []
//! fp = (1 << bitshift, -bitshift)
//! for exp in range(count):
//! fps.append((normalize_fp(fp), exp))
//! fp = next_fp(fp, base)
//!
//! # Print the small powers as integers.
//! ints = [base**i for _, i in fps]
//!
//! return fps, ints
//!
//!
//! def generate_large(base, step):
//! '''Generate the large powers for a given base.'''
//!
//! # Get our starting parameters
//! min_exp = math.floor(math.log(5e-324, base) - math.log(0xFFFFFFFFFFFFFFFF, base))
//! max_exp = math.ceil(math.log(1.7976931348623157e+308, base))
//! bitshift = calculate_bitshift(base, abs(min_exp - step))
//! fps = deque()
//!
//! # Add negative exponents
//! # We need to go below the minimum exponent, since we need
//! # all resulting exponents to be positive.
//! fp = (1 << bitshift, -bitshift)
//! for exp in range(-step, min_exp-step, -step):
//! fp = prev_fp(fp, base, step)
//! fps.appendleft((normalize_fp(fp), exp))
//!
//! # Add positive exponents
//! fp = (1 << bitshift, -bitshift)
//! fps.append((normalize_fp(fp), 0))
//! for exp in range(step, max_exp, step):
//! fp = next_fp(fp, base, step)
//! fps.append((normalize_fp(fp), exp))
//!
//! # Return the smallest exp, AKA, the bias
//! return fps, -fps[0][1]
//!
//!
//! def print_array(base, string, fps, index):
//! '''Print an entire array'''
//!
//! print(string.format(base, len(fps)))
//! for fp, exp in fps:
//! value = " {},".format(fp[index])
//! exp = EXP_STR.format(base, exp)
//! print(value.ljust(30, " ") + exp)
//! print("];")
//!
//!
//! def generate_base(base):
//! '''Generate all powers and variables.'''
//!
//! step = math.floor(math.log(1e10, base))
//! small, ints = generate_small(base, step)
//! large, bias = generate_large(base, step)
//!
//! print_array(base, SMALL_MANTISSA_STR, small, 0)
//! print_array(base, SMALL_EXPONENT_STR, small, 1)
//! print_array(base, LARGE_MANTISSA_STR, large, 0)
//! print_array(base, LARGE_EXPONENT_STR, large, 1)
//! print(SMALL_INT_STR.format(base, len(ints), ints))
//! print(STEP_STR.format(base, step))
//! print(BIAS_STR.format(base, bias))
//!
//!
//! def generate():
//! '''Generate all bases.'''
//!
//! bases = [
//! 3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21,
//! 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 36
//! ]
//!
//! for base in bases:
//! print("// BASE{}\n".format(base))
//! generate_base(base)
//! print("")
//!
//! print("// HIGH LEVEL\n// ----------\n")
//!
//! for base in bases:
//! print(POWER_STR.format(base))
//!
//!
//! if __name__ == '__main__':
//! generate()
//! ```
use super::cached::{ExtendedFloatArray, ModeratePathPowers};
@@ -331,7 +182,7 @@ const BASE10_BIAS: i32 = 350;
// HIGH LEVEL
// ----------
pub(crate) const BASE10_POWERS: ModeratePathPowers = ModeratePathPowers {
const BASE10_POWERS: ModeratePathPowers = ModeratePathPowers {
small: ExtendedFloatArray { mant: &BASE10_SMALL_MANTISSA, exp: &BASE10_SMALL_EXPONENT },
large: ExtendedFloatArray { mant: &BASE10_LARGE_MANTISSA, exp: &BASE10_LARGE_EXPONENT },
small_int: &BASE10_SMALL_INT_POWERS,
-32
View File
@@ -1,32 +0,0 @@
use super::float::ExtendedFloat;
use super::num::*;
// INTO FLOAT
// Export extended-precision float to native float.
//
// The extended-precision float must be in native float representation,
// with overflow/underflow appropriately handled.
pub(crate) fn into_float<F>(fp: ExtendedFloat) -> F
where F: Float
{
// Export floating-point number.
if fp.mant == 0 || fp.exp < F::DENORMAL_EXPONENT {
// sub-denormal, underflow
F::ZERO
} else if fp.exp >= F::MAX_EXPONENT {
// overflow
F::from_bits(F::INFINITY_BITS)
} else {
// calculate the exp and fraction bits, and return a float from bits.
let exp: u64;
if (fp.exp == F::DENORMAL_EXPONENT) && (fp.mant & F::HIDDEN_BIT_MASK.as_u64()) == 0 {
exp = 0;
} else {
exp = (fp.exp + F::EXPONENT_BIAS).as_u64();
}
let exp = exp << F::MANTISSA_SIZE;
let mant = fp.mant & F::MANTISSA_MASK.as_u64();
F::from_bits(F::Unsigned::as_cast(mant | exp))
}
}
+36 -6
View File
@@ -1,6 +1,5 @@
// FLOAT TYPE
use super::convert::*;
use super::num::*;
use super::rounding::*;
use super::shift::*;
@@ -10,7 +9,7 @@ use super::shift::*;
/// Private implementation, exposed only for testing purposes.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ExtendedFloat {
pub(crate) struct ExtendedFloat {
/// Mantissa for the extended-precision float.
pub mant: u64,
/// Binary exponent for the extended-precision float.
@@ -32,7 +31,7 @@ impl ExtendedFloat {
/// 1. Non-signed multiplication of mantissas (requires 2x as many bits as input).
/// 2. Normalization of the result (not done here).
/// 3. Addition of exponents.
pub fn mul(&self, b: &ExtendedFloat) -> ExtendedFloat {
pub(crate) fn mul(&self, b: &ExtendedFloat) -> ExtendedFloat {
// Logic check, values must be decently normalized prior to multiplication.
debug_assert!((self.mant & u64::HIMASK != 0) && (b.mant & u64::HIMASK != 0));
@@ -61,7 +60,7 @@ impl ExtendedFloat {
/// Multiply in-place, as if by `a*b`.
///
/// The result is not normalized.
pub fn imul(&mut self, b: &ExtendedFloat) {
pub(crate) fn imul(&mut self, b: &ExtendedFloat) {
*self = self.mul(b);
}
@@ -73,7 +72,7 @@ impl ExtendedFloat {
/// itself is 0.
///
/// Get the number of bytes shifted.
pub fn normalize(&mut self) -> u32 {
pub(crate) fn normalize(&mut self) -> u32 {
// Note:
// Using the cltz intrinsic via leading_zeros is way faster (~10x)
// than shifting 1-bit at a time, via while loop, and also way
@@ -104,8 +103,39 @@ impl ExtendedFloat {
// INTO
/// Convert into lower-precision native float.
pub fn into_float<F: Float>(mut self) -> F {
pub(crate) fn into_float<F: Float>(mut self) -> F {
self.round_to_native::<F>();
into_float(self)
}
}
// INTO FLOAT
// Export extended-precision float to native float.
//
// The extended-precision float must be in native float representation,
// with overflow/underflow appropriately handled.
pub(crate) fn into_float<F>(fp: ExtendedFloat) -> F
where F: Float
{
// Export floating-point number.
if fp.mant == 0 || fp.exp < F::DENORMAL_EXPONENT {
// sub-denormal, underflow
F::ZERO
} else if fp.exp >= F::MAX_EXPONENT {
// overflow
F::from_bits(F::INFINITY_BITS)
} else {
// calculate the exp and fraction bits, and return a float from bits.
let exp: u64;
if (fp.exp == F::DENORMAL_EXPONENT) && (fp.mant & F::HIDDEN_BIT_MASK.as_u64()) == 0 {
exp = 0;
} else {
exp = (fp.exp + F::EXPONENT_BIAS).as_u64();
}
let exp = exp << F::MANTISSA_SIZE;
let mant = fp.mant & F::MANTISSA_MASK.as_u64();
F::from_bits(F::Unsigned::as_cast(mant | exp))
}
}
+11 -1
View File
@@ -1,6 +1,14 @@
/// Facade around the core features for name mangling.
pub(crate) mod lib {
#[cfg(feature = "std")]
pub(crate) use std::*;
#[cfg(not(feature = "std"))]
pub(crate) use core::*;
}
mod cached;
mod cached_float80;
mod convert;
mod float;
mod num;
mod parse;
@@ -8,4 +16,6 @@ mod rounding;
mod shift;
// API.
pub use self::num::Float;
pub use self::parse::parse_float;
+130 -13
View File
@@ -1,5 +1,8 @@
use std::ops;
//! Utilities for Rust numbers.
use crate::lib::ops;
/// Type that can be converted to primitive with `as`.
pub trait AsPrimitive:
Sized +
Copy +
@@ -135,6 +138,7 @@ as_cast_impl!(isize, as_isize);
as_cast_impl!(f32, as_f32);
as_cast_impl!(f64, as_f64);
/// Numerical type trait.
pub trait Number:
AsCast +
ops::Add<Output=Self> +
@@ -158,6 +162,7 @@ macro_rules! number_impl {
number_impl! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize f32 f64 }
/// Defines a trait that supports integral operations.
pub trait Integer:
Number +
ops::BitAnd<Output=Self> +
@@ -176,18 +181,8 @@ macro_rules! integer_impl {
integer_impl! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
pub trait UnsignedInteger: Integer {}
macro_rules! unsigned_integer_impl {
($($t:ty)*) => ($(
impl UnsignedInteger for $t {}
)*)
}
unsigned_integer_impl! { u8 u16 u32 u64 u128 usize }
/// Type trait for the mantissa type.
pub trait Mantissa: UnsignedInteger {
pub trait Mantissa: Integer {
/// Mask for the left-most bit, to check if the value is normalized.
const NORMALIZED_MASK: Self;
/// Mask to extract the high bits from the integer.
@@ -210,7 +205,7 @@ impl Mantissa for u64 {
/// Get exact exponent limit for radix.
pub trait Float: Number {
/// Unsigned type of the same size.
type Unsigned: UnsignedInteger;
type Unsigned: Integer;
const ZERO: Self;
@@ -377,3 +372,125 @@ impl Float for f64 {
f64::to_bits(self)
}
}
// TEST
// ----
#[cfg(test)]
mod tests {
use super::*;
fn check_as_primitive<T: AsPrimitive>(t: T) {
let _: u8 = t.as_u8();
let _: u16 = t.as_u16();
let _: u32 = t.as_u32();
let _: u64 = t.as_u64();
let _: u128 = t.as_u128();
let _: usize = t.as_usize();
let _: i8 = t.as_i8();
let _: i16 = t.as_i16();
let _: i32 = t.as_i32();
let _: i64 = t.as_i64();
let _: i128 = t.as_i128();
let _: isize = t.as_isize();
let _: f32 = t.as_f32();
let _: f64 = t.as_f64();
}
#[test]
fn as_primitive_test() {
check_as_primitive(1u8);
check_as_primitive(1u16);
check_as_primitive(1u32);
check_as_primitive(1u64);
check_as_primitive(1u128);
check_as_primitive(1usize);
check_as_primitive(1i8);
check_as_primitive(1i16);
check_as_primitive(1i32);
check_as_primitive(1i64);
check_as_primitive(1i128);
check_as_primitive(1isize);
check_as_primitive(1f32);
check_as_primitive(1f64);
}
fn check_number<T: Number>(x: T, mut y: T) {
// Copy, partialeq, partialord
let _ = x;
assert!(x < y);
assert!(x != y);
// Operations
let _ = y + x;
let _ = y - x;
let _ = y * x;
let _ = y / x;
let _ = y % x;
y += x;
y -= x;
y *= x;
y /= x;
y %= x;
// Conversions already tested.
}
#[test]
fn number_test() {
check_number(1u8, 5);
check_number(1u16, 5);
check_number(1u32, 5);
check_number(1u64, 5);
check_number(1u128, 5);
check_number(1usize, 5);
check_number(1i8, 5);
check_number(1i16, 5);
check_number(1i32, 5);
check_number(1i64, 5);
check_number(1i128, 5);
check_number(1isize, 5);
check_number(1f32, 5.0);
check_number(1f64, 5.0);
}
fn check_integer<T: Integer>(x: T) {
// Bitwise operations
let _ = x & T::ZERO;
}
#[test]
fn integer_test() {
check_integer(65u8);
check_integer(65u16);
check_integer(65u32);
check_integer(65u64);
check_integer(65u128);
check_integer(65usize);
check_integer(65i8);
check_integer(65i16);
check_integer(65i32);
check_integer(65i64);
check_integer(65i128);
check_integer(65isize);
}
fn check_float<T: Float>(x: T) {
// Check functions
let _ = x.powi(5);
let _ = x.to_bits();
assert!(T::from_bits(x.to_bits()) == x);
// Check properties
let _ = x.to_bits() & T::SIGN_MASK;
let _ = x.to_bits() & T::EXPONENT_MASK;
let _ = x.to_bits() & T::HIDDEN_BIT_MASK;
let _ = x.to_bits() & T::MANTISSA_MASK;
}
#[test]
fn float_test() {
check_float(123f32);
check_float(123f64);
}
}
+87 -1
View File
@@ -116,7 +116,7 @@ fn multiply_exponent_extended<F>(fp: &mut ExtendedFloat, exponent: i32)
///
/// Return the float approximation and if the value can be accurately
/// represented with mantissa bits of precision.
pub(super) fn moderate_path<F>(mantissa: u64, exponent: i32) -> F
fn moderate_path<F>(mantissa: u64, exponent: i32) -> F
where F: Float
{
let mut fp = ExtendedFloat { mant: mantissa, exp: 0 };
@@ -156,3 +156,89 @@ pub fn parse_float<F>(mantissa: u64, exponent: i32, truncated: bool) -> F
moderate_path(mantissa, exponent)
}
}
// TESTS
// -----
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn float_fast_path_test() {
// valid
let mantissa = (1 << f32::MANTISSA_SIZE) - 1;
let (min_exp, max_exp) = f32::exponent_limit();
for exp in min_exp..max_exp+1 {
let f = fast_path::<f32>(mantissa, exp);
assert!(f.is_some(), "should be valid {:?}.", (mantissa, exp));
}
// Check slightly above valid exponents
let f = fast_path::<f32>(123, 15);
assert_eq!(f, Some(1.23e+17));
// Exponent is 1 too high, pushes over the mantissa.
let f = fast_path::<f32>(123, 16);
assert!(f.is_none());
// Mantissa is too large, checked_mul should overflow.
let f = fast_path::<f32>(mantissa, 11);
assert!(f.is_none());
// invalid mantissa
#[cfg(feature = "radix")] {
let (_, max_exp) = f64::exponent_limit(3);
let f = fast_path::<f32>(1<<f32::MANTISSA_SIZE, 3, max_exp+1);
assert!(f.is_none(), "invalid mantissa");
}
// invalid exponents
let (min_exp, max_exp) = f32::exponent_limit();
let f = fast_path::<f32>(mantissa, min_exp-1);
assert!(f.is_none(), "exponent under min_exp");
let f = fast_path::<f32>(mantissa, max_exp+1);
assert!(f.is_none(), "exponent above max_exp");
}
#[test]
fn double_fast_path_test() {
// valid
let mantissa = (1 << f64::MANTISSA_SIZE) - 1;
let (min_exp, max_exp) = f64::exponent_limit();
for exp in min_exp..max_exp+1 {
let f = fast_path::<f64>(mantissa, exp);
assert!(f.is_some(), "should be valid {:?}.", (mantissa, exp));
}
// invalid mantissa
#[cfg(feature = "radix")] {
let (_, max_exp) = f64::exponent_limit(3);
let f = fast_path::<f64>(1<<f64::MANTISSA_SIZE, 3, max_exp+1);
assert!(f.is_none(), "invalid mantissa");
}
// invalid exponents
let (min_exp, max_exp) = f64::exponent_limit();
let f = fast_path::<f64>(mantissa, min_exp-1);
assert!(f.is_none(), "exponent under min_exp");
let f = fast_path::<f64>(mantissa, max_exp+1);
assert!(f.is_none(), "exponent above max_exp");
}
#[test]
fn parse_double_test() {
assert_eq!(123456789.0, moderate_path::<f64>(1234567890, -1));
assert_eq!(123456789.1, moderate_path::<f64>(1234567891, -1));
assert_eq!(123456789.12, moderate_path::<f64>(12345678912, -2));
assert_eq!(123456789.123, moderate_path::<f64>(123456789123, -3));
assert_eq!(123456789.1234, moderate_path::<f64>(1234567891234, -4));
assert_eq!(123456789.12345, moderate_path::<f64>(12345678912345, -5));
assert_eq!(123456789.123456, moderate_path::<f64>(123456789123456, -6));
assert_eq!(123456789.1234567, moderate_path::<f64>(1234567891234567, -7));
assert_eq!(123456789.12345679, moderate_path::<f64>(12345678912345679, -8));
assert_eq!(123456789.12345, moderate_path::<f64>(12345678912345, -5));
}
}
+259 -3
View File
@@ -1,4 +1,6 @@
use std::mem;
//! Defines rounding schemes for floating-point numbers.
use crate::lib::mem;
use super::float::ExtendedFloat;
use super::num::*;
use super::shift::*;
@@ -75,6 +77,31 @@ pub(crate) fn round_nearest(fp: &mut ExtendedFloat, shift: i32)
(is_above, is_halfway)
}
// Tie rounded floating point to event.
pub(crate) fn tie_even(fp: &mut ExtendedFloat, is_above: bool, is_halfway: bool)
{
// Extract the last bit after shifting (and determine if it is odd).
let is_odd = fp.mant & 1 == 1;
// Calculate if we need to roundup.
// We need to roundup if we are above halfway, or if we are odd
// and at half-way (need to tie-to-even).
if is_above || (is_odd && is_halfway) {
fp.mant += 1;
}
}
// Shift right N-bytes and round nearest, tie-to-even.
//
// Floating-point arithmetic uses round to nearest, ties to even,
// which rounds to the nearest value, if the value is halfway in between,
// round to an even value.
pub(crate) fn round_nearest_tie_even(fp: &mut ExtendedFloat, shift: i32)
{
let (is_above, is_halfway) = round_nearest(fp, shift);
tie_even(fp, is_above, is_halfway);
}
// ROUND TO FLOAT
// Shift the ExtendedFloat fraction to the fraction bits in a native float.
@@ -98,14 +125,14 @@ pub(crate) fn round_to_float<F>(fp: &mut ExtendedFloat)
let diff = F::DENORMAL_EXPONENT - fp.exp;
if diff <= u64::FULL {
// We can avoid underflow, can get a valid representation.
round_nearest(fp, diff);
round_nearest_tie_even(fp, diff);
} else {
// Certain underflow, assign literal 0s.
fp.mant = 0;
fp.exp = 0;
}
} else {
round_nearest(fp, F::DEFAULT_SHIFT);
round_nearest_tie_even(fp, F::DEFAULT_SHIFT);
}
if fp.mant & F::CARRY_MASK == F::CARRY_MASK {
@@ -158,3 +185,232 @@ pub(crate) fn round_to_native<F>(fp: &mut ExtendedFloat)
round_to_float::<F>(fp);
avoid_overflow::<F>(fp);
}
// TESTS
// -----
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lower_n_mask_test() {
assert_eq!(lower_n_mask(0u64), 0b0);
assert_eq!(lower_n_mask(1u64), 0b1);
assert_eq!(lower_n_mask(2u64), 0b11);
assert_eq!(lower_n_mask(10u64), 0b1111111111);
assert_eq!(lower_n_mask(32u64), 0b11111111111111111111111111111111);
}
#[test]
fn lower_n_halfway_test() {
assert_eq!(lower_n_halfway(0u64), 0b0);
assert_eq!(lower_n_halfway(1u64), 0b1);
assert_eq!(lower_n_halfway(2u64), 0b10);
assert_eq!(lower_n_halfway(10u64), 0b1000000000);
assert_eq!(lower_n_halfway(32u64), 0b10000000000000000000000000000000);
}
#[test]
fn nth_bit_test() {
assert_eq!(nth_bit(0u64), 0b1);
assert_eq!(nth_bit(1u64), 0b10);
assert_eq!(nth_bit(2u64), 0b100);
assert_eq!(nth_bit(10u64), 0b10000000000);
assert_eq!(nth_bit(31u64), 0b10000000000000000000000000000000);
}
#[test]
fn internal_n_mask_test() {
assert_eq!(internal_n_mask(1u64, 0u64), 0b0);
assert_eq!(internal_n_mask(1u64, 1u64), 0b1);
assert_eq!(internal_n_mask(2u64, 1u64), 0b10);
assert_eq!(internal_n_mask(4u64, 2u64), 0b1100);
assert_eq!(internal_n_mask(10u64, 2u64), 0b1100000000);
assert_eq!(internal_n_mask(10u64, 4u64), 0b1111000000);
assert_eq!(internal_n_mask(32u64, 4u64), 0b11110000000000000000000000000000);
}
// NEAREST ROUNDING
#[test]
fn round_nearest_test() {
// Check exactly halfway (b'1100000')
let mut fp = ExtendedFloat { mant: 0x60, exp: 0 };
let (above, halfway) = round_nearest(&mut fp, 6);
assert!(!above);
assert!(halfway);
assert_eq!(fp.mant, 1);
// Check above halfway (b'1100001')
let mut fp = ExtendedFloat { mant: 0x61, exp: 0 };
let (above, halfway) = round_nearest(&mut fp, 6);
assert!(above);
assert!(!halfway);
assert_eq!(fp.mant, 1);
// Check below halfway (b'1011111')
let mut fp = ExtendedFloat { mant: 0x5F, exp: 0 };
let (above, halfway) = round_nearest(&mut fp, 6);
assert!(!above);
assert!(!halfway);
assert_eq!(fp.mant, 1);
}
#[test]
fn round_nearest_tie_even_test() {
// Check round-up, halfway
let mut fp = ExtendedFloat { mant: 0x60, exp: 0 };
round_nearest_tie_even(&mut fp, 6);
assert_eq!(fp.mant, 2);
// Check round-down, halfway
let mut fp = ExtendedFloat { mant: 0x20, exp: 0 };
round_nearest_tie_even(&mut fp, 6);
assert_eq!(fp.mant, 0);
// Check round-up, above halfway
let mut fp = ExtendedFloat { mant: 0x61, exp: 0 };
round_nearest_tie_even(&mut fp, 6);
assert_eq!(fp.mant, 2);
let mut fp = ExtendedFloat { mant: 0x21, exp: 0 };
round_nearest_tie_even(&mut fp, 6);
assert_eq!(fp.mant, 1);
// Check round-down, below halfway
let mut fp = ExtendedFloat { mant: 0x5F, exp: 0 };
round_nearest_tie_even(&mut fp, 6);
assert_eq!(fp.mant, 1);
let mut fp = ExtendedFloat { mant: 0x1F, exp: 0 };
round_nearest_tie_even(&mut fp, 6);
assert_eq!(fp.mant, 0);
}
// HIGH-LEVEL
#[test]
fn round_to_float_test() {
// Denormal
let mut fp = ExtendedFloat { mant: 1<<63, exp: f64::DENORMAL_EXPONENT - 15 };
round_to_float::<f64>(&mut fp);
assert_eq!(fp.mant, 1<<48);
assert_eq!(fp.exp, f64::DENORMAL_EXPONENT);
// Halfway, round-down (b'1000000000000000000000000000000000000000000000000000010000000000')
let mut fp = ExtendedFloat { mant: 0x8000000000000400, exp: -63 };
round_to_float::<f64>(&mut fp);
assert_eq!(fp.mant, 1<<52);
assert_eq!(fp.exp, -52);
// Halfway, round-up (b'1000000000000000000000000000000000000000000000000000110000000000')
let mut fp = ExtendedFloat { mant: 0x8000000000000C00, exp: -63 };
round_to_float::<f64>(&mut fp);
assert_eq!(fp.mant, (1<<52) + 2);
assert_eq!(fp.exp, -52);
// Above halfway
let mut fp = ExtendedFloat { mant: 0x8000000000000401, exp: -63 };
round_to_float::<f64>(&mut fp);
assert_eq!(fp.mant, (1<<52)+1);
assert_eq!(fp.exp, -52);
let mut fp = ExtendedFloat { mant: 0x8000000000000C01, exp: -63 };
round_to_float::<f64>(&mut fp);
assert_eq!(fp.mant, (1<<52) + 2);
assert_eq!(fp.exp, -52);
// Below halfway
let mut fp = ExtendedFloat { mant: 0x80000000000003FF, exp: -63 };
round_to_float::<f64>(&mut fp);
assert_eq!(fp.mant, 1<<52);
assert_eq!(fp.exp, -52);
let mut fp = ExtendedFloat { mant: 0x8000000000000BFF, exp: -63 };
round_to_float::<f64>(&mut fp);
assert_eq!(fp.mant, (1<<52) + 1);
assert_eq!(fp.exp, -52);
}
#[test]
fn avoid_overflow_test() {
// Avoid overflow, fails by 1
let mut fp = ExtendedFloat { mant: 0xFFFFFFFFFFFF, exp: f64::MAX_EXPONENT + 5 };
avoid_overflow::<f64>(&mut fp);
assert_eq!(fp.mant, 0xFFFFFFFFFFFF);
assert_eq!(fp.exp, f64::MAX_EXPONENT+5);
// Avoid overflow, succeeds
let mut fp = ExtendedFloat { mant: 0xFFFFFFFFFFFF, exp: f64::MAX_EXPONENT + 4 };
avoid_overflow::<f64>(&mut fp);
assert_eq!(fp.mant, 0x1FFFFFFFFFFFE0);
assert_eq!(fp.exp, f64::MAX_EXPONENT-1);
}
#[test]
fn round_to_native_test() {
// Overflow
let mut fp = ExtendedFloat { mant: 0xFFFFFFFFFFFF, exp: f64::MAX_EXPONENT + 4 };
round_to_native::<f64>(&mut fp);
assert_eq!(fp.mant, 0x1FFFFFFFFFFFE0);
assert_eq!(fp.exp, f64::MAX_EXPONENT-1);
// Need denormal
let mut fp = ExtendedFloat { mant: 1, exp: f64::DENORMAL_EXPONENT +48 };
round_to_native::<f64>(&mut fp);
assert_eq!(fp.mant, 1<<48);
assert_eq!(fp.exp, f64::DENORMAL_EXPONENT);
// Halfway, round-down (b'10000000000000000000000000000000000000000000000000000100000')
let mut fp = ExtendedFloat { mant: 0x400000000000020, exp: -58 };
round_to_native::<f64>(&mut fp);
assert_eq!(fp.mant, 1<<52);
assert_eq!(fp.exp, -52);
// Halfway, round-up (b'10000000000000000000000000000000000000000000000000001100000')
let mut fp = ExtendedFloat { mant: 0x400000000000060, exp: -58 };
round_to_native::<f64>(&mut fp);
assert_eq!(fp.mant, (1<<52) + 2);
assert_eq!(fp.exp, -52);
// Above halfway
let mut fp = ExtendedFloat { mant: 0x400000000000021, exp: -58 };
round_to_native::<f64>(&mut fp);
assert_eq!(fp.mant, (1<<52)+1);
assert_eq!(fp.exp, -52);
let mut fp = ExtendedFloat { mant: 0x400000000000061, exp: -58 };
round_to_native::<f64>(&mut fp);
assert_eq!(fp.mant, (1<<52) + 2);
assert_eq!(fp.exp, -52);
// Below halfway
let mut fp = ExtendedFloat { mant: 0x40000000000001F, exp: -58 };
round_to_native::<f64>(&mut fp);
assert_eq!(fp.mant, 1<<52);
assert_eq!(fp.exp, -52);
let mut fp = ExtendedFloat { mant: 0x40000000000005F, exp: -58 };
round_to_native::<f64>(&mut fp);
assert_eq!(fp.mant, (1<<52) + 1);
assert_eq!(fp.exp, -52);
// Underflow
// Adapted from failures in strtod.
let mut fp = ExtendedFloat { exp: -1139, mant: 18446744073709550712 };
round_to_native::<f64>(&mut fp);
assert_eq!(fp.mant, 0);
assert_eq!(fp.exp, 0);
let mut fp = ExtendedFloat { exp: -1139, mant: 18446744073709551460 };
round_to_native::<f64>(&mut fp);
assert_eq!(fp.mant, 0);
assert_eq!(fp.exp, 0);
let mut fp = ExtendedFloat { exp: -1138, mant: 9223372036854776103 };
round_to_native::<f64>(&mut fp);
assert_eq!(fp.mant, 1);
assert_eq!(fp.exp, -1074);
}
}
+3 -1
View File
@@ -1,4 +1,6 @@
use std::mem;
//! Bit-shift helpers.
use crate::lib::mem;
use super::float::ExtendedFloat;
// Shift extended-precision float right `shift` bytes.