iron_ingot/structs/bound/
ubound.rs

1use crate::{DBound, DSeq, FBound, FSeq, IBound};
2use rand::prelude::*;
3
4#[derive(Copy, Clone, Debug)]
5pub struct Arg(u32, u32);
6
7impl From<()> for Arg {
8  fn from(_: ()) -> Self {
9    Self(0, 0)
10  }
11}
12
13impl From<(u32, u32)> for Arg {
14  fn from((a, b): (u32, u32)) -> Self {
15    Self(a, b)
16  }
17}
18
19/// It defines a boundary between the minimum and maximum value.
20#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
21pub struct UBound {
22  min: u32,
23  max: u32,
24}
25
26impl UBound {
27  pub fn new(arg: impl Into<Arg>) -> Self {
28    let Arg(a, b) = arg.into();
29    Self {
30      min: a.min(b),
31      max: a.max(b),
32    }
33  }
34
35  pub const fn get_min(&self) -> u32 {
36    self.min
37  }
38
39  pub fn get_middle(&self) -> u32 {
40    (self.min + self.max) >> 1
41  }
42
43  pub const fn get_max(&self) -> u32 {
44    self.max
45  }
46
47  /// It checks whether the boundary received overlaps with this boundary.
48  ///
49  /// `other` The boundary to be checked with.
50  ///
51  /// It returns true if both boundaries overlaps, false otherwise.
52  pub fn is_intersect(&self, other: UBound) -> bool {
53    self.min <= other.max && self.max >= other.min
54  }
55
56  /// It finds out the intersection between both boundaries received as a boundary.
57  ///
58  /// `other`: The boundary to intersect with.
59  ///
60  /// It returns an intersection as a boundary if exist.
61  pub fn intersect(&self, other: UBound) -> Option<UBound> {
62    if self.is_intersect(other) {
63      Some(UBound::new((
64        self.min.max(other.min),
65        self.max.min(other.max),
66      )))
67    } else {
68      None
69    }
70  }
71
72  pub fn has(&self, value: u32) -> bool {
73    value >= self.min && value <= self.max
74  }
75
76  /// It returns a random value in this boundary.
77  pub fn rand(&self) -> u32 {
78    thread_rng().gen_range(self.min..=self.max)
79  }
80}
81
82impl From<DBound> for UBound {
83  fn from(bound: DBound) -> Self {
84    Self::new((bound.get_min() as _, bound.get_max() as _))
85  }
86}
87
88impl From<FBound> for UBound {
89  fn from(bound: FBound) -> Self {
90    Self::new((bound.get_min() as _, bound.get_max() as _))
91  }
92}
93
94impl From<IBound> for UBound {
95  fn from(bound: IBound) -> Self {
96    Self::new((bound.get_min() as _, bound.get_max() as _))
97  }
98}
99
100impl From<DSeq> for UBound {
101  fn from(seq: DSeq) -> Self {
102    Self::new((seq.get_a() as _, seq.get_b() as _))
103  }
104}
105
106impl From<FSeq> for UBound {
107  fn from(seq: FSeq) -> Self {
108    Self::new((seq.get_a() as _, seq.get_b() as _))
109  }
110}