|
| 1 | +extern crate serde; |
| 2 | + |
| 3 | +use bitflags::{ |
| 4 | + parser::{self, ParseHex, WriteHex}, |
| 5 | + Flags, |
| 6 | +}; |
| 7 | + |
| 8 | +use core::{fmt, str}; |
| 9 | + |
| 10 | +pub use serde::{ |
| 11 | + de::{Error, Visitor}, |
| 12 | + Deserialize, Deserializer, Serialize, Serializer, |
| 13 | +}; |
| 14 | + |
| 15 | +struct AsDisplay<'a, B>(pub(crate) &'a B); |
| 16 | + |
| 17 | +impl<'a, B: Flags> fmt::Display for AsDisplay<'a, B> |
| 18 | +where |
| 19 | + B::Bits: WriteHex, |
| 20 | +{ |
| 21 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 22 | + parser::to_writer(self.0, f) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | +Serialize a set of flags as a human-readable string or their underlying bits. |
| 28 | +
|
| 29 | +Any unknown bits will be retained. |
| 30 | +*/ |
| 31 | +pub fn serialize<B: Flags, S: Serializer>(flags: &B, serializer: S) -> Result<S::Ok, S::Error> |
| 32 | +where |
| 33 | + B::Bits: WriteHex + Serialize, |
| 34 | +{ |
| 35 | + // Serialize human-readable flags as a string like `"A | B"` |
| 36 | + if serializer.is_human_readable() { |
| 37 | + serializer.collect_str(&AsDisplay(flags)) |
| 38 | + } |
| 39 | + // Serialize non-human-readable flags directly as the underlying bits |
| 40 | + else { |
| 41 | + flags.bits().serialize(serializer) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | +Deserialize a set of flags from a human-readable string or their underlying bits. |
| 47 | +
|
| 48 | +Any unknown bits will be retained. |
| 49 | +*/ |
| 50 | +pub fn deserialize<'de, B: Flags, D: Deserializer<'de>>(deserializer: D) -> Result<B, D::Error> |
| 51 | +where |
| 52 | + B::Bits: ParseHex + Deserialize<'de>, |
| 53 | +{ |
| 54 | + if deserializer.is_human_readable() { |
| 55 | + // Deserialize human-readable flags by parsing them from strings like `"A | B"` |
| 56 | + struct FlagsVisitor<B>(core::marker::PhantomData<B>); |
| 57 | + |
| 58 | + impl<'de, B: Flags> Visitor<'de> for FlagsVisitor<B> |
| 59 | + where |
| 60 | + B::Bits: ParseHex, |
| 61 | + { |
| 62 | + type Value = B; |
| 63 | + |
| 64 | + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 65 | + formatter.write_str("a string value of `|` separated flags") |
| 66 | + } |
| 67 | + |
| 68 | + fn visit_str<E: Error>(self, flags: &str) -> Result<Self::Value, E> { |
| 69 | + parser::from_str(flags).map_err(|e| E::custom(e)) |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + deserializer.deserialize_str(FlagsVisitor(Default::default())) |
| 74 | + } else { |
| 75 | + // Deserialize non-human-readable flags directly from the underlying bits |
| 76 | + let bits = B::Bits::deserialize(deserializer)?; |
| 77 | + |
| 78 | + Ok(B::from_bits_retain(bits)) |
| 79 | + } |
| 80 | +} |
0 commit comments