gear_core/
percent.rs

1// This file is part of Gear.
2
3// Copyright (C) 2021-2025 Gear Technologies Inc.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! Basic struct for working with integer percentages.
20
21use core::cmp::Ord;
22use num_traits::{Num, cast::NumCast};
23use parity_scale_codec::{Decode, Encode};
24use scale_info::TypeInfo;
25
26/// Basic struct for working with integer percentages.
27#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Encode, Decode, TypeInfo)]
28pub struct Percent(u32);
29
30impl Percent {
31    /// Creates a new `Percent` from a `u32` value. The value can be
32    /// greater than 100.
33    pub fn new(value: u32) -> Self {
34        Self(value)
35    }
36
37    /// Returns the inner `u32` value.
38    pub fn value(self) -> u32 {
39        self.0
40    }
41
42    /// Applies the percentage to the given value.
43    pub fn apply_to<T: Num + Ord + Copy + NumCast>(&self, value: T) -> T {
44        (value * NumCast::from(self.0).unwrap()) / NumCast::from(100).unwrap()
45    }
46}
47
48impl From<u32> for Percent {
49    fn from(value: u32) -> Self {
50        Self::new(value)
51    }
52}
53
54impl From<Percent> for gsys::Percent {
55    fn from(value: Percent) -> Self {
56        gsys::Percent::new(value.value())
57    }
58}