Skip to main content

nil_core/ranking/
score.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use derive_more::{Deref, From, Into};
5use nil_num::impl_mul_ceil;
6use serde::{Deserialize, Serialize};
7use std::cmp::Ordering;
8use std::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign};
9
10#[derive(
11  Clone,
12  Copy,
13  Debug,
14  Default,
15  Deref,
16  From,
17  Into,
18  PartialEq,
19  Eq,
20  PartialOrd,
21  Ord,
22  Deserialize,
23  Serialize,
24  nil_num::F64Ops,
25)]
26#[into(u32, f64)]
27pub struct Score(u32);
28
29impl Score {
30  pub const ZERO: Score = Score(0);
31
32  #[inline]
33  pub const fn new(value: u32) -> Self {
34    Self(value)
35  }
36}
37
38impl From<f64> for Score {
39  fn from(value: f64) -> Self {
40    Self::new(value as u32)
41  }
42}
43
44impl PartialEq<u32> for Score {
45  fn eq(&self, other: &u32) -> bool {
46    self.0.eq(other)
47  }
48}
49
50impl PartialOrd<u32> for Score {
51  fn partial_cmp(&self, other: &u32) -> Option<Ordering> {
52    self.0.partial_cmp(other)
53  }
54}
55
56impl Add for Score {
57  type Output = Score;
58
59  fn add(self, rhs: Self) -> Self::Output {
60    Self(self.0.saturating_add(rhs.0))
61  }
62}
63
64impl AddAssign for Score {
65  fn add_assign(&mut self, rhs: Self) {
66    *self = *self + rhs;
67  }
68}
69
70impl Add<u32> for Score {
71  type Output = Score;
72
73  fn add(self, rhs: u32) -> Self::Output {
74    Self(self.0.saturating_add(rhs))
75  }
76}
77
78impl AddAssign<u32> for Score {
79  fn add_assign(&mut self, rhs: u32) {
80    *self = *self + rhs;
81  }
82}
83
84impl Sub for Score {
85  type Output = Score;
86
87  fn sub(self, rhs: Self) -> Self::Output {
88    Self(self.0.saturating_sub(rhs.0))
89  }
90}
91
92impl SubAssign for Score {
93  fn sub_assign(&mut self, rhs: Self) {
94    *self = *self - rhs;
95  }
96}
97
98impl Mul for Score {
99  type Output = Score;
100
101  fn mul(self, rhs: Score) -> Self::Output {
102    Self(self.0.saturating_mul(rhs.0))
103  }
104}
105
106impl Mul<u32> for Score {
107  type Output = Score;
108
109  fn mul(self, rhs: u32) -> Self::Output {
110    Self(self.0.saturating_mul(rhs))
111  }
112}
113
114impl MulAssign for Score {
115  fn mul_assign(&mut self, rhs: Self) {
116    *self = *self * rhs;
117  }
118}
119
120impl_mul_ceil!(Score);