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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
//! [BSON Decimal128](https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.rst) data type representation

#[cfg(feature = "decimal128")]
use decimal::d128;
use std::fmt;

/// Decimal128 type.
///
/// Currently, this type does not have any functionality and can only be serialized and
/// deserialized from existing documents that contain BSON decimal128s.
///
/// Experimental functionality can be enabled through the usage of the `"decimal128"`
/// feature flag. Note that the API and behavior of such functionality are unstable and
/// subject to change.
#[derive(Clone, PartialEq, PartialOrd)]
pub struct Decimal128 {
    #[cfg(not(feature = "decimal128"))]
    /// BSON bytes containing the decimal128. Stored for round tripping.
    pub(crate) bytes: [u8; 128 / 8],

    #[cfg(feature = "decimal128")]
    inner: decimal::d128,
}

#[cfg(feature = "decimal128")]
impl Decimal128 {
    /// Construct a `Decimal128` from string.
    ///
    /// For example:
    ///
    /// * `NaN`
    /// * `Infinity` or `Inf`
    /// * `1.0`, `+37.0`, `0.73e-7`, `.5`
    ///
    /// ```rust
    /// use bson::decimal128::Decimal128;
    ///
    /// let dec128 = Decimal128::from_str("1.05E+3");
    /// ```
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Decimal128 {
        Decimal128 {
            inner: s.parse::<d128>().expect("Invalid Decimal128 string"),
        }
    }

    /// Construct a `Decimal128` from a `i32` number.
    ///
    /// ```rust
    /// use bson::decimal128::Decimal128;
    ///
    /// let num: i32 = 23;
    /// let dec128 = Decimal128::from_i32(num);
    /// ```
    pub fn from_i32(d: i32) -> Decimal128 {
        Decimal128 {
            inner: From::from(d),
        }
    }

    /// Construct a `Decimal128` from a `u32` number.
    ///
    /// ```rust
    /// use bson::decimal128::Decimal128;
    ///
    /// let num: u32 = 78;
    /// let dec128 = Decimal128::from_u32(num);
    /// ```
    pub fn from_u32(d: u32) -> Decimal128 {
        Decimal128 {
            inner: From::from(d),
        }
    }

    /// Construct a `Decimal128` from a `i32` number.
    ///
    /// ```rust
    /// use bson::decimal128::Decimal128;
    ///
    /// let num: i32 = 23;
    /// let dec128 = Decimal128::from_i32(num);
    /// let int = dec128.into_i32();
    /// assert_eq!(int, num);
    /// ```
    #[allow(clippy::wrong_self_convention)]
    #[deprecated(since = "0.15.0", note = "Replaced by `to_i32`")]
    pub fn into_i32(&self) -> i32 {
        Into::into(self.inner)
    }

    /// Construct a `Decimal128` from a `i32` number.
    ///
    /// ```rust
    /// use bson::decimal128::Decimal128;
    ///
    /// let num: i32 = 23;
    /// let dec128 = Decimal128::from_i32(num);
    /// let int = dec128.to_i32();
    /// assert_eq!(int, num);
    /// ```
    pub fn to_i32(&self) -> i32 {
        Into::into(self.inner)
    }

    /// Construct a `Decimal128` from a `i32` number.
    ///
    /// ```rust
    /// use bson::decimal128::Decimal128;
    ///
    /// let num: u32 = 23;
    /// let dec128 = Decimal128::from_u32(num);
    /// let int = dec128.into_u32();
    /// assert_eq!(int, num);
    /// ```
    #[allow(clippy::wrong_self_convention)]
    #[deprecated(since = "0.15.0", note = "Replaced by `to_u32`")]
    pub fn into_u32(&self) -> u32 {
        Into::into(self.inner)
    }

    /// Construct a `Decimal128` from a `i32` number.
    ///
    /// ```rust
    /// use bson::decimal128::Decimal128;
    ///
    /// let num: u32 = 23;
    /// let dec128 = Decimal128::from_u32(num);
    /// let int = dec128.to_u32();
    /// assert_eq!(int, num);
    /// ```
    pub fn to_u32(&self) -> u32 {
        Into::into(self.inner)
    }

    /// Create a new Decimal128 as `0`.
    ///
    /// ```rust
    /// use bson::decimal128::Decimal128;
    ///
    /// let dec128 = Decimal128::zero();
    /// ```
    pub fn zero() -> Decimal128 {
        Decimal128 {
            inner: d128::zero(),
        }
    }

    #[doc(hidden)]
    pub unsafe fn from_raw_bytes_le(mut raw: [u8; 16]) -> Decimal128 {
        if cfg!(target_endian = "big") {
            raw.reverse();
        }

        Decimal128 {
            inner: d128::from_raw_bytes(raw),
        }
    }

    #[doc(hidden)]
    pub fn to_raw_bytes_le(&self) -> [u8; 16] {
        let mut buf = self.inner.to_raw_bytes();
        if cfg!(target_endian = "big") {
            buf.reverse();
        }
        buf
    }

    /// Check if value is `NaN`
    ///
    /// ```rust
    /// use bson::decimal128::Decimal128;
    ///
    /// let num: u32 = 78;
    /// let dec128 = Decimal128::from_u32(num);
    /// assert!(!dec128.is_nan());
    /// ```
    pub fn is_nan(&self) -> bool {
        self.inner.is_nan()
    }

    /// Check if value is 0
    ///
    /// ```rust
    /// use bson::decimal128::Decimal128;
    ///
    /// let num: u32 = 0;
    /// let dec128 = Decimal128::from_u32(num);
    /// assert!(dec128.is_zero());
    /// ```
    pub fn is_zero(&self) -> bool {
        self.inner.is_zero()
    }
}

impl fmt::Debug for Decimal128 {
    #[cfg(feature = "decimal128")]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Decimal128(\"{:?}\")", self.inner)
    }

    #[cfg(not(feature = "decimal128"))]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Decimal128(...)")
    }
}

impl fmt::Display for Decimal128 {
    #[cfg(feature = "decimal128")]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.inner)
    }

    #[cfg(not(feature = "decimal128"))]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

#[cfg(feature = "decimal128")]
impl fmt::LowerHex for Decimal128 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        <d128 as fmt::LowerHex>::fmt(&self.inner, f)
    }
}

#[cfg(feature = "decimal128")]
impl fmt::LowerExp for Decimal128 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        <d128 as fmt::LowerExp>::fmt(&self.inner, f)
    }
}

#[cfg(feature = "decimal128")]
impl std::str::FromStr for Decimal128 {
    type Err = ();
    fn from_str(s: &str) -> Result<Decimal128, ()> {
        Ok(Decimal128::from_str(s))
    }
}

#[cfg(feature = "decimal128")]
impl Into<d128> for Decimal128 {
    fn into(self) -> d128 {
        self.inner
    }
}

#[cfg(feature = "decimal128")]
impl From<d128> for Decimal128 {
    fn from(d: d128) -> Decimal128 {
        Decimal128 { inner: d }
    }
}

#[cfg(feature = "decimal128")]
impl Default for Decimal128 {
    fn default() -> Decimal128 {
        Decimal128::zero()
    }
}

#[cfg(test)]
#[cfg(feature = "decimal128")]
mod test {
    use super::*;

    #[test]
    fn decimal128_string() {
        assert!(Decimal128::from_str("0").is_zero());
        assert!(!Decimal128::from_str("12").is_nan());
        assert!(!Decimal128::from_str("-76").is_nan());
        assert!(!Decimal128::from_str("12.70").is_nan());
        assert!(!Decimal128::from_str("+0.003").is_nan());
        assert!(!Decimal128::from_str("017.").is_nan());
        assert!(!Decimal128::from_str(".5").is_nan());
        assert!(!Decimal128::from_str("4E+9").is_nan());
        assert!(!Decimal128::from_str("0.73e-7").is_nan());
        assert!(!Decimal128::from_str("Inf").is_nan());
        assert!(!Decimal128::from_str("-infinity").is_nan());
        assert!(Decimal128::from_str("NaN").is_nan());
    }

    #[test]
    fn decimal128_i32() {
        let num: i32 = 89;
        let dec128 = Decimal128::from_i32(num);

        assert!(!dec128.is_nan());
        assert!(!dec128.is_zero());
        assert_eq!(dec128.to_i32(), num);
    }

    #[test]
    fn decimal128_u32() {
        let num: u32 = 89;
        let dec128 = Decimal128::from_u32(num);

        assert!(!dec128.is_nan());
        assert!(!dec128.is_zero());
        assert_eq!(dec128.to_u32(), num);
    }

    #[test]
    fn decimal128_0() {
        let dec128 = Decimal128::zero();
        assert!(dec128.is_zero());
    }

    #[test]
    fn decimal128_is_zero() {
        let dec128 = Decimal128::from_i32(234);
        assert!(!dec128.is_zero());

        let dec128_0 = Decimal128::from_i32(0);
        assert!(dec128_0.is_zero());
    }

    #[test]
    fn decimal128_is_nan() {
        let dec128 = Decimal128::from_str("NaN");
        assert!(dec128.is_nan());

        let dec128 = Decimal128::from_i32(234);
        assert!(!dec128.is_nan());
    }
}