From 1579d16943ee1f72a25c45bc69f100675ecbcdbb Mon Sep 17 00:00:00 2001 From: Jeremy Wall Date: Mon, 12 Apr 2021 20:22:18 -0400 Subject: [PATCH] Recipe Data model: Units --- .gitignore | 1 + Cargo.lock | 56 +++++++ Cargo.toml | 2 + LICENSE | 201 ++++++++++++++++++++++ recipes/Cargo.toml | 10 ++ recipes/src/lib.rs | 47 ++++++ recipes/src/test.rs | 76 +++++++++ recipes/src/unit.rs | 396 ++++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 789 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 recipes/Cargo.toml create mode 100644 recipes/src/lib.rs create mode 100644 recipes/src/test.rs create mode 100644 recipes/src/unit.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..844041c --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,56 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "autocfg" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" + +[[package]] +name = "num-bigint" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e0d047c1062aa51e256408c560894e5251f08925980e53cf1aa5bd00eec6512" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" +dependencies = [ + "autocfg", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d41702bd167c2df5520b384281bc111a4b5efcf7fbc4c9c222c815b07e0a6a6a" +dependencies = [ + "autocfg", + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" +dependencies = [ + "autocfg", +] + +[[package]] +name = "recipes" +version = "0.1.0" +dependencies = [ + "num-rational", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..54b4115 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,2 @@ +[workspace] +members = [ "recipes" ] \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f49a4e1 --- /dev/null +++ b/LICENSE @@ -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. \ No newline at end of file diff --git a/recipes/Cargo.toml b/recipes/Cargo.toml new file mode 100644 index 0000000..ba33b97 --- /dev/null +++ b/recipes/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "recipes" +version = "0.1.0" +authors = ["Jeremy Wall "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies.num-rational] +version = "~0.4.0" \ No newline at end of file diff --git a/recipes/src/lib.rs b/recipes/src/lib.rs new file mode 100644 index 0000000..3b35fd1 --- /dev/null +++ b/recipes/src/lib.rs @@ -0,0 +1,47 @@ +// Copyright 2021 Jeremy Wall +// +// 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. +pub mod unit; + +use unit::*; + +pub struct Recipe { + pub title: String, + pub desc: String, + pub steps: Vec, +} + +pub struct Step { + pub prep_time: std::time::Duration, + pub instructions: String, + pub ingredients: Vec, +} + +pub enum Form { + Whole, // default + Chopped, + Minced, + Sliced, + Ground, + Custom(String), +} + +pub struct Ingredient { + pub name: String, + pub amt: Measure, + pub form: Form, + pub category: String, +} + +#[cfg(test)] +mod test; diff --git a/recipes/src/test.rs b/recipes/src/test.rs new file mode 100644 index 0000000..3fda70b --- /dev/null +++ b/recipes/src/test.rs @@ -0,0 +1,76 @@ +// Copyright 2021 Jeremy Wall +// +// 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. +use crate::unit::*; +use VolumeMeasure::*; + +use std::convert::Into; + +use num_rational::Ratio; + +#[test] +fn test_volume_measure_conversion() { + let gal = Gal(1.into()); + assert_eq!(gal.into_qrt(), Qrt(4.into())); + assert_eq!(gal.into_pint(), Pint((4 * 2).into())); + assert_eq!(gal.into_cup(), Cup((4 * 2 * 2).into())); + assert_eq!(gal.into_tbsp(), Tbsp((4 * 2 * 2 * 16).into())); + assert_eq!(gal.into_tbsp(), Tsp((4 * 2 * 2 * 16 * 3).into())); +} + +#[test] +fn test_quantity_math() { + // All frac + let half: Quantity = Ratio::new(1, 2).into(); + assert_eq!(half + half, 1.into()); + assert_eq!(half * half, Ratio::new(1, 4).into()); + assert_eq!(half - half, 0.into()); + assert_eq!(half / half, 1.into()); + // Mix of whole and frac + assert_eq!(Quantity::from(2) * half, 1.into()); + assert_eq!(half * Quantity::from(2), 1.into()); + // All whole + assert_eq!( + Quantity::from(2) / Quantity::from(3), + Quantity::from(Ratio::new(2, 3)) + ); +} + +#[test] +fn test_volume_math() { + let tsp = Tsp(1.into()); + assert_eq!(tsp + tsp, Tsp(2.into())); + assert_eq!(tsp - tsp, Tsp(0.into())); +} + +macro_rules! assert_normalize { + ($typ:path, $conv:ident, $msg:expr) => { + if let $typ(qty) = dbg!($typ(1.into()).$conv().normalize()) { + assert_eq!(qty, 1.into()); + } else { + assert!(false, $msg); + } + }; +} + +#[test] +fn test_volume_normalize() { + assert_normalize!(Tbsp, into_tsp, "not a tablespoon after normalize call"); + assert_normalize!(Floz, into_tbsp, "not a floz after normalize call"); + assert_normalize!(Cup, into_floz, "not a cup after normalize call"); + assert_normalize!(Pint, into_cup, "not a pint after normalize call"); + assert_normalize!(Qrt, into_pint, "not a qrt after normalize call"); + assert_normalize!(Ltr, into_qrt, "not a ltr after normalize call"); + assert_normalize!(Gal, into_ltr, "not a gal after normalize call"); + assert_normalize!(Gal, into_tsp, "not a gal after normalize call"); +} diff --git a/recipes/src/unit.rs b/recipes/src/unit.rs new file mode 100644 index 0000000..a7dc4e6 --- /dev/null +++ b/recipes/src/unit.rs @@ -0,0 +1,396 @@ +// Copyright 2021 Jeremy Wall +// +// 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. +/*! +Numerical measures for Recipe ingredients with math defined for them. +Each of these types implement copy and have the common math operations +defined for them. +*/ + +use std::{ + cmp::{Ordering, PartialEq, PartialOrd}, + convert::TryFrom, + fmt::Display, + ops::{Add, Div, Mul, Sub}, +}; + +use num_rational::Ratio; + +#[derive(Copy, Clone, Debug)] +/// Volume Measurements for ingredients in a recipe. +pub enum VolumeMeasure { + // Imperial volume measurements. US. + /// Teaspoon measurements. + Tsp(Quantity), // 5 ml + /// Tablespoon measurements. + Tbsp(Quantity), // 15 ml + /// Cup measurements. + Cup(Quantity), // 240 ml + /// Pint Measurements + Pint(Quantity), // 475 ml + /// Quart measurements + Qrt(Quantity), // 950 ml + /// Gallon Measurements + Gal(Quantity), // 3800 ml + /// Fluid Ounces + Floz(Quantity), // 30 ml + /// Milliliter Measurements. + // Metric volume measurements. + ML(Quantity), // Base unit + Ltr(Quantity), // 1000 ml +} +use VolumeMeasure::{Cup, Floz, Gal, Ltr, Pint, Qrt, Tbsp, Tsp, ML}; + +// multiplier contants for various units into milliliter. Used in conversion functions. +const TSP: Quantity = Quantity::Whole(5); +const TBSP: Quantity = Quantity::Whole(15); +const FLOZ: Quantity = Quantity::Whole(30); +const CUP: Quantity = Quantity::Whole(240); +const PINT: Quantity = Quantity::Whole(480); +const QRT: Quantity = Quantity::Whole(960); +const LTR: Quantity = Quantity::Whole(1000); +const GAL: Quantity = Quantity::Whole(3840); + +const ONE: Quantity = Quantity::Whole(1); + +impl VolumeMeasure { + /// Get this measures `Quantity` as milliliters. + pub fn get_ml(&self) -> Quantity { + match self { + ML(qty) => *qty, + Tsp(qty) => *qty * TSP, + Tbsp(qty) => *qty * TBSP, + Floz(qty) => *qty * FLOZ, + Cup(qty) => *qty * CUP, + Pint(qty) => *qty * PINT, + Qrt(qty) => *qty * QRT, + Gal(qty) => *qty * GAL, + Ltr(qty) => *qty * LTR, + } + } + + /// Convert into milliliters. + pub fn into_ml(self) -> Self { + ML(self.get_ml()) + } + + /// Convert into teaspoons. + pub fn into_tsp(self) -> Self { + Tsp(self.get_ml() / TSP) + } + + /// Convert into tablespoons. + pub fn into_tbsp(self) -> Self { + Tbsp(self.get_ml() / TBSP) + } + + /// Convert into fluid oz. + pub fn into_floz(self) -> Self { + Floz(self.get_ml() / FLOZ) + } + + /// Convert into cups. + pub fn into_cup(self) -> Self { + Cup(self.get_ml() / CUP) + } + + /// Convert into pints. + pub fn into_pint(self) -> Self { + Pint(self.get_ml() / PINT) + } + + /// Convert into quarts. + pub fn into_qrt(self) -> Self { + Qrt(self.get_ml() / QRT) + } + + /// Convert into gallons. + pub fn into_gal(self) -> Self { + Gal(self.get_ml() / GAL) + } + + /// Convert into liters. + pub fn into_ltr(self) -> Self { + Ltr(self.get_ml() / LTR) + } + + pub fn normalize(self) -> Self { + let ml = self.get_ml(); + if (ml / GAL) >= ONE { + return self.into_gal(); + } + if (ml / LTR) >= ONE { + return self.into_ltr(); + } + if (ml / QRT) >= ONE { + return self.into_qrt(); + } + if (ml / PINT) >= ONE { + return self.into_pint(); + } + if (ml / CUP) >= ONE { + return self.into_cup(); + } + if (ml / FLOZ) >= ONE { + return self.into_floz(); + } + if (ml / TBSP) >= ONE { + return self.into_tbsp(); + } + if (ml / TSP) >= ONE { + return self.into_tsp(); + } + return self.into_ml(); + } +} + +macro_rules! volume_op { + ($trait:ident, $method:ident) => { + impl $trait for VolumeMeasure { + type Output = Self; + + fn $method(self, lhs: Self) -> Self::Output { + let (l, r) = (self.get_ml(), lhs.get_ml()); + ML($trait::$method(l, r)) + } + } + }; +} + +volume_op!(Add, add); +volume_op!(Sub, sub); + +impl PartialEq for VolumeMeasure { + fn eq(&self, lhs: &Self) -> bool { + let rhs = self.get_ml(); + let lhs = lhs.get_ml(); + PartialEq::eq(&rhs, &lhs) + } +} + +impl Display for VolumeMeasure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Tsp(qty) => write!(f, "{} tsp", qty), + Tbsp(qty) => write!(f, "{} tbsp", qty), + Cup(qty) => write!(f, "{} cup", qty), + Pint(qty) => write!(f, "{} pint", qty), + Qrt(qty) => write!(f, "{} qrt", qty), + Gal(qty) => write!(f, "{} gal", qty), + Floz(qty) => write!(f, "{} floz", qty), + ML(qty) => write!(f, "{} ml", qty), + Ltr(qty) => write!(f, "{} ltr", qty), + } + } +} + +#[derive(Copy, Clone, Debug)] +/// Measurements in a Recipe with associated units for them. +pub enum Measure { + /// Volume measurements as meter cubed base unit + Volume(VolumeMeasure), + /// Simple count of items + Count(Quantity), + /// Weight measure as Grams base unit + Gram(Quantity), +} + +use Measure::{Count, Gram, Volume}; + +impl Measure { + pub fn tsp(qty: Quantity) -> Self { + Volume(Tsp(qty)) + } + + pub fn tbsp(qty: Quantity) -> Self { + Volume(Tbsp(qty)) + } + + pub fn cup(qty: Quantity) -> Self { + Volume(Cup(qty)) + } + + pub fn qrt(qty: Quantity) -> Self { + Volume(Qrt(qty)) + } + + pub fn pint(qty: Quantity) -> Self { + Volume(Pint(qty)) + } + + pub fn gal(qty: Quantity) -> Self { + Volume(Gal(qty)) + } + + pub fn count(qty: u32) -> Self { + Count(Whole(qty)) + } + + pub fn gram(qty: Quantity) -> Self { + Gram(qty) + } +} + +impl Display for Measure { + fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Volume(vm) => write!(w, "{}", vm), + Count(qty) => write!(w, "{}", qty), + Gram(qty) => write!(w, "{} grams", qty), + } + } +} + +/// Represents a Quantity for an ingredient of a recipe. +#[derive(Copy, Clone, Debug)] +pub enum Quantity { + /// Whole or non fractional quantities of an ingredient in a recipe. + Whole(u32), + /// Fractional quantities of an ingredient in a recipe. + Frac(Ratio), +} + +impl Quantity { + /// Construct a `Whole` quantity. + pub fn whole(n: u32) -> Self { + Whole(n) + } + + /// Construct a Fractional quantity. + pub fn frac(whole: u32, numer: u32, denom: u32) -> Self { + Frac(Ratio::from_integer(whole) + Ratio::new(numer, denom)) + } + + /// For `Frac` values if the `Quantity` is a whole number normalize the `Whole(n)` type. + /// Otherwise leave the `Quantity` untouched. + pub fn normalize(self) -> Self { + if let Frac(rat) = self { + if rat.is_integer() { + Whole(*rat.numer()) + } else { + Frac(rat) + } + } else { + self + } + } + + /// Extract out the whole and the fractional parts of a `Quantity`. + pub fn extract_parts(self) -> (u32, Ratio) { + match self { + Whole(v) => (v, Ratio::new(0, 1)), + Frac(v) => (v.to_integer(), v.fract()), + } + } + + /// Approximate a quantity as a float. This will lose precision in the case + /// of fractional quantities. + pub fn approx_f32(self) -> f32 { + match self { + Whole(v) => v as f32, + Frac(v) => (*v.numer() / *v.denom()) as f32, + } + } +} +use Quantity::{Frac, Whole}; + +pub struct ConversionError { + pub err_message: String, +} + +impl From> for Quantity { + fn from(r: Ratio) -> Self { + Quantity::Frac(r).normalize() + } +} + +impl From for Quantity { + fn from(u: u32) -> Self { + Quantity::Whole(u) + } +} + +impl TryFrom for Quantity { + type Error = ConversionError; + + fn try_from(f: f32) -> Result { + Ratio::approximate_float(f) + .map(|rat: Ratio| Frac(Ratio::new(*rat.numer() as u32, *rat.denom() as u32))) + .ok_or_else(|| ConversionError { + err_message: format!("Cannot Convert {} into a Rational", f), + }) + } +} + +macro_rules! quantity_op { + ($trait:ident, $method:ident) => { + impl $trait for Quantity { + type Output = Self; + + fn $method(self, lhs: Self) -> Self::Output { + match (self, lhs) { + (Whole(rhs), Whole(lhs)) => Frac($trait::$method( + Ratio::from_integer(rhs), + Ratio::from_integer(lhs), + )), + (Frac(rhs), Frac(lhs)) => Frac($trait::$method(rhs, lhs)), + (Whole(rhs), Frac(lhs)) => Frac($trait::$method(Ratio::from_integer(rhs), lhs)), + (Frac(rhs), Whole(lhs)) => Frac($trait::$method(rhs, Ratio::from_integer(lhs))), + } + } + } + }; +} + +quantity_op!(Add, add); +quantity_op!(Sub, sub); +quantity_op!(Mul, mul); +quantity_op!(Div, div); + +impl PartialOrd for Quantity { + fn partial_cmp(&self, lhs: &Self) -> Option { + match (self, lhs) { + (Whole(rhs), Whole(lhs)) => PartialOrd::partial_cmp(rhs, lhs), + (Frac(rhs), Frac(lhs)) => PartialOrd::partial_cmp(rhs, lhs), + (Whole(rhs), Frac(lhs)) => PartialOrd::partial_cmp(&Ratio::from_integer(*rhs), lhs), + (Frac(rhs), Whole(lhs)) => PartialOrd::partial_cmp(rhs, &Ratio::from_integer(*lhs)), + } + } +} + +impl PartialEq for Quantity { + fn eq(&self, lhs: &Self) -> bool { + match (self, lhs) { + (Whole(rhs), Whole(lhs)) => PartialEq::eq(rhs, lhs), + (Frac(rhs), Frac(lhs)) => PartialEq::eq(rhs, lhs), + (Whole(rhs), Frac(lhs)) => PartialEq::eq(&Ratio::from_integer(*rhs), lhs), + (Frac(rhs), Whole(lhs)) => PartialEq::eq(rhs, &Ratio::from_integer(*lhs)), + } + } +} + +impl Display for Quantity { + fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.normalize() { + Whole(v) => write!(w, "{}", v), + Frac(_) => { + let (whole, frac) = self.extract_parts(); + if whole == 0 { + write!(w, "{}/{}", frac.numer(), frac.denom()) + } else { + write!(w, "{} {}/{}", whole, frac.numer(), frac.denom()) + } + } + } + } +}