0
0
Fork 0
mirror of https://github.com/denoland/rusty_v8.git synced 2024-12-24 00:00:06 -05:00

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
This commit is contained in:
Ben Noordhuis 2020-01-21 23:33:51 +01:00 committed by Ry Dahl
parent 1a1bac3883
commit 4b8573a993

View file

@ -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"[..])));
}