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_decode::DecodeAsType;
25use scale_encode::EncodeAsType;
26use scale_info::TypeInfo;
27
28/// Basic struct for working with integer percentages.
29#[derive(
30 Clone,
31 Copy,
32 Debug,
33 PartialEq,
34 Eq,
35 PartialOrd,
36 Ord,
37 Encode,
38 EncodeAsType,
39 Decode,
40 DecodeAsType,
41 TypeInfo,
42)]
43pub struct Percent(u32);
44
45impl Percent {
46 /// Creates a new `Percent` from a `u32` value. The value can be
47 /// greater than 100.
48 pub fn new(value: u32) -> Self {
49 Self(value)
50 }
51
52 /// Returns the inner `u32` value.
53 pub fn value(self) -> u32 {
54 self.0
55 }
56
57 /// Applies the percentage to the given value.
58 pub fn apply_to<T: Num + Ord + Copy + NumCast>(&self, value: T) -> T {
59 (value * NumCast::from(self.0).unwrap()) / NumCast::from(100).unwrap()
60 }
61}
62
63impl From<u32> for Percent {
64 fn from(value: u32) -> Self {
65 Self::new(value)
66 }
67}
68
69impl From<Percent> for gsys::Percent {
70 fn from(value: Percent) -> Self {
71 gsys::Percent::new(value.value())
72 }
73}