Skip to main content

nil_core/continent/
size.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use derive_more::Display;
5use nil_util::ConstDeref;
6use serde::{Deserialize, Serialize};
7use std::cmp::Ordering;
8use std::num::NonZeroU8;
9
10#[derive(Copy, Debug, Display, Deserialize, Serialize, ConstDeref)]
11#[derive_const(Clone, PartialEq, Eq, PartialOrd, Ord)]
12#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
13pub struct ContinentSize(NonZeroU8);
14
15impl ContinentSize {
16  pub const MIN: ContinentSize = unsafe { Self::new_unchecked(100) };
17  pub const MAX: ContinentSize = unsafe { Self::new_unchecked(200) };
18
19  pub const fn new(size: u8) -> Self {
20    let size = size
21      .clamp(Self::MIN.0.get(), Self::MAX.0.get())
22      .next_multiple_of(10);
23
24    unsafe { Self::new_unchecked(size) }
25  }
26
27  /// # Safety
28  ///
29  /// The size must be between [`ContinentSize::MIN`] and [`ContinentSize::MAX`].
30  #[inline]
31  pub const unsafe fn new_unchecked(size: u8) -> Self {
32    Self(unsafe { NonZeroU8::new_unchecked(size) })
33  }
34}
35
36impl const Default for ContinentSize {
37  fn default() -> Self {
38    Self::MIN
39  }
40}
41
42impl const From<u8> for ContinentSize {
43  fn from(value: u8) -> Self {
44    Self::new(value)
45  }
46}
47
48impl const From<ContinentSize> for u8 {
49  fn from(value: ContinentSize) -> Self {
50    value.0.get()
51  }
52}
53
54impl const From<ContinentSize> for u16 {
55  fn from(value: ContinentSize) -> Self {
56    u16::from(value.0.get())
57  }
58}
59
60impl const From<ContinentSize> for usize {
61  fn from(value: ContinentSize) -> Self {
62    usize::from(value.0.get())
63  }
64}
65
66impl const From<ContinentSize> for i16 {
67  fn from(value: ContinentSize) -> Self {
68    i16::from(value.0.get())
69  }
70}
71
72impl const From<ContinentSize> for f64 {
73  fn from(value: ContinentSize) -> Self {
74    f64::from(value.0.get())
75  }
76}
77
78impl const PartialEq<u8> for ContinentSize {
79  fn eq(&self, other: &u8) -> bool {
80    self.0.get().eq(other)
81  }
82}
83
84impl const PartialEq<usize> for ContinentSize {
85  fn eq(&self, other: &usize) -> bool {
86    usize::from(self.0.get()).eq(other)
87  }
88}
89
90impl const PartialEq<ContinentSize> for usize {
91  fn eq(&self, other: &ContinentSize) -> bool {
92    self.eq(&usize::from(other.0.get()))
93  }
94}
95
96impl const PartialOrd<u8> for ContinentSize {
97  fn partial_cmp(&self, other: &u8) -> Option<Ordering> {
98    self.0.get().partial_cmp(other)
99  }
100}
101
102impl const PartialOrd<usize> for ContinentSize {
103  fn partial_cmp(&self, other: &usize) -> Option<Ordering> {
104    usize::from(self.0.get()).partial_cmp(other)
105  }
106}
107
108impl const PartialOrd<ContinentSize> for usize {
109  fn partial_cmp(&self, other: &ContinentSize) -> Option<Ordering> {
110    self.partial_cmp(&usize::from(other.0.get()))
111  }
112}