Macro for fast implementing serialize methods in serde::Serializer trait

Overview

impl_serialize!

This library provides a simple procedural macro for fast implementing serialize methods in serde::Serializer trait.

[dependencies]
impl_serialize = "3.1"

Example

Read about using metavariables inside 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
        ]
    );
}
You might also like...
A procedural macro for configuring constant values across crates

toml-cfg Rough ideas: Crates can declare variables that can be overridden Anything const, e.g. usize, strings, etc. (Only) The "root crate" can overri

A Rust attribute macro that adds memoization to a function (rhymes with Mickey)

michie (sounds like Mickey) — an attribute macro that adds memoization to a function. Table of contents Features Non-features key_expr key_type store_

Proc macro implementation of #[naked]

#[naked] Documentation This crate provide a proc macro version of the #[naked] attribute which can be used on stable Rust. Example // The SYSV64 calli

hashmap macro for creating hashmap from provided key/value pairs

HashMap Macro Creates a HashMap from provided key/value pairs. Usage use std::collections::HashMap; use hashmap_macro::hashmap; let m: HashMap&str,

Library and proc macro to analyze memory usage of data structures in rust.
Library and proc macro to analyze memory usage of data structures in rust.

Allocative: memory profiler for Rust This crate implements a lightweight memory profiler which allows object traversal and memory size introspection.

Simple Rust derive-macro that simplifies integral enum creation

Integral enum A simple way to define integer-like enums. This macro implements bunch of traits that are usually implemented via looooong derive(..) at

proc-macro to help with using surrealdb's custom functions

SurrealDB Functions This is a proc-macro crate that given a path to a .surql file or a folder of .surql files, will parse DEFINE FUNCTION fn::s inside

todo2(a.k.a. todo or die) - A better todo! macro inspired from searls/todo_or_die

todo2 todo2(a.k.a. todo or die) - A better todo! macro inspired from searls/todo_or_die This crate provides a better todo! macro, which allows you to

A procedural macro to generate a new function implementation for your struct.

Impl New 🦀 A procedural macro to generate a new function implementation for your struct. 🚀 Add to your project Add this to your Cargo.toml: [depende

Comments
  • Add value capturing from specific functions

    Add value capturing from specific functions

    Add value capturing from specific functions

    impl_serialize!(|value_type: &str, len: Option<usize>| Ok(()), [map, seq]);
    impl_serialize!(|value_type: &str, name: &'static str| Ok(()), [unit_struct, unit_variant]);
    
    enhancement good first issue 
    opened by Trard 5
  • 2.0 Evolution to impl_serialize!

    2.0 Evolution to impl_serialize!

    from impl_serde_serialize_error to impl_serialize.

    Changelog

    • Now the macro can implement more than just error.

    • Now macro requires closure.

    • Argument of this closure is value type

    opened by Trard 0
Releases(v3.1.4)
Serialize & deserialize device tree binary using serde

serde_device_tree Use serde framework to deserialize Device Tree Blob binary files; no_std compatible. Use this library Run example: cargo run --examp

Luo Jia 20 Aug 20, 2022
A tool to deserialize data from an input encoding, transform it and serialize it back into an output encoding.

dts A simple tool to deserialize data from an input encoding, transform it and serialize it back into an output encoding. Requires rust >= 1.56.0. Ins

null 11 Dec 14, 2022
Goodname is a tool to assist you with cool naming of your methods and software

Goodname is a tool to assist you with cool naming of your methods and software. Given a brief description of your method or software, this tool enumerates name candidates forming subsequences of the description (i.e., abbreviation).

Shunsuke Kanda 118 Dec 28, 2022
A Rust trait to convert numbers of any type and size to their English representation.

num2english This Rust crate provides the NumberToEnglish trait which can be used to convert any* number to its string representation in English. It us

Travis A. Wagner 6 Mar 8, 2023
Serde support for n-dimensional arrays from self-describing formats

serde-ndim Overview This crate provides a way to serialize and deserialize arrays of arbitrary dimensionality from self-described formats such as JSON

Ingvar Stepanyan 5 Apr 3, 2023
A benchmark of Rust/serde deserializers on configuration files

This program compares the time some serde deserializers take to deserialize some string into a configuration-like struct deriving Deserialize. The ben

Denys Séguret 4 Oct 30, 2023
An attempt at implementing a state-of-the-art Voxel DAG in Rust

VDAG Introduction This is an attempt at implementing a state-of-the-art compressed voxel data structure, as described in a number of papers ([PDFs] Ka

SamCasavant 2 Aug 25, 2022
Rust crate implementing short & stable ids based on timestamps

Lexicoid Short & stable IDs based on timestamps. Heavily inspired by Short, friendly base32 slugs from timestamps by @brandur. Install Install with ca

Luciano Mammino 6 Jan 29, 2023
A Rust macro for writing nested loop expressions

loop_chain A Rust macro for writing nested loop expressions Usage | Examples | Docs Dependencies [dependencies] loop_chain = "0.1.1" Usage For express

Takayuki Maeda 5 Jul 30, 2021
Macro assembler for Rust

Macro Assembler This crate implement JSC/SpiderMonkey like macro assembler. Macro assembler purpose is to generate machine code for different platform

playX 6 Nov 26, 2022