From 50df5a220fbe7e326b85fc900ac56836320860a3 Mon Sep 17 00:00:00 2001 From: Jonathan Johnson Date: Thu, 19 Sep 2024 09:36:21 -0700 Subject: [PATCH] Initial commit --- .github/FUNDING.yml | 1 + .github/workflows/docs.yml | 28 ++ .github/workflows/rust.yml | 37 ++ .gitignore | 1 + .rustme/config.ron | 55 +++ .rustme/docs.md | 31 ++ .rustme/header.md | 1 + CODE_OF_CONDUCT.md | 128 +++++ CONTRIBUTING.md | 55 +++ Cargo.lock | 7 + Cargo.toml | 24 + LICENSE-APACHE | 201 ++++++++ LICENSE-MIT | 8 + README.md | 41 ++ rustfmt.toml | 6 + src/.crate-docs.md | 39 ++ src/lib.rs | 925 +++++++++++++++++++++++++++++++++++++ src/tests.rs | 174 +++++++ 18 files changed, 1762 insertions(+) create mode 100644 .github/FUNDING.yml create mode 100644 .github/workflows/docs.yml create mode 100644 .github/workflows/rust.yml create mode 100644 .gitignore create mode 100644 .rustme/config.ron create mode 100644 .rustme/docs.md create mode 100644 .rustme/header.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 README.md create mode 100644 rustfmt.toml create mode 100644 src/.crate-docs.md create mode 100644 src/lib.rs create mode 100644 src/tests.rs diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..e9f2f13 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: [ecton] \ No newline at end of file diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..534bd74 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,28 @@ +name: Docs + +on: [push, pull_request] + +jobs: + docs: + runs-on: ubuntu-latest + steps: + - name: Install Rust + uses: hecrj/setup-rust-action@v1 + with: + rust-version: nightly + + - uses: actions/checkout@v3 + - name: Generate Docs + run: | + cargo +nightly doc --no-deps --all-features --workspace + + - name: Deploy Docs + if: github.ref == 'refs/heads/main' + uses: JamesIves/github-pages-deploy-action@releases/v4 + with: + branch: gh-pages + folder: target/doc/ + git-config-name: kl-botsu + git-config-email: botsu@khonsulabs.com + target-folder: /main/ + clean: true diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml new file mode 100644 index 0000000..7a77823 --- /dev/null +++ b/.github/workflows/rust.yml @@ -0,0 +1,37 @@ +name: Tests + +on: [push, pull_request] + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v3 + + - name: Install Rust + uses: hecrj/setup-rust-action@v1 + + - name: Run clippy + run: | + cargo clippy + + - name: Run clippy without std + run: | + cargo clippy --no-default-features + + - name: Run unit tests + run: | + cargo test + + build-msrv: + name: Test on MSRV + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Install Rust + uses: hecrj/setup-rust-action@v1 + with: + rust-version: 1.81.0 + - name: Run unit tests + run: cargo test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/.rustme/config.ron b/.rustme/config.ron new file mode 100644 index 0000000..9876215 --- /dev/null +++ b/.rustme/config.ron @@ -0,0 +1,55 @@ +Configuration( + files: { + "../README.md": ( + for_docs: false, + sections: [ + "header.md", + "docs.md", + "https://github.com/khonsulabs/.github/raw/main/snippets/readme-footer.md", + ], + ), + "../src/.crate-docs.md": ( + for_docs: true, + sections: [ + "docs.md", + "https://github.com/khonsulabs/.github/raw/main/snippets/readme-footer.md", + ], + ), + "../CONTRIBUTING.md": [ + "https://github.com/khonsulabs/.github/raw/main/docs/CONTRIBUTING.md", + ], + "../CODE_OF_CONDUCT.md": [ + "https://github.com/khonsulabs/.github/raw/main/docs/CODE_OF_CONDUCT.md", + ], + "../LICENSE-APACHE": [ + "https://github.com/khonsulabs/.github/raw/main/licenses/LICENSE-APACHE", + ], + "../LICENSE-MIT": [ + "https://github.com/khonsulabs/.github/raw/main/licenses/LICENSE-MIT", + ], + }, + glossaries: [ + "https://github.com/khonsulabs/.github/raw/main/snippets/glossary.ron", + { + // "msrv": "1.70", + "ref-name": ( + default: "main", + release: "v0.4.0", + ), + "docs": ( + default: "https://cushy.rs/main/docs/cushy/", + release: "https://docs.rs/cushy", + ), + "widget": ( + default: "https://cushy.rs/main/docs/cushy/widget/trait.Widget.html", + release: "https://docs.rs/cushy/*/cushy/widget/trait.Widget.html", + for_docs: "crate::widget::Widget", + ), + "widgets": ( + default: "https://cushy.rs/main/docs/cushy/widgets/index.html", + release: "https://docs.rs/cushy/*/cushy/widgets/index.html", + for_docs: "mod@crate::widgets", + ), + }, + ], +) \ No newline at end of file diff --git a/.rustme/docs.md b/.rustme/docs.md new file mode 100644 index 0000000..03a7c11 --- /dev/null +++ b/.rustme/docs.md @@ -0,0 +1,31 @@ + + + +![Approximint is considered alpha and unsupported](https://img.shields.io/badge/status-alpha-orange) +[![crate version](https://img.shields.io/crates/v/approximint.svg)](https://crates.io/crates/approximint) +[![Documentation for `$ref-name$`](https://img.shields.io/badge/docs-$ref-name$-informational)]($docs$) + +A large integer library supporting a non-inclusive range of +(-1e4,294,967,305..+1e4,294,967,305) with 9 decimal digits of precision. + +This library was designed to be a simple, efficient implementation of large +numbers for use in incremental games. It utilizes two 32 bit integers to +represent a number in the form of `coefficient * 10^exponent`. + +## Basic usage + +```rust +use approximint::Approximint; + +let googol = Approximint::one_e(100); +let billion = Approximint::new(1_000_000_000); + +assert_eq!((googol * billion).to_string(), "1.000e109"); +assert_eq!((googol * billion).as_english().to_string(), "1 billion googol"); +``` + +## no_std + +This crate supports all integer operations, including formatting, in no_std +without alloc. Floating point operations require the `std` feature to be +enabled. diff --git a/.rustme/header.md b/.rustme/header.md new file mode 100644 index 0000000..fdf4af6 --- /dev/null +++ b/.rustme/header.md @@ -0,0 +1 @@ +# Approximint diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..f5e94d4 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +moderators@khonsulabs.com. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..56b08ab --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,55 @@ +# Contributing to our projects + +Thank you for your interest in contributing to one of our projects. We want +everyone to have a positive experience contributing, so please carefully review +our only requirements for contributing: + +- All contributors must agree to [our Contributor License + Agreement](https://gist.github.com/ecton/b2e1e72abfa122da5e69ed30164f739e). + This will be asked for during your first pull request. +- All contributors must uphold the standards of our [Code of + Conduct](./CODE_OF_CONDUCT.md). + +The rest of this document is recommendations/guidelines to help consistency and +communication within our projects. + +## Creating Issues + +### Reporting Bugs + +To us, if something isn't behaving as you expect it to, that's a bug. Even if +it's misbehaving due to a misunderstanding, that means there's an opportunity to +improve our documentation or examples. Please don't hesitate to let us know if +you run into any issues while working with one of our projects. + +### Requesting New Features + +When requesting new features, please include details about what problem you're +trying to solve, not just a solution to your problem. By helping the community +understand the underlying problem, we can better evaluate what the best solution +to the problem might be. + +## Contributing Changes + +We openly welcome pull requests on our projects. We don't like bugs, and if +you've found one and wish to submit a fix, we greatly appreciate it. + +If you find that fixing a bug requires a significant change, or you are wanting +to add a somewhat large feature, please submit a proposal as an issue first. We +want to make sure that your efforts have the highest chance of success, and a +short discussion before starting can go a long way towards a pull request being +merged with less revisions. + +When working on an existing issue, update the issue to reflect that you're +working on it. This will help prevent duplicated efforts. + +If you begin working on something but need some assistance, don't hesitate to +reach out inside of the issue, on [our +forums](https://community.khonsulabs.com/), or in [our +Discord](https://discord.khonsulabs.com/). We will do our best to help you. + +### Project-specific requirements + +Be sure to check if a project's README contains additional contributing +guidelines. Each project may have different tools and commands that should be +run to validate that changes pass all requirements. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..b50d95f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "approximint" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..7b882af --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "approximint" +version = "0.1.0" +edition = "2021" +rust-version = "1.81.0" +description = "A large integer library using an approximate representation inspired by scientific notation" +repository = "https://github.com/khonsulabs/approximint" +license = "MIT OR Apache-2.0" +keywords = ["decimal", "incremental", "math"] +categories = ["mathematics", "game-development"] +readme = "./README.md" + +[features] +default = ["std"] +std = [] + +[lints.clippy] +pedantic = { level = "warn", priority = -1 } +missing_errors_doc = "allow" +missing_panics_doc = "allow" + +[lints.rust] +unsafe_code = "forbid" +missing_docs = "warn" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..28add2d --- /dev/null +++ b/LICENSE-APACHE @@ -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 2021 Khonsu Labs LLC + +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. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..2b84906 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,8 @@ +Copyright 2021 Khonsu Labs LLC + +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. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..90796ab --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +# Approximint + + + + +![Approximint is considered alpha and unsupported](https://img.shields.io/badge/status-alpha-orange) +[![crate version](https://img.shields.io/crates/v/approximint.svg)](https://crates.io/crates/approximint) +[![Documentation for `main`](https://img.shields.io/badge/docs-main-informational)](https://cushy.rs/main/docs/cushy/) + +A large integer library supporting a non-inclusive range of +(-1e4,294,967,305..+1e4,294,967,305) with 9 decimal digits of precision. + +This library was designed to be a simple, efficient implementation of large +numbers for use in incremental games. It utilizes two 32 bit integers to +represent a number in the form of `coefficient * 10^exponent`. + +## Basic usage + +```rust +use approximint::Approximint; + +let googol = Approximint::one_e(100); +let billion = Approximint::new(1_000_000_000); + +assert_eq!((googol * billion).to_string(), "1.000e109"); +assert_eq!((googol * billion).as_english().to_string(), "1 billion googol"); +``` + +## no_std + +This crate supports all integer operations, including formatting, in no_std +without alloc. Floating point operations require the `std` feature to be +enabled. + +## Open-source Licenses + +This project, like all projects from [Khonsu Labs](https://khonsulabs.com/), is open-source. +This repository is available under the [MIT License](./LICENSE-MIT) or the +[Apache License 2.0](./LICENSE-APACHE). + +To learn more about contributing, please see [CONTRIBUTING.md](./CONTRIBUTING.md). diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..db443f8 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,6 @@ +unstable_features = true +use_field_init_shorthand = true +imports_granularity = "Module" +group_imports = "StdExternalCrate" +format_code_in_doc_comments = true +reorder_impl_items = true diff --git a/src/.crate-docs.md b/src/.crate-docs.md new file mode 100644 index 0000000..5f7c526 --- /dev/null +++ b/src/.crate-docs.md @@ -0,0 +1,39 @@ + + + +![Approximint is considered alpha and unsupported](https://img.shields.io/badge/status-alpha-orange) +[![crate version](https://img.shields.io/crates/v/approximint.svg)](https://crates.io/crates/approximint) +[![Documentation for `main`](https://img.shields.io/badge/docs-main-informational)](https://cushy.rs/main/docs/cushy/) + +A large integer library supporting a non-inclusive range of +(-1e4,294,967,305..+1e4,294,967,305) with 9 decimal digits of precision. + +This library was designed to be a simple, efficient implementation of large +numbers for use in incremental games. It utilizes two 32 bit integers to +represent a number in the form of `coefficient * 10^exponent`. + +## Basic usage + +```rust +use approximint::Approximint; + +let googol = Approximint::one_e(100); +let billion = Approximint::new(1_000_000_000); + +assert_eq!((googol * billion).to_string(), "1.000e109"); +assert_eq!((googol * billion).as_english().to_string(), "1 billion googol"); +``` + +## no_std + +This crate supports all integer operations, including formatting, in no_std +without alloc. Floating point operations require the `std` feature to be +enabled. + +## Open-source Licenses + +This project, like all projects from [Khonsu Labs](https://khonsulabs.com/), is open-source. +This repository is available under the [MIT License](./LICENSE-MIT) or the +[Apache License 2.0](./LICENSE-APACHE). + +To learn more about contributing, please see [CONTRIBUTING.md](./CONTRIBUTING.md). diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..2588ef2 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,925 @@ +#![doc = include_str!(".crate-docs.md")] +#![no_std] +use core::fmt::{Display, Write}; +use core::ops::{Add, AddAssign, Mul, Neg, Sub, SubAssign}; +use core::slice; + +#[cfg(any(feature = "std", test))] +extern crate std; + +/// An integer type that approximates its value using storage inspired by +/// scientific notation. +/// +/// This type supports representing integers in a form of `coefficient * +/// 10^exponent`. The coefficient has a range of `-999_999_999..=999_999_999`, +/// and the maximum exponent is `u32::MAX`. This approach supports a range of +/// `-9.999_999_99e4,294,967,295..=9.999_999_99e4,294,967,295` while retaining 9 +/// digits of precision. +#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Default)] +pub struct Approximint { + ten_power: u32, + coefficient: i32, +} + +impl Approximint { + const COEFFICIENT_LIMIT: i32 = 1_000_000_000; + /// A value representing 1. + pub const ONE: Self = Self { + ten_power: 0, + coefficient: 1, + }; + /// A value representing 0. + pub const ZERO: Self = Self { + ten_power: 0, + coefficient: 0, + }; + + /// Returns `value` as an approximint. + #[must_use] + #[inline] + pub const fn new(value: i32) -> Self { + Self { + coefficient: value, + ten_power: 0, + } + .normalize_overflow() + } + + /// Returns an approximation of `value`. + #[inline] + pub fn approximate(value: impl Approximate) -> Self { + value.approximate() + } + + /// Returns a value representing 10 raised to the power of `exponent`. + #[must_use] + #[inline] + pub const fn one_e(exponent: u32) -> Self { + Self { + coefficient: 1, + ten_power: exponent, + } + .normalize_underflow() + } + + const fn normalized(self) -> Self { + self.normalize_underflow().normalize_overflow() + } + + const fn normalize_underflow(mut self) -> Self { + if self.coefficient > 0 { + while self.ten_power > 0 && self.coefficient < 100_000_000 { + self.coefficient *= 10; + self.ten_power -= 1; + } + } else if self.coefficient < 0 { + while self.ten_power > 0 && self.coefficient < -100_000_000 { + self.coefficient *= 10; + self.ten_power -= 1; + } + } + + self + } + + const fn normalize_overflow(mut self) -> Self { + if self.coefficient >= Self::COEFFICIENT_LIMIT + || self.coefficient <= -Self::COEFFICIENT_LIMIT + { + self.ten_power += 1; + self.coefficient /= 10; + } + self + } + + const fn match_powers(left: Self, right: Self) -> (Self, Self) { + let left = left.normalized(); + let right = right.normalized(); + + if left.ten_power < right.ten_power { + Self::adjusted_powers(left, right) + } else { + let (right, left) = Self::adjusted_powers(right, left); + (left, right) + } + } + + const fn adjusted_powers(mut lower: Self, higher: Self) -> (Self, Self) { + while lower.ten_power < higher.ten_power { + lower.coefficient /= 10; + if lower.coefficient == 0 { + lower.ten_power = higher.ten_power; + break; + } + lower.ten_power += 1; + } + (lower, higher) + } + + /// Returns a [`Display`] implementor that formats this number using English + /// words. + pub fn as_english(self) -> WordFormatter<'static> { + WordFormatter::english(self) + } + + /// Returns a [`Display`] implementor that formats this number using + /// scientific notation. + pub fn as_scientific(self) -> ScientificFormatter { + ScientificFormatter::from(self) + } + + /// Returns a [`Display`] implementor that formats this number using decimal + /// notation. + pub fn as_decimal(self) -> DecimalFormatter { + DecimalFormatter::from(self) + } +} + +impl Neg for Approximint { + type Output = Self; + + #[inline] + fn neg(self) -> Self::Output { + Self { + ten_power: self.ten_power, + coefficient: -self.coefficient, + } + } +} + +impl Add for Approximint { + type Output = Self; + + #[inline] + fn add(self, rhs: Self) -> Self::Output { + let (lhs, rhs) = Self::match_powers(self, rhs); + Self { + // Adding two numbers less than 1 billion will never overflow u32 + coefficient: lhs.coefficient + rhs.coefficient, + ten_power: lhs.ten_power, + } + .normalized() + } +} + +impl AddAssign for Approximint { + #[inline] + fn add_assign(&mut self, rhs: Self) { + *self = *self + rhs; + } +} + +impl Sub for Approximint { + type Output = Self; + + #[inline] + fn sub(self, rhs: Self) -> Self::Output { + let (lhs, rhs) = Self::match_powers(self, rhs); + Self { + coefficient: lhs.coefficient - rhs.coefficient, + ten_power: lhs.ten_power, + } + .normalized() + } +} + +impl SubAssign for Approximint { + #[inline] + fn sub_assign(&mut self, rhs: Self) { + *self = *self - rhs; + } +} + +impl Mul for Approximint { + type Output = Self; + + #[inline] + #[expect(clippy::cast_possible_truncation)] + fn mul(self, rhs: Self) -> Self::Output { + let mut coefficient = i64::from(self.coefficient) * i64::from(rhs.coefficient); + let mut ten_power = self.ten_power + rhs.ten_power; + while coefficient >= i64::from(Self::COEFFICIENT_LIMIT) { + ten_power += 1; + coefficient /= 10; + } + while coefficient <= i64::from(-Self::COEFFICIENT_LIMIT) { + ten_power += 1; + coefficient /= 10; + } + Self { + coefficient: coefficient as i32, + ten_power, + } + } +} + +#[cfg(feature = "std")] +impl Mul for Approximint { + type Output = Self; + + #[inline] + #[expect(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] + fn mul(self, rhs: f64) -> Self::Output { + if rhs >= f64::from(Self::COEFFICIENT_LIMIT) { + self * Self::approximate(rhs) + } else { + let coefficient = f64::from(self.coefficient) * rhs; + let decimals = coefficient.abs().log10(); + let mut places_to_shift = (9.0 - decimals).floor() as i32; + let ten_power = + if let Some(ten_power) = self.ten_power.checked_add_signed(-places_to_shift) { + ten_power + } else { + places_to_shift = self.ten_power as i32; + 0 + }; + + let shifted = coefficient * 10f64.powi(places_to_shift); + Self { + coefficient: shifted.round() as i32, + ten_power, + } + .normalize_overflow() + } + } +} + +impl From for Approximint { + #[inline] + fn from(value: u8) -> Self { + Self::new(i32::from(value)) + } +} + +impl From for Approximint { + #[inline] + fn from(value: u16) -> Self { + Self::new(i32::from(value)) + } +} + +impl From for Approximint { + #[inline] + fn from(value: i32) -> Self { + Self::new(value) + } +} + +impl Display for Approximint { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if self.ten_power > 0 { + ScientificFormatter::from(*self).fmt(f) + } else { + DecimalFormatter::from(*self).fmt(f) + } + } +} + +/// A [`Display`] implementation that formats an [`Approximint`] using +/// scientific notation. +#[derive(Clone, Copy, Eq, PartialEq, Debug)] +#[must_use] +pub struct ScientificFormatter { + num: Approximint, + round: bool, + settings: ScientificSettings, +} + +impl ScientificFormatter { + /// Sets the character to use between the whole number and decimal digits. + /// + /// By default, the decimal character is `.`. + #[inline] + pub fn decimal(mut self, decimal: char) -> Self { + self.settings.decimal = decimal; + self + } + + /// Performs rounding on the displayed value. + #[inline] + pub fn rounded(mut self) -> Self { + self.round = true; + self + } + + /// Sets the number of significant digits to display. + #[inline] + pub fn significant_digits(mut self, digits: u8) -> Self { + assert!(digits <= 8, "significant digits must be less than 9"); + self.settings.significant_digits = digits; + self + } + + /// Prevents displaying trailing zeroes. + #[inline] + pub fn truncate_zeroes(mut self) -> Self { + self.settings.keep_trailing_zeroes = false; + self + } +} + +impl From for ScientificFormatter { + #[inline] + fn from(num: Approximint) -> Self { + Self { + num, + round: false, + settings: ScientificSettings::default(), + } + } +} + +impl Display for ScientificFormatter { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if self.num.ten_power == 0 && self.num.coefficient == 0 { + return f.write_str("0"); + } + + let mut info = ScientificInfo::new(self.num); + if self.round { + info.round(self.settings.significant_digits); + } + info.fmt(f, self.settings) + } +} + +#[derive(Debug, Copy, Clone)] +struct ScientificInfo { + digits: DigitRing, + exponent: u32, + negative: bool, +} + +impl ScientificInfo { + #[expect(clippy::cast_sign_loss)] + fn new(num: Approximint) -> Self { + let mut digits = DigitRing::default(); + + let (negative, mut coefficient) = if num.coefficient >= 0 { + (false, num.coefficient as u32) + } else { + (true, num.coefficient.unsigned_abs()) + }; + let mut exponent = 0; + while coefficient > 0 { + digits.push_back((coefficient % 10) as u8 + b'0'); + coefficient /= 10; + exponent += 1; + } + + let exponent = exponent - 1 + num.ten_power; + Self { + digits, + exponent, + negative, + } + } + + fn round(&mut self, significant_digits: u8) { + if significant_digits <= 8 { + let mut digits_to_round = self + .digits + .iter_mut_rev() + .skip(8 - usize::from(significant_digits)); + let check_digit = digits_to_round.next().expect("not 0"); + if (b'5'..=b'9').contains(check_digit) { + let mut carry = false; + for digit in digits_to_round { + if *digit == b'9' { + *digit = b'0'; + carry = true; + } else { + *digit += 1; + carry = false; + break; + } + } + + // If we still have the carry flag, we need to push a new 1 + // digit. + if carry { + self.digits.push_back(b'1'); + self.exponent += 1; + } + } + } + } + + fn fmt( + &self, + f: &mut core::fmt::Formatter<'_>, + settings: ScientificSettings, + ) -> core::fmt::Result { + if self.negative { + f.write_char('-')?; + } + let mut digits = self + .digits + .iter() + .take(usize::from(settings.significant_digits)) + .enumerate(); + while let Some((index, digit)) = digits.next() { + if !settings.keep_trailing_zeroes + && index > 0 + && digit == b'0' + && digits.clone().all(|(_, digit)| digit == b'0') + { + break; + } + + if index == 1 { + f.write_char(settings.decimal)?; + } + + f.write_char(char::from(digit))?; + } + + write!(f, "e{}", self.exponent) + } +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +struct ScientificSettings { + decimal: char, + significant_digits: u8, + keep_trailing_zeroes: bool, +} + +impl Default for ScientificSettings { + #[inline] + fn default() -> Self { + Self { + decimal: '.', + significant_digits: 4, + keep_trailing_zeroes: true, + } + } +} + +#[derive(Default, Debug, Copy, Clone)] +struct DigitRing { + digits: [u8; 9], + first: u8, +} + +impl DigitRing { + fn push_back(&mut self, digit: u8) { + self.digits[usize::from(self.first)] = digit; + self.first += 1; + if usize::from(self.first) == self.digits.len() { + self.first = 0; + } + } + + fn iter(&self) -> DigitRingIter<'_> { + self.into_iter() + } + + fn iter_mut_rev(&mut self) -> DigitRingIterMutRev<'_> { + let (first, second) = self.digits.split_at_mut(usize::from(self.first)); + DigitRingIterMutRev(second.iter_mut(), first.iter_mut()) + } + + const fn len(&self) -> usize { + self.digits.len() + } +} + +impl<'a> IntoIterator for &'a DigitRing { + type IntoIter = DigitRingIter<'a>; + type Item = u8; + + #[inline] + fn into_iter(self) -> Self::IntoIter { + let (first, second) = self.digits.split_at(usize::from(self.first)); + DigitRingIter(second.iter(), first.iter()) + } +} + +#[derive(Clone)] +struct DigitRingIter<'a>(slice::Iter<'a, u8>, slice::Iter<'a, u8>); + +impl<'a> Iterator for DigitRingIter<'a> { + type Item = u8; + + #[inline] + fn next(&mut self) -> Option { + loop { + let digit = self.1.next_back().or_else(|| self.0.next_back())?; + if *digit > 0 { + return Some(*digit); + } + } + } +} + +struct DigitRingIterMutRev<'a>(slice::IterMut<'a, u8>, slice::IterMut<'a, u8>); + +impl<'a> Iterator for DigitRingIterMutRev<'a> { + type Item = &'a mut u8; + + #[inline] + fn next(&mut self) -> Option { + self.0.next().or_else(|| self.1.next()) + } +} + +/// A [`Display`] implementation for an [`Approximint`] that uses a word list. +#[derive(Clone, Debug)] +#[must_use] +pub struct WordFormatter<'a> { + decimal: DecimalFormatter, + decimal_before: u32, + words: &'a [(u32, &'a str)], + round: bool, +} + +static ENGLISH: [(u32, &str); 33] = [ + (3, "thousand"), + (6, "million"), + (9, "billion"), + (12, "trillion"), + (15, "quadrillion"), + (18, "quintillion"), + (21, "sextillion"), + (24, "septillion"), + (27, "octillion"), + (30, "nonillion"), + (33, "decillion"), + (36, "undecillion"), + (39, "duodecillion"), + (42, "tredecillion"), + (45, "quattuordecillion"), + (48, "quindecillion"), + (51, "sexdecillion"), + (54, "septendecillion"), + (57, "octodecillion"), + (60, "novemdecillion"), + (63, "vigintillion"), + (66, "unvigintillion"), + (69, "duovigintillion"), + (72, "trevigintillion"), + (75, "quattuorvigintillion"), + (78, "quinvigintillion"), + (81, "sexvigintillion"), + (84, "septenvigintillion"), + (87, "octovigintillion"), + (90, "novemvigintillion"), + (93, "trigintillion"), + (100, "googol"), + (303, "centillion"), +]; + +impl WordFormatter<'static> { + /// Returns a formatter for the English language. + #[inline] + pub fn english(num: Approximint) -> Self { + Self::new(num, &ENGLISH).decimal_before_10_power(9) + } +} + +impl<'a> WordFormatter<'a> { + /// Returns a new formatter for `num` using the given `words`. + /// + /// `words` is a slice of pairs of powers of ten and the associated word. + /// For example, here is a portion of the English word list: + /// + /// ```rust + /// &[ + /// (3, "thousand"), + /// (6, "million"), + /// (9, "billion"), + /// (12, "trillion"), + /// // ... + /// ]; + /// ``` + /// + /// The formatter will reduce `num`'s ten-power by the largest matching + /// word, and repeat the process until the value is too small for any + /// eligible words. The remaining value will then be formatted using decimal + /// notation with a single decimal digit when the value is less than 1,000. + #[inline] + pub fn new(num: Approximint, words: &'static [(u32, &'static str)]) -> Self { + Self { + decimal: DecimalFormatter::from(num), + decimal_before: 0, + words, + round: false, + } + } + + /// Performs rounding before formatting the number. + #[inline] + pub fn rounded(mut self) -> Self { + self.round = true; + self + } + + /// Prevents using words for powers of ten less than or equal to + /// `ten_power`. + /// + /// The default English formatter sets this to 9, preventing values less + /// than 1 billion from being converted to words. + #[inline] + pub fn decimal_before_10_power(mut self, ten_power: u32) -> Self { + self.decimal_before = ten_power; + self + } + + /// Sets the character to use between grouped integer digits. + /// + /// The default separator is `,`. + #[inline] + pub fn separator(mut self, separator: char) -> Self { + self.decimal.separator = separator; + self + } + + /// Sets the number of integer digits between each separator character. + /// + /// The default is 3. + #[inline] + pub fn digits_per_separator(mut self, digits: u8) -> Self { + self.decimal.digits_per_separator = digits; + self + } + + fn format_info( + &self, + info: ScientificInfo, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + if info.negative { + f.write_char('-')?; + } + self.format_words(info.exponent, f, |f, exponent| { + let digits_per_separator = usize::from(self.decimal.digits_per_separator); + let separator_offset = + digits_per_separator - 1 - exponent as usize % digits_per_separator; + for (index, digit) in info.digits.iter().take(exponent as usize + 2).enumerate() { + if index == exponent as usize + 1 { + if digit == b'0' { + break; + } + f.write_char('.')?; + } else if index > 0 && (index + separator_offset) % digits_per_separator == 0 { + f.write_char(self.decimal.separator)?; + } + f.write_char(char::from(digit))?; + } + Ok(()) + }) + } + + fn format_words( + &self, + exponent: u32, + f: &mut core::fmt::Formatter<'_>, + format_exponent: impl FnOnce(&mut core::fmt::Formatter<'_>, u32) -> core::fmt::Result, + ) -> core::fmt::Result { + // info treats the leading digit as significant, but for the purpose of + // this function we need to treat exponent as a count of digits. + let word = self + .words + .windows(2) + .skip_while(|words| words[0].0 < self.decimal_before) + .find(|words| words[0].0 <= exponent && words[1].0 > exponent) + .map_or_else( + || self.words.last().expect("at least one word"), + |words| &words[0], + ); + let Some(exponent) = exponent.checked_sub(word.0) else { + return format_exponent(f, exponent); + }; + + if self.round { + todo!("round"); + } + + if exponent < self.decimal_before { + format_exponent(f, exponent)?; + } else { + self.format_words(exponent, f, format_exponent)?; + } + + f.write_char(' ')?; + f.write_str(word.1) + } +} + +impl Display for WordFormatter<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.format_info(ScientificInfo::new(self.decimal.num), f) + } +} + +/// A [`Display`] implementor for an [`Approximint`] that formats using decimal +/// notation. +#[derive(Clone, Copy, Eq, PartialEq, Debug)] +#[must_use] +pub struct DecimalFormatter { + num: Approximint, + separator: char, + digits_per_separator: u8, + scientific_after: u32, +} + +impl DecimalFormatter { + /// Sets the character to use between grouped integer digits. + /// + /// The default separator is `,`. + #[inline] + pub fn separator(mut self, separator: char) -> Self { + self.separator = separator; + self + } + + /// Sets the number of integer digits between each separator character. + /// + /// The default is 3. + #[inline] + pub fn digits_per_separator(mut self, digits: u8) -> Self { + self.digits_per_separator = digits; + self + } +} + +impl From for DecimalFormatter { + #[inline] + fn from(num: Approximint) -> Self { + Self { + num, + separator: ',', + digits_per_separator: 3, + scientific_after: 30, + } + } +} + +impl Display for DecimalFormatter { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if self.num.ten_power == 0 && self.num.coefficient == 0 { + return f.write_str("0"); + } else if self.num.ten_power >= self.scientific_after { + return ScientificFormatter::from(self.num).fmt(f); + } + + // To avoid allocations, we need to figure out how many total digits we + // have so that we can emit separators along the way. + let info = ScientificInfo::new(self.num); + + if info.negative { + f.write_char('-')?; + } + + let digits_per_separator = usize::from(self.digits_per_separator); + let exponent_usize = info.exponent as usize; + let separator_offset = if digits_per_separator > 0 { + digits_per_separator - 1 - exponent_usize % digits_per_separator + } else { + 0 + }; + + let mut index = 0; + for digit in info + .digits + .iter() + .take(info.digits.len().min(exponent_usize + 1)) + { + if self.digits_per_separator > 0 + && index > 0 + && (index + separator_offset) % digits_per_separator == 0 + { + f.write_char(self.separator)?; + } + f.write_char(char::from(digit))?; + index += 1; + } + + for index in index..=exponent_usize { + if self.digits_per_separator > 0 + && (index + separator_offset) % digits_per_separator == 0 + { + f.write_char(self.separator)?; + } + f.write_char('0')?; + } + Ok(()) + } +} + +/// A value that can be approximated into an [`Approximint`]. +pub trait Approximate { + /// Returns this value as an integer approximation. + fn approximate(self) -> Approximint; +} + +impl Approximate for u32 { + #[inline] + #[expect(clippy::cast_possible_wrap)] + fn approximate(mut self) -> Approximint { + let mut ten_power = 0; + while self >= Approximint::COEFFICIENT_LIMIT as u32 { + ten_power += 1; + self /= 10; + } + + Approximint { + coefficient: self as i32, + ten_power, + } + } +} + +impl Approximate for u64 { + #[inline] + #[expect(clippy::cast_possible_truncation)] + fn approximate(mut self) -> Approximint { + let mut ten_power = 0; + while self >= Approximint::COEFFICIENT_LIMIT as u64 { + ten_power += 1; + self /= 10; + } + + Approximint { + coefficient: self as i32, + ten_power, + } + } +} + +impl Approximate for usize { + #[inline] + #[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))] + fn approximate(self) -> Approximint { + Approximint::from(self as u32) + } + + #[inline] + #[cfg(not(any(target_pointer_width = "16", target_pointer_width = "32")))] + #[expect(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] + fn approximate(mut self) -> Approximint { + let mut ten_power = 0; + while self >= Approximint::COEFFICIENT_LIMIT as usize { + ten_power += 1; + self /= 10; + } + + Approximint { + coefficient: self as i32, + ten_power, + } + } +} + +impl Approximate for u128 { + #[inline] + #[expect(clippy::cast_possible_truncation)] + fn approximate(mut self) -> Approximint { + let mut ten_power = 0; + while self >= Approximint::COEFFICIENT_LIMIT as u128 { + ten_power += 1; + self /= 10; + } + + Approximint { + coefficient: self as i32, + ten_power, + } + } +} + +#[cfg(feature = "std")] +impl Approximate for f64 { + #[inline] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + fn approximate(self) -> Approximint { + let coefficient = self; + let decimals = coefficient.log10(); + let mut places_to_shift = (9.0 - decimals).floor() as i32; + let ten_power = if places_to_shift < 0 { + (-places_to_shift) as u32 + } else { + places_to_shift = 0; + 0 + }; + + let shifted = coefficient * 10f64.powi(places_to_shift); + Approximint { + coefficient: shifted.round() as i32, + ten_power, + } + .normalize_overflow() + } +} + +#[cfg(feature = "std")] +impl Approximate for f32 { + #[inline] + fn approximate(self) -> Approximint { + f64::from(self).approximate() + } +} + +#[cfg(test)] +mod tests; diff --git a/src/tests.rs b/src/tests.rs new file mode 100644 index 0000000..ef4d433 --- /dev/null +++ b/src/tests.rs @@ -0,0 +1,174 @@ +use std::string::ToString; + +use crate::{Approximint, DecimalFormatter, ScientificFormatter, WordFormatter}; + +#[test] +#[expect(clippy::similar_names)] +fn basics() { + let thousand = Approximint::new(1000); + let million = thousand * thousand; + let billion = thousand * million; + assert_eq!(million * 0.001, thousand); + assert_eq!(billion * 0.001, million); + assert_eq!(billion * 0.000_001, thousand); + assert_eq!(billion * 0.000_000_001, Approximint::ONE); + assert_eq!(billion * 3.12, Approximint::approximate(3_120_000_000_u32)); + let negative_million = -thousand * thousand; + let negative_billion = thousand * negative_million; + assert_eq!(negative_million * 0.001, -thousand); + assert_eq!(negative_billion * 0.001, negative_million); + assert_eq!(negative_billion * 0.000_001, -thousand); + assert_eq!(negative_billion * 0.000_000_001, -Approximint::ONE); + assert_eq!( + negative_billion * 3.12, + -Approximint::approximate(3_120_000_000_u32) + ); + + assert_eq!( + billion * 1_000., + Approximint::approximate(1_000_000_000_000u64) + ); + assert_eq!( + billion * thousand, + Approximint::approximate(1_000_000_000_000u64) + ); + assert_eq!(thousand - thousand, Approximint::ZERO); + assert_eq!(Approximint::ZERO - thousand, -thousand); +} + +#[test] +fn formatting() { + assert_eq!(Approximint::new(123).to_string(), "123"); + assert_eq!(Approximint::new(1234).to_string(), "1,234"); + assert_eq!(Approximint::new(123_456_789).to_string(), "123,456,789"); + assert_eq!( + DecimalFormatter::from(Approximint::new(1_234_567_890)).to_string(), + "1,234,567,890" + ); + assert_eq!( + DecimalFormatter::from(Approximint::new(1_234_567_890)) + .separator('.') + .digits_per_separator(4) + .to_string(), + "12.3456.7890" + ); + assert_eq!( + DecimalFormatter::from(Approximint::new(1_234_567_890)) + .digits_per_separator(0) + .to_string(), + "1234567890" + ); + // Feature, not a bug: don't round by default in display formatting. In a + // clicker game if your currency total displays the same as what the + // purchase price is, it should always be able to purchase it. Rounding can + // make the currency total larger than it actually is. + assert_eq!(Approximint::new(1_234_567_890).to_string(), "1.234e9"); + // But we support rounding. + assert_eq!( + ScientificFormatter::from(Approximint::new(1_234_567_890)) + .rounded() + .to_string(), + "1.235e9" + ); + assert_eq!( + ScientificFormatter::from(Approximint::new(999_999)).to_string(), + "9.999e5" + ); + assert_eq!( + ScientificFormatter::from(Approximint::new(999_999)) + .rounded() + .to_string(), + "1.000e6" + ); + assert_eq!( + ScientificFormatter::from(Approximint::new(999_999)) + .rounded() + .truncate_zeroes() + .to_string(), + "1e6" + ); + assert_eq!( + ScientificFormatter::from(Approximint::new(1_045_999)) + .rounded() + .significant_digits(2) + .to_string(), + "1.0e6" + ); + assert_eq!( + ScientificFormatter::from(Approximint::new(1_045_999)) + .rounded() + .significant_digits(3) + .to_string(), + "1.05e6" + ); + assert_eq!( + ScientificFormatter::from(Approximint::new(1_105_999)) + .significant_digits(3) + .truncate_zeroes() + .to_string(), + "1.1e6" + ); +} + +#[test] +fn english() { + assert_eq!( + WordFormatter::english(Approximint::new(123_000)) + .decimal_before_10_power(0) + .to_string(), + "123 thousand" + ); + assert_eq!( + WordFormatter::english(Approximint::new(123_100)) + .decimal_before_10_power(0) + .to_string(), + "123.1 thousand" + ); + assert_eq!( + WordFormatter::english(Approximint::new(123_100)) + .decimal_before_10_power(9) + .to_string(), + "123,100" + ); + assert_eq!( + WordFormatter::english(Approximint::new(123_456_789)) + .decimal_before_10_power(6) + .to_string(), + "123.4 million" + ); + assert_eq!( + WordFormatter::english(Approximint::one_e(100) * core::f64::consts::PI).to_string(), + "3.1 googol" + ); + assert_eq!( + WordFormatter::english(Approximint::one_e(100) * Approximint::new(1_000)).to_string(), + "1,000 googol" + ); + assert_eq!( + WordFormatter::english(Approximint::one_e(100) * Approximint::new(999_999_999)).to_string(), + "999,999,999 googol" + ); + assert_eq!( + WordFormatter::english(Approximint::one_e(100) * Approximint::new(1_000_000_000)) + .to_string(), + "1 billion googol" + ); + assert_eq!( + WordFormatter::english(Approximint::one_e(100) * Approximint::one_e(100)).to_string(), + "1 googol googol" + ); +} + +#[test] +fn float_conversion() { + assert_eq!(Approximint::approximate(123.), Approximint::new(123)); + assert_eq!( + Approximint::approximate(1_234_567_890.), + Approximint::new(1_234_567_890) + ); + assert_eq!( + Approximint::approximate(1_234_567_890.), + Approximint::new(1_234_567_890) + ); + assert_eq!(Approximint::approximate(1.0e100), Approximint::one_e(100)); +}