near_sdk_core/
allowance.rs1use std::num::NonZeroU128;
2
3use near_token::NearToken;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum Allowance {
9 Unlimited,
10 Limited(NonZeroU128),
11}
12
13impl Allowance {
14 pub fn unlimited() -> Allowance {
15 Allowance::Unlimited
16 }
17
18 pub fn limited(balance: NearToken) -> Option<Allowance> {
20 NonZeroU128::new(balance.as_yoctonear()).map(Allowance::Limited)
21 }
22}
23
24#[cfg(feature = "serde")]
25impl serde::Serialize for Allowance {
26 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
27 where
28 S: serde::Serializer,
29 {
30 match self {
31 Allowance::Unlimited => serializer.serialize_none(),
32 Allowance::Limited(v) => serializer.serialize_some(&v.get()),
33 }
34 }
35}
36
37#[cfg(feature = "serde")]
38impl<'de> serde::Deserialize<'de> for Allowance {
39 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
40 where
41 D: serde::Deserializer<'de>,
42 {
43 let opt: Option<u128> =
44 <std::option::Option<_> as serde::Deserialize>::deserialize(deserializer)?;
45 match opt {
46 None => Ok(Allowance::Unlimited),
47 Some(val) => {
48 let nz = NonZeroU128::new(val)
49 .ok_or_else(|| serde::de::Error::custom("allowance cannot be zero"))?;
50 Ok(Allowance::Limited(nz))
51 }
52 }
53 }
54}
55
56#[cfg(feature = "borsh")]
57impl borsh::BorshSerialize for Allowance {
58 fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
59 let opt: Option<u128> = match self {
60 Allowance::Unlimited => None,
61 Allowance::Limited(v) => Some(v.get()),
62 };
63 borsh::BorshSerialize::serialize(&opt, writer)
64 }
65}
66
67#[cfg(feature = "borsh")]
68impl borsh::BorshDeserialize for Allowance {
69 fn deserialize_reader<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
70 let opt: Option<u128> = borsh::de::from_reader(reader)?;
71 match opt {
72 None => Ok(Allowance::Unlimited),
73 Some(val) => {
74 let nz = NonZeroU128::new(val).ok_or_else(|| {
75 borsh::io::Error::new(
76 borsh::io::ErrorKind::InvalidData,
77 "allowance cannot be zero",
78 )
79 })?;
80 Ok(Allowance::Limited(nz))
81 }
82 }
83 }
84}
85
86#[cfg(test)]
87mod test {
88 use crate::{allowance::Allowance, types::NearToken};
89
90 #[cfg(feature = "borsh")]
91 #[test]
92 fn test_allowance_borsh() {
93 let unlimited = Allowance::Unlimited;
94 let opt_none: Option<u128> = Option::None;
95 assert_eq!(borsh::to_vec(&unlimited).unwrap(), borsh::to_vec(&opt_none).unwrap());
96
97 let limited = Allowance::limited(NearToken::from_yoctonear(1)).unwrap();
98 let token = Some(NearToken::from_yoctonear(1));
99 assert_eq!(borsh::to_vec(&limited).unwrap(), borsh::to_vec(&token).unwrap());
100 }
101
102 #[test]
103 fn test_allowance_debug() {
104 let unlimited = Allowance::Unlimited;
105 assert_eq!(format!("{:?}", unlimited), "Unlimited");
106
107 let limited = Allowance::Limited(100.try_into().unwrap());
108 assert_eq!(format!("{:?}", limited), "Limited(100)");
109 }
110
111 #[test]
112 fn test_allowance_eq() {
113 assert_eq!(Allowance::Unlimited, Allowance::Unlimited);
114 assert_eq!(
115 Allowance::Limited(100.try_into().unwrap()),
116 Allowance::Limited(100.try_into().unwrap())
117 );
118 assert_ne!(Allowance::Unlimited, Allowance::Limited(100.try_into().unwrap()));
119 assert_ne!(
120 Allowance::Limited(100.try_into().unwrap()),
121 Allowance::Limited(200.try_into().unwrap())
122 );
123 }
124
125 #[test]
126 fn test_allowance_copy() {
127 let a = Allowance::Unlimited;
128 let b = a; assert_eq!(a, b);
130
131 let c = Allowance::Limited(500.try_into().unwrap());
132 let d = c; assert_eq!(c, d);
134 }
135
136 #[test]
137 fn test_allowance_hash() {
138 use std::collections::HashSet;
139 let mut set = HashSet::new();
140 set.insert(Allowance::Unlimited);
141 set.insert(Allowance::Limited(100.try_into().unwrap()));
142 set.insert(Allowance::Unlimited); assert_eq!(set.len(), 2);
144 }
145
146 #[test]
147 fn test_allowance_limited_zero_returns_none() {
148 assert!(Allowance::limited(NearToken::from_yoctonear(0)).is_none());
149 }
150
151 #[test]
152 fn test_allowance_limited_nonzero() {
153 let allowance = Allowance::limited(NearToken::from_yoctonear(100));
154 assert_eq!(allowance, Some(Allowance::Limited(100.try_into().unwrap())));
155 }
156}