https://github.com/trard/impl_serialize
Macro for fast implementing serialize methods in serde::Serializer trait
https://github.com/trard/impl_serialize
error macro macros serde serde-serialization
Last synced: 12 months ago
JSON representation
Macro for fast implementing serialize methods in serde::Serializer trait
- Host: GitHub
- URL: https://github.com/trard/impl_serialize
- Owner: Trard
- License: mit
- Created: 2022-09-01T10:12:20.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2022-10-16T09:06:07.000Z (over 3 years ago)
- Last Synced: 2024-03-15T07:49:32.425Z (over 2 years ago)
- Topics: error, macro, macros, serde, serde-serialization
- Language: Rust
- Homepage: https://crates.io/crates/impl_serialize
- Size: 33.2 KB
- Stars: 3
- Watchers: 0
- Forks: 0
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# impl_serialize!
This library provides a simple procedural macro for fast implementing serialize methods in [`serde::Serializer`] trait.
```toml
[dependencies]
impl_serialize = "3.1"
```
# Example
Read about using [metavariables](docs/metavariables.md) inside impl_serialize!
```rust
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(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;
type SerializeSeq = ser::Impossible;
type SerializeStruct = ser::Impossible;
type SerializeStructVariant = ser::Impossible;
type SerializeTuple = ser::Impossible;
type SerializeTupleStruct = ser::Impossible;
type SerializeTupleVariant = ser::Impossible;
//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
]
);
}
```
[`serde::Serializer`]: https://docs.rs/serde/latest/serde/trait.Serializer.html