Skip to main content

gear_core/
percent.rs

1// Copyright (C) Gear Technologies Inc.
2// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
3
4//! Basic struct for working with integer percentages.
5
6use core::cmp::Ord;
7use num_traits::{Num, cast::NumCast};
8use parity_scale_codec::{Decode, Encode};
9use scale_decode::DecodeAsType;
10use scale_encode::EncodeAsType;
11use scale_info::TypeInfo;
12
13/// Basic struct for working with integer percentages.
14#[derive(
15    Clone,
16    Copy,
17    Debug,
18    PartialEq,
19    Eq,
20    PartialOrd,
21    Ord,
22    Encode,
23    EncodeAsType,
24    Decode,
25    DecodeAsType,
26    TypeInfo,
27)]
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}