crypto_bigint/
wrapping.rs
1use crate::Zero;
4use core::fmt;
5use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
6
7#[cfg(feature = "serde")]
8use serdect::serde::{Deserialize, Deserializer, Serialize, Serializer};
9
10#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
15pub struct Wrapping<T>(pub T);
16
17impl<T: Zero> Zero for Wrapping<T> {
18 const ZERO: Self = Self(T::ZERO);
19}
20
21impl<T: fmt::Display> fmt::Display for Wrapping<T> {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 self.0.fmt(f)
24 }
25}
26
27impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 self.0.fmt(f)
30 }
31}
32
33impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 self.0.fmt(f)
36 }
37}
38
39impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 self.0.fmt(f)
42 }
43}
44
45impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 self.0.fmt(f)
48 }
49}
50
51impl<T: ConditionallySelectable> ConditionallySelectable for Wrapping<T> {
52 fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
53 Wrapping(T::conditional_select(&a.0, &b.0, choice))
54 }
55}
56
57impl<T: ConstantTimeEq> ConstantTimeEq for Wrapping<T> {
58 fn ct_eq(&self, other: &Self) -> Choice {
59 self.0.ct_eq(&other.0)
60 }
61}
62
63#[cfg(feature = "serde")]
64#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
65impl<'de, T: Deserialize<'de>> Deserialize<'de> for Wrapping<T> {
66 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
67 where
68 D: Deserializer<'de>,
69 {
70 Ok(Self(T::deserialize(deserializer)?))
71 }
72}
73
74#[cfg(feature = "serde")]
75#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
76impl<'de, T: Serialize> Serialize for Wrapping<T> {
77 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
78 where
79 S: Serializer,
80 {
81 self.0.serialize(serializer)
82 }
83}
84
85#[cfg(all(test, feature = "serde"))]
86mod tests {
87 use crate::{Wrapping, U64};
88
89 #[test]
90 fn serde() {
91 const TEST: Wrapping<U64> = Wrapping(U64::from_u64(0x0011223344556677));
92
93 let serialized = bincode::serialize(&TEST).unwrap();
94 let deserialized: Wrapping<U64> = bincode::deserialize(&serialized).unwrap();
95
96 assert_eq!(TEST, deserialized);
97 }
98
99 #[test]
100 fn serde_owned() {
101 const TEST: Wrapping<U64> = Wrapping(U64::from_u64(0x0011223344556677));
102
103 let serialized = bincode::serialize(&TEST).unwrap();
104 let deserialized: Wrapping<U64> = bincode::deserialize_from(serialized.as_slice()).unwrap();
105
106 assert_eq!(TEST, deserialized);
107 }
108}