Compare commits
10 Commits
5b7c532353
...
9eabb7cdbf
| Author | SHA1 | Date | |
|---|---|---|---|
|
9eabb7cdbf
|
|||
|
c34ab24c6f
|
|||
|
f147abda5f
|
|||
|
3cdd512e8b
|
|||
|
39dcd647f2
|
|||
|
33dda0d6ea
|
|||
|
27f745ee6d
|
|||
|
cd6f9486f7
|
|||
|
cfee5d2214
|
|||
|
77928c8fcb
|
63
Cargo.lock
generated
63
Cargo.lock
generated
@@ -20,6 +20,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"num-traits",
|
||||
"ufmt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -30,3 +31,65 @@ checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.95"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.40"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.109"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ufmt"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1a64846ec02b57e9108d6469d98d1648782ad6bb150a95a9baac26900bbeab9d"
|
||||
dependencies = [
|
||||
"ufmt-macros",
|
||||
"ufmt-write",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ufmt-macros"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d337d3be617449165cb4633c8dece429afd83f84051024079f97ad32a9663716"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ufmt-write"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e87a2ed6b42ec5e28cc3b94c09982969e9227600b2e3dcbc1db927a84c06bd69"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
|
||||
|
||||
@@ -5,6 +5,10 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
num-traits = { version = "0.2.19", default-features = false }
|
||||
ufmt = { version = "0.2.0", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
arrayvec = { version = "0.7.6", default-features = false }
|
||||
|
||||
[features]
|
||||
ufmt = ["dep:ufmt"]
|
||||
|
||||
201
LICENSE-APACHE
Normal file
201
LICENSE-APACHE
Normal 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.
|
||||
3
README.md
Normal file
3
README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# Decimal numbers and simple calculator math for Rust core projects
|
||||
|
||||
Tests can be run on `std` but library is designed for `core` only for embedded systems.
|
||||
128
src/calc.rs
128
src/calc.rs
@@ -1,38 +1,59 @@
|
||||
use core::{convert::Infallible, error::Error, fmt::Display};
|
||||
use core::{convert::Infallible, fmt::Display, marker::PhantomData};
|
||||
|
||||
use num_traits::{PrimInt, Unsigned};
|
||||
use num_traits::{float::FloatCore, PrimInt, Unsigned};
|
||||
#[cfg(feature = "ufmt")]
|
||||
use ufmt::derive::uDebug;
|
||||
|
||||
use crate::{Decimal, DecimalError};
|
||||
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "ufmt", derive(uDebug))]
|
||||
pub enum StackCalcError {
|
||||
StackOverflow,
|
||||
StackUnderflow,
|
||||
DecimalError(DecimalError),
|
||||
}
|
||||
|
||||
impl Error for StackCalcError {}
|
||||
impl Display for StackCalcError {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
StackCalcError::StackOverflow => f.write_str("stack overflow"),
|
||||
StackCalcError::StackUnderflow => f.write_str("stack underflow"),
|
||||
StackCalcError::DecimalError(de) => de.fmt(f),
|
||||
StackCalcError::DecimalError(de) => Display::fmt(de, f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StackCalc<const SS: usize = 2, const DS: usize = 5, E = u16> {
|
||||
stack: [Decimal<DS, E>; SS],
|
||||
pub struct StackCalc<F: FloatCore, const STACK: usize = 2, const DSIZE: usize = 5, EXP = u16> {
|
||||
stack: [Decimal<DSIZE, EXP>; STACK],
|
||||
index: usize,
|
||||
phantom: PhantomData<F>,
|
||||
}
|
||||
|
||||
impl<const SS: usize, const DS: usize, E: PrimInt> Default for StackCalc<SS, DS, E> {
|
||||
#[cfg(feature = "ufmt")]
|
||||
impl<F: FloatCore, const STACK: usize, const DSIZE: usize, EXP: ufmt::uDebug> ufmt::uDebug
|
||||
for StackCalc<F, STACK, DSIZE, EXP>
|
||||
{
|
||||
fn fmt<W>(&self, f: &mut ufmt::Formatter<'_, W>) -> Result<(), W::Error>
|
||||
where
|
||||
W: ufmt::uWrite + ?Sized,
|
||||
{
|
||||
f.debug_struct("StackCalc")?
|
||||
.field("stack", &self.stack.as_slice())?
|
||||
.field("index", &self.index)?
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F: FloatCore, const STACK: usize, const DSIZE: usize, EXP: PrimInt> Default
|
||||
for StackCalc<F, STACK, DSIZE, EXP>
|
||||
{
|
||||
fn default() -> Self {
|
||||
StackCalc {
|
||||
stack: [Decimal::default(); SS],
|
||||
stack: [Decimal::default(); STACK],
|
||||
index: 0,
|
||||
phantom: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,12 +70,41 @@ impl From<Infallible> for StackCalcError {
|
||||
}
|
||||
}
|
||||
|
||||
impl<const SS: usize, const DS: usize, E: PrimInt + Unsigned> StackCalc<SS, DS, E> {
|
||||
impl<F: FloatCore, const STACK: usize, const DSIZE: usize, EXP: PrimInt + Unsigned>
|
||||
StackCalc<F, STACK, DSIZE, EXP>
|
||||
{
|
||||
pub fn is_full(&self) -> bool {
|
||||
self.index == STACK
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.index == 0
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.index
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.index = 0;
|
||||
}
|
||||
|
||||
pub fn last(&self) -> Option<Decimal<DSIZE, EXP>> {
|
||||
if self.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(self.stack[self.index - 1])
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> impl Iterator<Item = &Decimal<DSIZE, EXP>> {
|
||||
self.stack.iter().take(self.index)
|
||||
}
|
||||
|
||||
pub fn push(
|
||||
&mut self,
|
||||
val: impl TryInto<Decimal<DS, E>, Error: Into<StackCalcError>>,
|
||||
val: impl TryInto<Decimal<DSIZE, EXP>, Error: Into<StackCalcError>>,
|
||||
) -> Result<(), StackCalcError> {
|
||||
if self.index == SS {
|
||||
if self.is_full() {
|
||||
return Err(StackCalcError::StackOverflow);
|
||||
}
|
||||
self.stack[self.index] = val.try_into().map_err(Into::into)?;
|
||||
@@ -62,23 +112,47 @@ impl<const SS: usize, const DS: usize, E: PrimInt + Unsigned> StackCalc<SS, DS,
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn pop(&mut self) -> Result<Decimal<DS, E>, StackCalcError> {
|
||||
if self.index == 0 {
|
||||
pub fn pop(&mut self) -> Result<Decimal<DSIZE, EXP>, StackCalcError> {
|
||||
if self.is_empty() {
|
||||
return Err(StackCalcError::StackUnderflow);
|
||||
}
|
||||
self.index -= 1;
|
||||
Ok(self.stack[self.index])
|
||||
}
|
||||
|
||||
pub fn add(&mut self) -> Result<Decimal<DS, E>, StackCalcError> {
|
||||
fn pop_pair_float(&mut self) -> Result<(F, F), StackCalcError> {
|
||||
let a = self.pop()?;
|
||||
let b = self.pop()?;
|
||||
let a = f64::try_from(a)?;
|
||||
let b = f64::try_from(b)?;
|
||||
let res = Decimal::try_from(a + b)?;
|
||||
let a = a.to_float::<F>()?;
|
||||
let b = b.to_float::<F>()?;
|
||||
Ok((a, b))
|
||||
}
|
||||
|
||||
fn calc_pair_float(
|
||||
&mut self,
|
||||
f: impl FnOnce(F, F) -> Result<F, StackCalcError>,
|
||||
) -> Result<Decimal<DSIZE, EXP>, StackCalcError> {
|
||||
let (a, b) = self.pop_pair_float()?;
|
||||
let res = Decimal::from_float(f(a, b)?)?;
|
||||
self.push(res)?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn add(&mut self) -> Result<Decimal<DSIZE, EXP>, StackCalcError> {
|
||||
self.calc_pair_float(|a, b| Ok(b + a))
|
||||
}
|
||||
|
||||
pub fn sub(&mut self) -> Result<Decimal<DSIZE, EXP>, StackCalcError> {
|
||||
self.calc_pair_float(|a, b| Ok(b - a))
|
||||
}
|
||||
|
||||
pub fn mul(&mut self) -> Result<Decimal<DSIZE, EXP>, StackCalcError> {
|
||||
self.calc_pair_float(|a, b| Ok(b * a))
|
||||
}
|
||||
|
||||
pub fn div(&mut self) -> Result<Decimal<DSIZE, EXP>, StackCalcError> {
|
||||
self.calc_pair_float(|a, b| Ok(b / a))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -86,7 +160,7 @@ mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn test_add() -> Result<(), StackCalcError> {
|
||||
let mut calc = StackCalc::<3, 7>::default();
|
||||
let mut calc = StackCalc::<f64, 3, 7>::default();
|
||||
calc.push(Decimal::default())?;
|
||||
calc.push(1337.42)?;
|
||||
assert_eq!(calc.add()?, Decimal::try_from(1337.42)?);
|
||||
@@ -98,12 +172,26 @@ mod tests {
|
||||
calc.push(3.0).unwrap_err(),
|
||||
StackCalcError::StackOverflow
|
||||
));
|
||||
assert_eq!(calc.add()?, Decimal::try_from(5.0)?);
|
||||
assert_eq!(calc.add()?, Decimal::try_from(1337.42 * 2.0 + 5.0)?);
|
||||
calc.add()?;
|
||||
assert_eq!(calc.last().unwrap(), Decimal::try_from(5.0)?);
|
||||
calc.add()?;
|
||||
assert_eq!(
|
||||
calc.last().unwrap(),
|
||||
Decimal::try_from(1337.42 * 2.0 + 5.0)?
|
||||
);
|
||||
assert!(matches!(
|
||||
calc.add().unwrap_err(),
|
||||
StackCalcError::StackUnderflow
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_add_10() -> Result<(), StackCalcError> {
|
||||
let mut calc = StackCalc::<f32, 3, 5>::default();
|
||||
calc.push(Decimal::new(false, [3, 0, 0, 0, 0], false, 0))?;
|
||||
calc.push(Decimal::new(false, [7, 0, 0, 0, 0], false, 0))?;
|
||||
assert_eq!(calc.add()?, Decimal::new(false, [1, 0, 0, 0, 0], false, 1));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
273
src/lib.rs
273
src/lib.rs
@@ -2,18 +2,21 @@
|
||||
|
||||
pub mod calc;
|
||||
|
||||
use core::{error::Error, fmt::Display};
|
||||
#[cfg(not(test))]
|
||||
use core::fmt::Display;
|
||||
use num_traits::float::FloatCore;
|
||||
use num_traits::{one, zero, PrimInt, Unsigned};
|
||||
#[cfg(feature = "ufmt")]
|
||||
use ufmt::derive::uDebug;
|
||||
#[cfg(feature = "ufmt")]
|
||||
use ufmt::{uDebug, uDisplay, uwrite};
|
||||
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "ufmt", derive(uDebug))]
|
||||
pub enum DecimalError {
|
||||
ExponentOverflow,
|
||||
NotANumber,
|
||||
}
|
||||
|
||||
impl Error for DecimalError {}
|
||||
impl Display for DecimalError {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
@@ -24,30 +27,140 @@ impl Display for DecimalError {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Decimal<const S: usize = 5, E = u16> {
|
||||
pub minus: bool,
|
||||
pub significant: [u8; S],
|
||||
pub minus_exponent: bool,
|
||||
pub exponent: E,
|
||||
pub struct Decimal<const SIZE: usize = 5, EXP = u16> {
|
||||
minus: bool,
|
||||
significant: [u8; SIZE],
|
||||
minus_exponent: bool,
|
||||
exponent: EXP,
|
||||
}
|
||||
|
||||
impl<const S: usize, E: PrimInt> Default for Decimal<S, E> {
|
||||
#[cfg(feature = "ufmt")]
|
||||
impl<const SIZE: usize, EXP: uDebug> uDebug for Decimal<SIZE, EXP> {
|
||||
fn fmt<W>(&self, f: &mut ufmt::Formatter<'_, W>) -> Result<(), W::Error>
|
||||
where
|
||||
W: ufmt::uWrite + ?Sized,
|
||||
{
|
||||
f.debug_struct("Decimal")?
|
||||
.field("minus", &self.minus)?
|
||||
.field("significant", &self.significant.as_slice())?
|
||||
.field("minus_exponent", &self.minus_exponent)?
|
||||
.field("exponent", &self.exponent)?
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<const SIZE: usize, EXP: PrimInt + Unsigned> Decimal<SIZE, EXP> {
|
||||
pub fn new(minus: bool, significant: [u8; SIZE], minus_exponent: bool, exponent: EXP) -> Self {
|
||||
for s in significant {
|
||||
assert!(s < 10, "bad significant");
|
||||
}
|
||||
Decimal {
|
||||
minus,
|
||||
significant,
|
||||
minus_exponent,
|
||||
exponent,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_parts(self) -> (bool, [u8; SIZE], bool, EXP) {
|
||||
(
|
||||
self.minus,
|
||||
self.significant,
|
||||
self.minus_exponent,
|
||||
self.exponent,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn from_float<F: FloatCore>(mut f: F) -> Result<Self, DecimalError> {
|
||||
if !f.is_finite() {
|
||||
return Err(DecimalError::NotANumber);
|
||||
}
|
||||
|
||||
let minus = f.is_sign_negative();
|
||||
if minus {
|
||||
f = f * F::from(-1).unwrap();
|
||||
}
|
||||
|
||||
let mut significant = [0; SIZE];
|
||||
let mut exponent: EXP = zero();
|
||||
let minus_exponent = f < one() && f > zero();
|
||||
let ten = F::from(10).unwrap();
|
||||
|
||||
if !f.is_zero() {
|
||||
while f >= ten {
|
||||
f = f / ten;
|
||||
exponent = exponent
|
||||
.checked_add(&one())
|
||||
.ok_or(DecimalError::ExponentOverflow)?;
|
||||
}
|
||||
while f < one() {
|
||||
f = f * ten;
|
||||
exponent = exponent
|
||||
.checked_add(&one())
|
||||
.ok_or(DecimalError::ExponentOverflow)?;
|
||||
}
|
||||
}
|
||||
|
||||
for i in 0..SIZE {
|
||||
significant[i] = f.trunc().to_u8().unwrap();
|
||||
f = f.fract() * ten;
|
||||
}
|
||||
|
||||
Ok(Decimal {
|
||||
minus,
|
||||
significant,
|
||||
minus_exponent,
|
||||
exponent,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn to_float<F: FloatCore>(&self) -> Result<F, DecimalError> {
|
||||
let Decimal {
|
||||
minus,
|
||||
significant,
|
||||
minus_exponent,
|
||||
exponent,
|
||||
} = *self;
|
||||
|
||||
let mut e = exponent.to_i32().ok_or(DecimalError::ExponentOverflow)?;
|
||||
if minus_exponent {
|
||||
e = -e;
|
||||
}
|
||||
let e = F::from(10).unwrap().powi(e);
|
||||
|
||||
let mut f: F = zero();
|
||||
|
||||
for i in (0..SIZE).rev() {
|
||||
f = f / F::from(10).unwrap();
|
||||
let s = significant[i];
|
||||
f = f + F::from(s).unwrap() * e;
|
||||
}
|
||||
|
||||
if minus {
|
||||
f = f * F::from(-1).unwrap();
|
||||
}
|
||||
|
||||
Ok(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<const SIZE: usize, EXP: PrimInt> Default for Decimal<SIZE, EXP> {
|
||||
fn default() -> Self {
|
||||
Decimal {
|
||||
minus: false,
|
||||
significant: [0; S],
|
||||
significant: [0; SIZE],
|
||||
minus_exponent: false,
|
||||
exponent: zero(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<const S: usize, E: Display> Display for Decimal<S, E> {
|
||||
impl<const SIZE: usize, EXP: Display> Display for Decimal<SIZE, EXP> {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
if self.minus {
|
||||
write!(f, "-")?;
|
||||
}
|
||||
for i in 0..S {
|
||||
for i in 0..SIZE {
|
||||
write!(f, "{}", self.significant[i])?;
|
||||
if i == 0 {
|
||||
write!(f, ".")?;
|
||||
@@ -61,80 +174,58 @@ impl<const S: usize, E: Display> Display for Decimal<S, E> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<const S: usize, E: PrimInt + Unsigned> TryFrom<f64> for Decimal<S, E> {
|
||||
type Error = DecimalError;
|
||||
|
||||
fn try_from(mut f: f64) -> Result<Self, Self::Error> {
|
||||
if !f.is_finite() {
|
||||
return Err(DecimalError::NotANumber);
|
||||
#[cfg(feature = "ufmt")]
|
||||
impl<const SIZE: usize, EXP: Display + uDisplay> uDisplay for Decimal<SIZE, EXP> {
|
||||
fn fmt<W>(&self, f: &mut ufmt::Formatter<'_, W>) -> Result<(), W::Error>
|
||||
where
|
||||
W: ufmt::uWrite + ?Sized,
|
||||
{
|
||||
if self.minus {
|
||||
uwrite!(f, "-")?;
|
||||
}
|
||||
let minus = f.is_sign_negative();
|
||||
if minus {
|
||||
f *= -1.0;
|
||||
}
|
||||
let mut exponent: E = zero();
|
||||
let minus_exponent = f < 1.0 && f > 0.0;
|
||||
while f > 10.0 {
|
||||
f /= 10.0;
|
||||
exponent = exponent
|
||||
.checked_add(&one())
|
||||
.ok_or(DecimalError::ExponentOverflow)?;
|
||||
}
|
||||
while f < 1.0 {
|
||||
if f == f * 10.0 {
|
||||
break;
|
||||
for i in 0..SIZE {
|
||||
uwrite!(f, "{}", self.significant[i])?;
|
||||
if i == 0 {
|
||||
uwrite!(f, ".")?;
|
||||
}
|
||||
f *= 10.0;
|
||||
exponent = exponent
|
||||
.checked_add(&one())
|
||||
.ok_or(DecimalError::ExponentOverflow)?;
|
||||
}
|
||||
let mut significant = [0; S];
|
||||
for i in 0..S {
|
||||
let s = f as u8;
|
||||
f *= 10.0;
|
||||
f -= (s * 10) as f64;
|
||||
significant[i] = s;
|
||||
uwrite!(f, "e")?;
|
||||
if self.minus_exponent {
|
||||
uwrite!(f, "-")?;
|
||||
}
|
||||
Ok(Decimal {
|
||||
minus,
|
||||
significant,
|
||||
minus_exponent,
|
||||
exponent,
|
||||
})
|
||||
uwrite!(f, "{}", self.exponent)
|
||||
}
|
||||
}
|
||||
|
||||
impl<const S: usize, E: PrimInt + Unsigned> TryFrom<Decimal<S, E>> for f64 {
|
||||
impl<const SIZE: usize, EXP: PrimInt + Unsigned> TryFrom<f32> for Decimal<SIZE, EXP> {
|
||||
type Error = DecimalError;
|
||||
|
||||
fn try_from(val: Decimal<S, E>) -> Result<Self, Self::Error> {
|
||||
let Decimal {
|
||||
minus,
|
||||
significant,
|
||||
minus_exponent,
|
||||
exponent,
|
||||
} = val;
|
||||
fn try_from(f: f32) -> Result<Self, Self::Error> {
|
||||
Self::from_float(f)
|
||||
}
|
||||
}
|
||||
|
||||
let mut e = exponent.to_i32().ok_or(DecimalError::ExponentOverflow)?;
|
||||
if minus_exponent {
|
||||
e = -e;
|
||||
}
|
||||
let e = 10.0f64.powi(e);
|
||||
impl<const SIZE: usize, EXP: PrimInt + Unsigned> TryFrom<f64> for Decimal<SIZE, EXP> {
|
||||
type Error = DecimalError;
|
||||
|
||||
let mut f: f64 = 0.0;
|
||||
fn try_from(f: f64) -> Result<Self, Self::Error> {
|
||||
Self::from_float(f)
|
||||
}
|
||||
}
|
||||
|
||||
for i in (0..S).rev() {
|
||||
f /= 10.0;
|
||||
let s = significant[i];
|
||||
f += (s as f64) * e;
|
||||
}
|
||||
impl<const SIZE: usize, EXP: PrimInt + Unsigned> TryFrom<Decimal<SIZE, EXP>> for f32 {
|
||||
type Error = DecimalError;
|
||||
|
||||
if minus {
|
||||
f *= -1.0;
|
||||
}
|
||||
fn try_from(val: Decimal<SIZE, EXP>) -> Result<Self, Self::Error> {
|
||||
val.to_float()
|
||||
}
|
||||
}
|
||||
|
||||
Ok(f)
|
||||
impl<const SIZE: usize, EXP: PrimInt + Unsigned> TryFrom<Decimal<SIZE, EXP>> for f64 {
|
||||
type Error = DecimalError;
|
||||
|
||||
fn try_from(val: Decimal<SIZE, EXP>) -> Result<Self, Self::Error> {
|
||||
val.to_float()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,6 +234,11 @@ mod tests {
|
||||
use super::*;
|
||||
use arrayvec::ArrayString;
|
||||
|
||||
fn round_f(f: f64, d: i32) -> f64 {
|
||||
let m = 10.0.powi(d);
|
||||
(f * m).round() / m
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_to_decimal_zero() {
|
||||
let dec = Decimal::<5>::try_from(0.0).unwrap();
|
||||
@@ -152,6 +248,25 @@ mod tests {
|
||||
assert_eq!(dec.exponent, 0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_to_decimal_10() {
|
||||
let dec = Decimal::<5>::try_from(10.0).unwrap();
|
||||
assert!(!dec.minus);
|
||||
assert_eq!(dec.significant, [1, 0, 0, 0, 0]);
|
||||
assert!(!dec.minus_exponent);
|
||||
assert_eq!(dec.exponent, 1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "dbg![1.14f32.fract()]; // 0.13999999"]
|
||||
fn float_to_decimal_114() {
|
||||
let dec = Decimal::<5>::try_from(114.0f32).unwrap();
|
||||
assert!(!dec.minus);
|
||||
assert_eq!(dec.significant, [1, 1, 4, 0, 0]);
|
||||
assert!(!dec.minus_exponent);
|
||||
assert_eq!(dec.exponent, 2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_to_decimal_pos_big() {
|
||||
let dec = Decimal::<7>::try_from(1337.42).unwrap();
|
||||
@@ -250,10 +365,13 @@ mod tests {
|
||||
#[test]
|
||||
fn decimal_to_float_small() {
|
||||
let mut dec = Decimal::<7, u8>::default();
|
||||
dec.significant = [1, 3, 3, 7, 4, 2, 0];
|
||||
dec.significant = [1, 3, 3, 7, 4, 2, 1];
|
||||
dec.minus_exponent = true;
|
||||
dec.exponent = 2;
|
||||
assert_eq!(f64::try_from(dec).unwrap(), 0.0133742);
|
||||
assert_eq!(
|
||||
round_f(f64::try_from(dec).unwrap(), 8),
|
||||
round_f(0.01337421, 8)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -269,10 +387,13 @@ mod tests {
|
||||
fn decimal_to_float_neg_small() {
|
||||
let mut dec = Decimal::<7, u8>::default();
|
||||
dec.minus = true;
|
||||
dec.significant = [1, 3, 3, 7, 4, 2, 0];
|
||||
dec.significant = [1, 3, 3, 7, 4, 2, 1];
|
||||
dec.minus_exponent = true;
|
||||
dec.exponent = 2;
|
||||
assert_eq!(f64::try_from(dec).unwrap(), -0.0133742);
|
||||
assert_eq!(
|
||||
round_f(f64::try_from(dec).unwrap(), 8),
|
||||
round_f(-0.01337421, 8)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user