1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
use serde::{de, ser};
use std::error::Error;
use std::fmt;
use std::ops::Deref;
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct SafeLong(i64);
impl SafeLong {
#[inline]
pub fn min_value() -> SafeLong {
SafeLong(-(1 << 53) + 1)
}
#[inline]
pub fn max_value() -> SafeLong {
SafeLong((1 << 53) - 1)
}
#[inline]
#[allow(clippy::new_ret_no_self)]
pub fn new(value: i64) -> Result<SafeLong, BoundsError> {
if value >= *SafeLong::min_value() && value <= *SafeLong::max_value() {
Ok(SafeLong(value))
} else {
Err(BoundsError(()))
}
}
}
impl Deref for SafeLong {
type Target = i64;
#[inline]
fn deref(&self) -> &i64 {
&self.0
}
}
impl fmt::Display for SafeLong {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, fmt)
}
}
impl ser::Serialize for SafeLong {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
s.serialize_i64(self.0)
}
}
impl<'de> de::Deserialize<'de> for SafeLong {
fn deserialize<D>(d: D) -> Result<SafeLong, D::Error>
where
D: de::Deserializer<'de>,
{
let value = i64::deserialize(d)?;
SafeLong::new(value)
.map_err(|_| de::Error::invalid_value(de::Unexpected::Signed(value), &"a safe long"))
}
}
#[derive(Debug, Clone)]
pub struct BoundsError(());
impl fmt::Display for BoundsError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("value was out of bounds of a safe long")
}
}
impl Error for BoundsError {}