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