From 4b8573a993ddab64ee1cf72da4353ec79783cf0e Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Tue, 21 Jan 2020 23:33:51 +0100 Subject: [PATCH] Implement fmt::Display for StringView (#236) Make StringView objects inspectable to make it easier to debug the V8 inspector's wire protocol. StringBuffer objects can't be inspected yet because they need a mutable reference if they want to call `StringBuffer::string()`, which makes sense because that method calls out to a C++ virtual method that can modify the object. For now, instances can be inspected like this: let mut sb = StringBuffer::create(...); println!("StringBuffer({})", sb.string().unwrap()); Closes #233 --- src/inspector/string_view.rs | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/inspector/string_view.rs b/src/inspector/string_view.rs index 9ce590c8..529aaafb 100644 --- a/src/inspector/string_view.rs +++ b/src/inspector/string_view.rs @@ -1,3 +1,4 @@ +use std::fmt; use std::iter::ExactSizeIterator; use std::iter::IntoIterator; use std::marker::PhantomData; @@ -5,6 +6,7 @@ use std::ops::Deref; use std::ptr::null; use std::ptr::NonNull; use std::slice; +use std::string; // class StringView { // public: @@ -38,7 +40,6 @@ use std::slice; // TODO: find/open upstream issue to allow #[repr(bool)] support. #[repr(u8)] -#[derive(Debug)] pub enum StringView<'a> { // Do not reorder! U16(CharacterArray<'a, u16>), @@ -51,6 +52,15 @@ impl StringView<'static> { } } +impl fmt::Display for StringView<'_> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::U16(v) => v.fmt(f), + Self::U8(v) => v.fmt(f), + } + } +} + impl<'a> From<&'a [u8]> for StringView<'a> { fn from(v: &'a [u8]) -> Self { Self::U8(CharacterArray::<'a, u8>::from(v)) @@ -146,6 +156,18 @@ where unsafe impl<'a, T> Send for CharacterArray<'a, T> where T: Copy {} unsafe impl<'a, T> Sync for CharacterArray<'a, T> where T: Sync {} +impl fmt::Display for CharacterArray<'_, u8> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(&string::String::from_utf8_lossy(&*self)) + } +} + +impl fmt::Display for CharacterArray<'_, u16> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(&string::String::from_utf16_lossy(&*self)) + } +} + impl<'a, T> From<&'a [T]> for CharacterArray<'a, T> { fn from(v: &'a [T]) -> Self { Self { @@ -173,7 +195,7 @@ impl<'a, T> Deref for CharacterArray<'a, T> { } } -#[derive(Copy, Clone, Debug)] +#[derive(Copy, Clone)] pub struct StringViewIterator<'a: 'b, 'b> { view: &'a StringView<'b>, pos: usize, @@ -197,3 +219,10 @@ impl<'a: 'b, 'b> ExactSizeIterator for StringViewIterator<'a, 'b> { self.view.len() } } + +#[test] +fn string_view_display() { + let ok: [u16; 2] = [111, 107]; + assert_eq!("ok", format!("{}", StringView::from(&ok[..]))); + assert_eq!("ok", format!("{}", StringView::from(&b"ok"[..]))); +}