Skip to content

Commit

Permalink
add some more methods to JsonStr
Browse files Browse the repository at this point in the history
  • Loading branch information
KodrAus committed Mar 28, 2024
1 parent 0e84b9a commit ec2d7f7
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
34 changes: 33 additions & 1 deletion json/src/value.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use core::fmt;
use core::{borrow::Borrow, fmt};

/**
A string containing encoded JSON.
Expand All @@ -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 {
Expand Down Expand Up @@ -53,6 +66,18 @@ impl sval::Value for JsonStr {
}
}

impl AsRef<str> for JsonStr {
fn as_ref(&self) -> &str {
&self.0
}
}

impl Borrow<str> for JsonStr {
fn borrow(&self) -> &str {
&self.0
}
}

#[cfg(feature = "alloc")]
mod alloc_support {
use super::*;
Expand All @@ -70,4 +95,11 @@ mod alloc_support {
unsafe { Box::from_raw(Box::into_raw(json) as *mut str as *mut JsonStr) }
}
}

impl From<Box<str>> for Box<JsonStr> {
fn from(value: Box<str>) -> Self {
// SAFETY: `JsonStr` and `str` have the same ABI
unsafe { Box::from_raw(Box::into_raw(value) as *mut JsonStr) }
}
}
}
14 changes: 14 additions & 0 deletions json/test/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit ec2d7f7

Please sign in to comment.