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
//! `bitflags` crate Serde shims
//!
//! To enable to `bitflags` shims, add it to the crate features list:
//!
//! ```toml
//! [dependencies]
//! bitflags_serde_shim = "0.2"
//! ```
//!
//! Full example:
//!
//! ```
//! #[macro_use]
//! extern crate serde_derive;
//! extern crate serde_json;
//!
//! #[macro_use]
//! extern crate bitflags;
//! #[macro_use] // required for impl_serde_for_bitflags
//! extern crate bitflags_serde_shim;
//!
//! bitflags! {
//! // Note that `impl_serde_for_bitflags` requires the flag type to
//! // implement `Serialize` and `Deserialize`.
//! //
//! // All primitive integer types satisfy this requirement.
//! pub struct Permission: u32 {
//! const SEND_MESSAGE = 0x00000001;
//! const EDIT_MESSAGE = 0x00000002;
//! const KICK_MEMBER = 0x00000004;
//! const BAN_MEMBER = 0x00000008;
//! }
//! }
//!
//! impl_serde_for_bitflags!(Permission);
//!
//! fn main() {
//! let test = Permission::SEND_MESSAGE | Permission::EDIT_MESSAGE;
//!
//! assert_eq!(serde_json::to_string(&test).unwrap(), "3");
//!
//! assert_eq!(serde_json::from_str::<Permission>("3").unwrap(), test);
//!
//! assert!(serde_json::from_str::<Permission>("51").is_err());
//! }
//! ```
#[doc(hidden)]
pub extern crate serde;
/// Implements `Serialize` and `Deserialize` for a `bitflags!` generated structure.
///
/// Note that `impl_serde_for_bitflags` requires the flag type to
/// implement `Serialize` and `Deserialize`.
///
/// All primitive integer types satisfy these requirements.
///
/// See the [`bitflags`](../bitflags_serde_shim/index.html) shim for a full example.
#[macro_export]
macro_rules! impl_serde_for_bitflags {
($name:ident) => {
impl $crate::serde::Serialize for $name {
fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: $crate::serde::Serializer,
{
self.bits().serialize(serializer)
}
}
impl<'de> $crate::serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> ::std::result::Result<$name, D::Error>
where
D: $crate::serde::Deserializer<'de>,
{
let value = <_ as $crate::serde::Deserialize<'de>>::deserialize(deserializer)?;
$name::from_bits(value)
.ok_or_else(|| $crate::serde::de::Error::custom(format!("Invalid bits {:#X} for {}", value, stringify!($name))))
}
}
};
}