From ec2d7f7f0766b469e516eba28f7d18e43fb8810e Mon Sep 17 00:00:00 2001 From: KodrAus Date: Thu, 28 Mar 2024 19:52:39 +1000 Subject: [PATCH] add some more methods to JsonStr --- json/src/value.rs | 34 +++++++++++++++++++++++++++++++++- json/test/lib.rs | 14 ++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/json/src/value.rs b/json/src/value.rs index bcd9cba4..ac636407 100644 --- a/json/src/value.rs +++ b/json/src/value.rs @@ -1,4 +1,4 @@ -use core::fmt; +use core::{borrow::Borrow, fmt}; /** A string containing encoded JSON. @@ -25,6 +25,19 @@ impl JsonStr { pub const fn as_str(&self) -> &str { &self.0 } + + /** + Get a reference to the bytes of the underlying string. + */ + pub const fn as_bytes(&self) -> &[u8] { + self.0.as_bytes() + } +} + +impl<'a> From<&'a str> for &'a JsonStr { + fn from(value: &'a str) -> Self { + JsonStr::new(value) + } } impl fmt::Debug for JsonStr { @@ -53,6 +66,18 @@ impl sval::Value for JsonStr { } } +impl AsRef for JsonStr { + fn as_ref(&self) -> &str { + &self.0 + } +} + +impl Borrow for JsonStr { + fn borrow(&self) -> &str { + &self.0 + } +} + #[cfg(feature = "alloc")] mod alloc_support { use super::*; @@ -70,4 +95,11 @@ mod alloc_support { unsafe { Box::from_raw(Box::into_raw(json) as *mut str as *mut JsonStr) } } } + + impl From> for Box { + fn from(value: Box) -> Self { + // SAFETY: `JsonStr` and `str` have the same ABI + unsafe { Box::from_raw(Box::into_raw(value) as *mut JsonStr) } + } + } } diff --git a/json/test/lib.rs b/json/test/lib.rs index 32ab17ca..cb465dfb 100644 --- a/json/test/lib.rs +++ b/json/test/lib.rs @@ -199,6 +199,20 @@ fn stream_unit_struct() { assert_stream("\"UnitStruct\"", UnitStruct); } +#[test] +fn stream_json_str() { + let json = "{\"a\":[1,true,4.3]}"; + + assert_eq!( + json, + sval_json::stream_to_string(sval_json::JsonStr::new(json)).unwrap() + ); + assert_eq!( + json, + sval_json::stream_to_string(sval_json::JsonStr::boxed(json)).unwrap() + ); +} + #[test] fn stream_map_struct() { assert_json(MapStruct {