diff --git a/gstreamer/Cargo.toml b/gstreamer/Cargo.toml index 64d142189..4e41906d9 100644 --- a/gstreamer/Cargo.toml +++ b/gstreamer/Cargo.toml @@ -28,6 +28,7 @@ serde = { version = "1.0", optional = true } serde_bytes = { version = "0.11", optional = true } serde_derive = { version = "1.0", optional = true } paste = { version = "0.1" } +pretty-hex = "0.1" [build-dependencies] rustdoc-stripper = { version = "0.1", optional = true } diff --git a/gstreamer/src/lib.rs b/gstreamer/src/lib.rs index 35db7fe0e..6028cbe8a 100644 --- a/gstreamer/src/lib.rs +++ b/gstreamer/src/lib.rs @@ -36,6 +36,8 @@ extern crate futures_core; extern crate muldiv; +extern crate pretty_hex; + #[cfg(feature = "ser_de")] extern crate serde; #[cfg(feature = "ser_de")] diff --git a/gstreamer/src/memory.rs b/gstreamer/src/memory.rs index 1f6809d5d..3ef920f12 100644 --- a/gstreamer/src/memory.rs +++ b/gstreamer/src/memory.rs @@ -308,6 +308,10 @@ impl MemoryRef { assert!(offset + (size as isize) < (self.get_maxsize() as isize)); unsafe { gst_sys::gst_memory_resize(self.as_mut_ptr(), offset, size) } } + + pub fn dump(&self, size: Option) -> Dump { + Dump { memory: self, size } + } } impl<'a, T> MemoryMap<'a, T> { @@ -466,3 +470,54 @@ impl Eq for MappedMemory {} unsafe impl Send for MappedMemory {} unsafe impl Sync for MappedMemory {} + +pub struct Dump<'a> { + memory: &'a MemoryRef, + size: Option, +} + +impl<'a> Dump<'a> { + fn fmt(&self, f: &mut fmt::Formatter, debug: bool) -> fmt::Result { + use pretty_hex::*; + + let map = self.memory.map_readable().expect("Failed to map memory"); + let data = map.as_slice(); + let size = self.size.unwrap_or_else(|| self.memory.get_size()); + let data = &data[0..size]; + + if debug { + write!(f, "{:?}", data.hex_dump()) + } else { + write!(f, "{}", data.hex_dump()) + } + } +} + +impl<'a> fmt::Display for Dump<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.fmt(f, false) + } +} + +impl<'a> fmt::Debug for Dump<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.fmt(f, true) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_dump() { + ::init().unwrap(); + + let mem = ::Memory::from_slice(vec![1, 2, 3, 4]); + println!("{}", mem.dump(Some(mem.get_size()))); + + let mem = ::Memory::from_slice(vec![1, 2, 3, 4]); + println!("{:?}", mem.dump(Some(2))); + + let mem = ::Memory::from_slice(vec![0; 64]); + dbg!(mem.dump(None)); + } +}