Skip to content

Commit

Permalink
fix: add default, debug, diplay for lazyvalue
Browse files Browse the repository at this point in the history
  • Loading branch information
liuq19 committed Jan 11, 2024
1 parent 56d2433 commit 9c42a68
Show file tree
Hide file tree
Showing 16 changed files with 137 additions and 51 deletions.
27 changes: 21 additions & 6 deletions examples/lazyvalue.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,30 @@
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use sonic_rs::{LazyValue, OwnedLazyValue};

fn main() {
#[derive(Debug, Deserialize, Serialize, PartialEq)]
let input = r#"{ "borrowed": "hello", "owned": "world" }"#;

// use sonic_rs
#[derive(Debug, Deserialize, Serialize)]
struct TestLazyValue<'a> {
#[serde(borrow)]
borrowed_lv: LazyValue<'a>,
owned_lv: OwnedLazyValue,
borrowed: LazyValue<'a>,
owned: OwnedLazyValue,
}
let input = r#"{ "borrowed_lv": "hello", "owned_lv": "world" }"#;
let data: TestLazyValue = sonic_rs::from_str(input).unwrap();
assert_eq!(data.borrowed_lv.as_raw_str(), "\"hello\"");
assert_eq!(data.owned_lv.as_raw_str(), "\"world\"");
assert_eq!(data.borrowed.as_raw_str(), "\"hello\"");
assert_eq!(data.owned.as_raw_str(), "\"world\"");

// use serde_json
#[derive(Debug, Deserialize, Serialize)]
struct TestRawValue<'a> {
#[serde(borrow)]
borrowed: &'a RawValue,
owned: Box<RawValue>,
}

let data: TestRawValue = serde_json::from_str(input).unwrap();
assert_eq!(data.borrowed.get(), "\"hello\"");
assert_eq!(data.owned.get(), "\"world\"");
}
2 changes: 2 additions & 0 deletions fuzz/fuzz_targets/from_slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ fuzz_target!(|data: &[u8]| {
test_struct!(Enum, data);
test_struct!(String, data);
test_struct!(f64, data);
test_struct!(u64, data);
test_struct!(i64, data);
});

fn compare_lazyvalue(jv: &JValue, sv: &sonic_rs::LazyValue) {
Expand Down
2 changes: 2 additions & 0 deletions src/format.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Formtter for JSON serialization.
// The code is cloned from [serde_json](https://github.com/serde-rs/json) and modified necessary parts.

use std::io::{self, Write};
Expand Down
2 changes: 2 additions & 0 deletions src/lazyvalue/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! A lazy type to representing a unparsed raw JSON text for lazy operators.
mod get;
mod iterator;
mod owned;
Expand Down
105 changes: 68 additions & 37 deletions src/lazyvalue/owned.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
use std::{hash::Hash, str::from_utf8_unchecked, sync::Arc};
use std::{
fmt,
fmt::{Debug, Display},
hash::Hash,
str::from_utf8_unchecked,
sync::Arc,
};

use faststr::FastStr;

Expand All @@ -11,6 +17,8 @@ use crate::{
///
/// It can be converted from [`LazyValue`](crate::lazyvalue::LazyValue). It can be used for serde.
///
/// Default value is a raw JSON text `null`.
///
/// # Examples
///
/// ```
Expand Down Expand Up @@ -58,48 +66,12 @@ use crate::{
/// assert_eq!(data.borrowed_lv.as_raw_str(), "\"hello\"");
/// assert_eq!(data.owned_lv.as_raw_str(), "\"world\"");
/// ```
#[derive(Debug)]
pub struct OwnedLazyValue {
// the raw slice from origin json
pub(crate) raw: FastStr,
unescape: Option<Arc<str>>,
}

impl PartialEq for OwnedLazyValue {
fn eq(&self, other: &Self) -> bool {
self.raw == other.raw
}
}

impl Clone for OwnedLazyValue {
fn clone(&self) -> Self {
Self {
raw: self.raw.clone(),
unescape: self.unescape.clone(),
}
}
}

impl PartialOrd for OwnedLazyValue {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}

impl Ord for OwnedLazyValue {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.raw.cmp(&other.raw)
}
}

impl Eq for OwnedLazyValue {}

impl Hash for OwnedLazyValue {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.raw.hash(state)
}
}

impl JsonValueTrait for OwnedLazyValue {
type ValueType<'v> = OwnedLazyValue;

Expand Down Expand Up @@ -247,3 +219,62 @@ impl<'de> From<LazyValue<'de>> for OwnedLazyValue {
}
}
}

impl Debug for OwnedLazyValue {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter
.debug_tuple("OwnedLazyValue")
.field(&format_args!("{}", &self.as_raw_str()))
.finish()
}
}

impl Display for OwnedLazyValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.as_raw_str())
}
}

impl Default for OwnedLazyValue {
fn default() -> Self {
Self {
raw: FastStr::new("null"),
unescape: None,
}
}
}

impl PartialEq for OwnedLazyValue {
fn eq(&self, other: &Self) -> bool {
self.raw == other.raw
}
}

impl Clone for OwnedLazyValue {
fn clone(&self) -> Self {
Self {
raw: self.raw.clone(),
unescape: self.unescape.clone(),
}
}
}

impl PartialOrd for OwnedLazyValue {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}

impl Ord for OwnedLazyValue {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.raw.cmp(&other.raw)
}
}

impl Eq for OwnedLazyValue {}

impl Hash for OwnedLazyValue {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.raw.hash(state)
}
}
25 changes: 23 additions & 2 deletions src/lazyvalue/value.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
use std::{borrow::Cow, hash::Hash, str::from_utf8_unchecked, sync::Arc};
use std::{
borrow::Cow,
fmt,
fmt::{Debug, Display},
hash::Hash,
str::from_utf8_unchecked,
sync::Arc,
};

use faststr::FastStr;

Expand Down Expand Up @@ -59,7 +66,6 @@ use crate::{
/// let data: TestLazyValue = sonic_rs::from_str(input).unwrap();
/// assert_eq!(data.borrowed_lv.as_raw_str(), "\"hello\"");
/// ```
#[derive(Debug)]
pub struct LazyValue<'a> {
// the raw slice from origin json
pub(crate) raw: JsonSlice<'a>,
Expand All @@ -75,6 +81,21 @@ impl Default for LazyValue<'_> {
}
}

impl<'a> Debug for LazyValue<'a> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter
.debug_tuple("LazyValue")
.field(&format_args!("{}", &self.as_raw_str()))
.finish()
}
}

impl<'a> Display for LazyValue<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.as_raw_str())
}
}

impl PartialEq for LazyValue<'_> {
fn eq(&self, other: &Self) -> bool {
self.raw.as_ref() == other.raw.as_ref()
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
#![doc(test(attr(warn(unused))))]

mod error;
mod index;
mod input;
mod parser;
mod pointer;
mod reader;
mod util;

pub mod format;
pub mod index;
pub mod lazyvalue;
pub mod serde;
pub mod value;
Expand Down
2 changes: 2 additions & 0 deletions src/serde/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Serde between JSON text and Rust data structure.
mod de;
pub(crate) mod number;
pub(crate) mod rawnumber;
Expand Down
1 change: 1 addition & 0 deletions src/util/simd/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod traits;

#[doc(hidden)]
#[macro_export]
macro_rules! impl_lanes {
($simd: ty, $lane: expr) => {
Expand Down
2 changes: 1 addition & 1 deletion src/util/simd/neon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ impl Mask for Mask128 {
#[inline(always)]
fn bitmask(self) -> Self::BitMap {
// TODO: optimize bitmask like this
// neon doesn't have instrution same as movemask, to_bitmask uses shrn to
// neon doesn't have instruction same as movemask, to_bitmask uses shrn to
// reduce 128bits -> 64bits. If a 128bits bool vector in x86 can convert
// as 0101, neon shrn will convert it as 0000111100001111.
// unsafe {
Expand Down
1 change: 1 addition & 0 deletions src/value/array.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Represents a parsed JSON array. Its APIs are likes `Vec<Value>`.
use std::{
fmt::Debug,
iter::FusedIterator,
Expand Down
7 changes: 6 additions & 1 deletion src/value/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
//! A dynamic type to representing any valid JSON value.
mod allocator;
pub mod array;
pub(crate) mod de;
mod from;
pub(crate) mod node;
#[doc(hidden)]
pub mod shared;
mod tryfrom;
#[macro_use]
Expand All @@ -23,7 +26,9 @@ pub use self::node::{Value, ValueRef};
#[doc(inline)]
pub use self::object::Object;
#[doc(inline)]
pub use self::ser::{to_value, to_value_in};
pub use self::ser::to_value;
#[doc(hidden)]
pub use self::ser::to_value_in;
#[doc(inline)]
pub use self::value_trait::{JsonContainerTrait, JsonType, JsonValueMutTrait, JsonValueTrait};

Expand Down
1 change: 1 addition & 0 deletions src/value/object.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Represents a parsed JSON object.
use std::marker::PhantomData;

use super::{
Expand Down
2 changes: 1 addition & 1 deletion src/value/tls_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ thread_local! {
static NODE_BUF: std::cell::RefCell<Vec<ManuallyDrop<Value>>> = std::cell::RefCell::new(Vec::new());
}

/// A thread-local buffer for temporary nodes. Avoid allocating temporay memory multiple times.
/// A thread-local buffer for temporary nodes. Avoid allocating temporary memory multiple times.
pub struct TlsBuf {
buf: NonNull<Vec<ManuallyDrop<Value>>>,
need_drop: bool,
Expand Down
1 change: 1 addition & 0 deletions src/value/value_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ impl From<u8> for JsonType {
}

/// A trait for all JSON values. Used by `Value` and `LazyValue`.
///
/// The `Option<V: JsonValueTrait>` and `Result<V: JsonValueTrait, E>` also implement this trait.
/// The `Option::None` or `Result::Err(_)` will be viewed as a null value.
pub trait JsonValueTrait {
Expand Down
6 changes: 4 additions & 2 deletions src/writer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use std::{io, io::BufWriter, mem::MaybeUninit, slice::from_raw_parts_mut};
//! Extend trait from io::Write for JSON serializing.
use std::{io, io::BufWriter as IoBufWriter, mem::MaybeUninit, slice::from_raw_parts_mut};

use bytes::{buf::Writer, BytesMut};

Expand Down Expand Up @@ -56,7 +58,7 @@ impl WriteExt for Writer<BytesMut> {
}
}

impl<W: WriteExt> WriteExt for BufWriter<W> {
impl<W: WriteExt + ?Sized> WriteExt for IoBufWriter<W> {
fn reserve_with(&mut self, additional: usize) -> io::Result<&mut [MaybeUninit<u8>]> {
self.get_mut().reserve_with(additional)
}
Expand Down

0 comments on commit 9c42a68

Please sign in to comment.