#serde-serialize #error #serialization #serde #macro

impl_serialize

用于在 serde::Serializer trait 中实现常见方法的宏

7 个稳定版本

3.1.4 2022 年 10 月 16 日
3.1.3 2022 年 9 月 6 日
2.0.1 2022 年 9 月 3 日
1.0.0 2022 年 9 月 2 日

#938编码

每月 21 次下载
用于 json_map_serializer

MIT/Apache 协议

29KB
685

impl_serialize!

该库提供了一个简单的过程宏,用于快速在 serde::Serializer trait 中实现序列化方法。

[dependencies]
impl_serialize = "3.1"

示例

了解如何在 impl_serialize! 内部使用 元变量

use impl_serialize::impl_serialize;
use serde::ser;
use thiserror::Error;

#[derive(Debug, Error)]
enum SerializationError {
    #[error("Other error")]
    OtherError,
    #[error("Cannot serialize value from {0}")]
    CannotSerializeFrom(String),
    #[error("Custom({0})")]
    Custom(String)
}

impl serde::ser::Error for SerializationError {
    fn custom<T>(msg:T) -> Self
    where T: std::fmt::Display
    {
        SerializationError::Custom(msg.to_string())
    }
}

struct MySerializer;

impl ser::Serializer for MySerializer {
    type Ok = ();
    type Error = SerializationError;

    type SerializeMap = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeSeq = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeStruct = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeStructVariant = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeTuple = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeTupleStruct = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeTupleVariant = ser::Impossible<Self::Ok, Self::Error>;

    //value_type is metavariable (&str) what represents any serializing value type.
    //for example, value_type will be "i8" when seializing i8 or "bytes" when &[u8] (bytes);

    //with value_type
    impl_serialize!(
        Err(SerializationError::CannotSerializeFrom(value_type.to_string())),
        bool
    );
    
    //without value_type
    impl_serialize!(
        Err(SerializationError::OtherError),
        char
    );
    
    //for many types
    impl_serialize!(
        Err(SerializationError::CannotSerializeFrom(value_type.to_string())),
        [
            bytes,
            i8, i16, i32, i64,
            u8, u16, u32, u64,
            f32, f64,
            str,
            none, some, unit,
            unit_struct, unit_variant,
            newtype_struct, newtype_variant,
            seq, map,
            tuple, tuple_struct, tuple_variant,
            struct, struct_variant
        ]
    );
}

依赖关系

~110–345KB