1 //! Support for serializing fields as `serde` structs or maps. 2 use super::*; 3 4 #[derive(Debug)] 5 pub struct SerializeFieldMap<'a, T>(&'a T); 6 7 pub trait AsMap: Sized + sealed::Sealed { field_map(&self) -> SerializeFieldMap<'_, Self>8 fn field_map(&self) -> SerializeFieldMap<'_, Self> { 9 SerializeFieldMap(self) 10 } 11 } 12 13 impl<'a> AsMap for Event<'a> {} 14 impl<'a> AsMap for Attributes<'a> {} 15 impl<'a> AsMap for Record<'a> {} 16 17 // === impl SerializeFieldMap === 18 19 impl<'a> Serialize for SerializeFieldMap<'a, Event<'_>> { serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer,20 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 21 where 22 S: Serializer, 23 { 24 let len = self.0.fields().count(); 25 let serializer = serializer.serialize_map(Some(len))?; 26 let mut visitor = SerdeMapVisitor::new(serializer); 27 self.0.record(&mut visitor); 28 visitor.finish() 29 } 30 } 31 32 impl<'a> Serialize for SerializeFieldMap<'a, Attributes<'_>> { serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer,33 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 34 where 35 S: Serializer, 36 { 37 let len = self.0.metadata().fields().len(); 38 let serializer = serializer.serialize_map(Some(len))?; 39 let mut visitor = SerdeMapVisitor::new(serializer); 40 self.0.record(&mut visitor); 41 visitor.finish() 42 } 43 } 44 45 impl<'a> Serialize for SerializeFieldMap<'a, Record<'_>> { serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer,46 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 47 where 48 S: Serializer, 49 { 50 let serializer = serializer.serialize_map(None)?; 51 let mut visitor = SerdeMapVisitor::new(serializer); 52 self.0.record(&mut visitor); 53 visitor.finish() 54 } 55 } 56