cloudwego / sonic-rs

A fast Rust JSON library based on SIMD.
https://crates.io/crates/sonic-rs
Apache License 2.0
487 stars 31 forks source link

Suggestion to unify `as_*()` methods under one `as_scalar()` #82

Closed aldanor closed 4 months ago

aldanor commented 6 months ago

Suggestion:

// impl for bool, &str, i64, u64, Number
trait Scalar<V>: Sealed + Sized {
    fn from_json_value(value: &V) -> Option<Self>;
}

trait JsonValueTrait {
    fn as_scalar<T: Scalar<Self::ValueType>>(&self) -> Option<T> {
        T::from_json_value(self)
    }

    fn get_scalar<T: Scalar<Self::ValueType>, I: Index>(&self, index: I) -> Option<T>;

    fn pointer_scalar<T: Scalar<Self::ValueType>, P: ..>(&self, path: P) -> Option<T>;
}

This would make it easier to build more generic wrappers around this API without too much copy/paste for each particular type.


Note 1: would be nice to have it just as Scalar without it being generic, but it seems that Scalar<Self::ValueType> is inevitable? (because JsonValueTrait may return non-self in get() and pointer()?)


Note 2: for consistency, it might make sense to also have

    fn as_object(&self) -> Option<LazyObject>;
    fn as_array(&self) -> Option<LazyObject>;
liuq19 commented 6 months ago

we use as_xx API for two reasons:

  1. consistent with serde_json as possible
  2. the bool, &str, i64, u64, Number are mostly used, the concise names are more readable