1use std::cell::Cell;
2use std::cmp::Ordering;
3use std::fmt;
4
5use std::ops::{Deref, DerefMut};
6
7#[repr(transparent)]
13#[derive(Default)]
14pub struct MathCell<T>(Cell<T>);
15
16impl<T> MathCell<T>
17{
18 #[inline(always)]
20 pub const fn new(value: T) -> Self
21 {
22 MathCell(Cell::new(value))
23 }
24
25 pub fn into_inner(self) -> T
27 {
28 Cell::into_inner(self.0)
29 }
30
31 pub fn swap(&self, other: &Self)
33 {
34 Cell::swap(&self.0, &other.0)
35 }
36}
37
38impl<T> Deref for MathCell<T>
39{
40 type Target = Cell<T>;
41 #[inline(always)]
42 fn deref(&self) -> &Self::Target
43 {
44 &self.0
45 }
46}
47
48impl<T> DerefMut for MathCell<T>
49{
50 #[inline(always)]
51 fn deref_mut(&mut self) -> &mut Self::Target
52 {
53 &mut self.0
54 }
55}
56
57impl<T> Clone for MathCell<T>
58where T: Copy
59{
60 fn clone(&self) -> Self
61 {
62 MathCell::new(self.get())
63 }
64}
65
66impl<T> PartialEq for MathCell<T>
67where T: Copy + PartialEq
68{
69 fn eq(&self, rhs: &Self) -> bool
70 {
71 self.get() == rhs.get()
72 }
73}
74
75impl<T> Eq for MathCell<T> where T: Copy + Eq {}
76
77impl<T> PartialOrd for MathCell<T>
78where T: Copy + PartialOrd
79{
80 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering>
81 {
82 self.get().partial_cmp(&rhs.get())
83 }
84
85 fn lt(&self, rhs: &Self) -> bool
86 {
87 self.get().lt(&rhs.get())
88 }
89 fn le(&self, rhs: &Self) -> bool
90 {
91 self.get().le(&rhs.get())
92 }
93 fn gt(&self, rhs: &Self) -> bool
94 {
95 self.get().gt(&rhs.get())
96 }
97 fn ge(&self, rhs: &Self) -> bool
98 {
99 self.get().ge(&rhs.get())
100 }
101}
102
103impl<T> Ord for MathCell<T>
104where T: Copy + Ord
105{
106 fn cmp(&self, rhs: &Self) -> Ordering
107 {
108 self.get().cmp(&rhs.get())
109 }
110}
111
112impl<T> fmt::Debug for MathCell<T>
113where T: Copy + fmt::Debug
114{
115 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
116 {
117 self.get().fmt(f)
118 }
119}
120
121#[cfg(test)]
122mod tests
123{
124 use super::MathCell;
125
126 #[test]
127 fn test_basic()
128 {
129 let c = &MathCell::new(0);
130 c.set(1);
131 assert_eq!(c.get(), 1);
132 }
133}