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
// Copyright 2021 CoD Technologies Corp.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! serde implementation.

use crate::decimal::{Buf, Decimal};

#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl serde::Serialize for Decimal {
    #[inline]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::ser::Serializer,
    {
        use std::io::Write;

        let mut buf = Buf::new();
        if serializer.is_human_readable() {
            write!(&mut buf, "{}", self).map_err(serde::ser::Error::custom)?;
            let str = unsafe { std::str::from_utf8_unchecked(buf.as_slice()) };
            str.serialize(serializer)
        } else {
            self.encode(&mut buf).map_err(serde::ser::Error::custom)?;
            buf.as_slice().serialize(serializer)
        }
    }
}

#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de> serde::Deserialize<'de> for Decimal {
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        struct DecimalVisitor;

        impl<'de> serde::de::Visitor<'de> for DecimalVisitor {
            type Value = Decimal;

            #[inline]
            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(formatter, "a decimal")
            }

            #[inline]
            fn visit_str<E>(self, v: &str) -> Result<Decimal, E>
            where
                E: serde::de::Error,
            {
                v.parse().map_err(serde::de::Error::custom)
            }

            #[inline]
            fn visit_bytes<E>(self, v: &[u8]) -> Result<Decimal, E>
            where
                E: serde::de::Error,
            {
                let n = Decimal::decode(v);
                Ok(n)
            }
        }

        if deserializer.is_human_readable() {
            deserializer.deserialize_str(DecimalVisitor)
        } else {
            deserializer.deserialize_bytes(DecimalVisitor)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_serde() {
        let dec = "123.456".parse::<Decimal>().unwrap();

        let json = serde_json::to_string(&dec).unwrap();
        assert_eq!(json, r#""123.456""#);
        let json_dec: Decimal = serde_json::from_str(&json).unwrap();
        assert_eq!(json_dec, dec);

        let bin = bincode::serialize(&dec).unwrap();
        let bin_dec: Decimal = bincode::deserialize(&bin).unwrap();
        assert_eq!(bin_dec, dec);
    }
}