From 905ab9d2493528e0a06c395e234910408acbed8a Mon Sep 17 00:00:00 2001 From: Ygg01 Date: Wed, 2 Sep 2026 21:30:44 +0200 Subject: [PATCH 1/2] WIP --- Cargo.toml | 2 ++ src/cow.rs | 2 +- src/error.rs | 24 ++++++++------- src/impls/avx2/stage1.rs | 8 +++-- src/impls/sse42/deser.rs | 8 ++--- src/impls/sse42/stage1.rs | 4 ++- src/lib.rs | 55 ++++++++++++++++++++--------------- src/macros.rs | 1 + src/serde/se.rs | 9 ++++-- src/serde/se/pp.rs | 16 ++++++---- src/value.rs | 5 ++-- src/value/borrowed.rs | 16 ++++++---- src/value/lazy/array.rs | 6 ++-- src/value/lazy/from.rs | 8 +++-- src/value/lazy/trait_impls.rs | 5 ++-- src/value/tape.rs | 4 ++- 16 files changed, 105 insertions(+), 68 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 793417ce..7a515c39 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,8 @@ rust-version = "1.88" [dependencies] simdutf8 = { version = "0.1.4", features = ["public_imp", "aarch64_neon"] } +core_detect = "1.0.0" +hashbrown = "0.17.1" value-trait = { version = "0.12" } beef = { version = "0.5", optional = true } diff --git a/src/cow.rs b/src/cow.rs index 712711e1..f9b3e2e3 100644 --- a/src/cow.rs +++ b/src/cow.rs @@ -5,7 +5,7 @@ //! //! [beef]: https://docs.rs/beef/latest/beef/lean/type.Cow.html #[cfg(not(feature = "beef"))] -pub use std::borrow::Cow; +pub use alloc::borrow::Cow; #[cfg(feature = "beef")] pub use beef::lean::Cow; diff --git a/src/error.rs b/src/error.rs index 3403b119..b59fe79e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,4 +1,5 @@ -use std::fmt; +use alloc::string::String; +use core::fmt; use value_trait::ValueType; @@ -91,7 +92,7 @@ pub enum ErrorType { /// No SIMD support detected during runtime SimdUnsupported, /// IO error - Io(std::io::Error), + Io(core::fmt::Error), } #[derive(Clone, Debug, PartialEq)] @@ -99,8 +100,8 @@ pub enum InternalError { TapeError, } -impl From for Error { - fn from(e: std::io::Error) -> Self { +impl From for Error { + fn from(e: core::fmt::Error) -> Self { Self::generic(ErrorType::Io(e)) } } @@ -273,7 +274,7 @@ impl Error { ) } } -impl std::error::Error for Error {} +impl core::error::Error for Error {} #[cfg(not(tarpaulin_include))] impl fmt::Display for Error { @@ -286,9 +287,10 @@ impl fmt::Display for Error { } } -#[cfg(not(tarpaulin_include))] -impl From for std::io::Error { - fn from(e: Error) -> Self { - std::io::Error::new(std::io::ErrorKind::InvalidData, e) - } -} +// TODO +// #[cfg(not(tarpaulin_include))] +// impl From for std::io::Error { +// fn from(e: Error) -> Self { +// std::io::Error::new(std::io::ErrorKind::InvalidData, e) +// } +// } diff --git a/src/impls/avx2/stage1.rs b/src/impls/avx2/stage1.rs index 3bc016d7..a532b369 100644 --- a/src/impls/avx2/stage1.rs +++ b/src/impls/avx2/stage1.rs @@ -1,13 +1,15 @@ #![allow(dead_code)] + +use alloc::vec::Vec; use crate::{ Stage1Parse, macros::{static_cast_i32, static_cast_i64, static_cast_u32}, }; #[cfg(target_arch = "x86")] -use std::arch::x86 as arch; +use core::arch::x86 as arch; #[cfg(target_arch = "x86_64")] -use std::arch::x86_64 as arch; +use core::arch::x86_64 as arch; use arch::{ __m256i, _mm_clmulepi64_si128, _mm_set_epi64x, _mm_set1_epi8, _mm256_add_epi32, @@ -62,7 +64,7 @@ impl Stage1Parse for SimdInput { #[cfg(target_arch = "x86_64")] unsafe fn compute_quote_mask(quote_bits: u64) -> u64 { unsafe { - std::arch::x86_64::_mm_cvtsi128_si64(_mm_clmulepi64_si128( + core::arch::x86_64::_mm_cvtsi128_si64(_mm_clmulepi64_si128( _mm_set_epi64x(0, static_cast_i64!(quote_bits)), _mm_set1_epi8(-1_i8 /* 0xFF */), 0, diff --git a/src/impls/sse42/deser.rs b/src/impls/sse42/deser.rs index c169c5a2..13214deb 100644 --- a/src/impls/sse42/deser.rs +++ b/src/impls/sse42/deser.rs @@ -1,8 +1,8 @@ #[cfg(target_arch = "x86")] -use std::arch::x86 as arch; +use core::arch::x86 as arch; #[cfg(target_arch = "x86_64")] -use std::arch::x86_64 as arch; +use core::arch::x86_64 as arch; use crate::{ Deserializer, Result, SillyWrapper, @@ -64,7 +64,7 @@ pub(crate) unsafe fn parse_str<'invoke, 'de>( len += quote_dist as usize; let v = - std::str::from_utf8_unchecked(std::slice::from_raw_parts(input.add(idx), len)); + core::str::from_utf8_unchecked(core::slice::from_raw_parts(input.add(idx), len)); return Ok(v); // we compare the pointers since we care if they are 'at the same spot' @@ -121,7 +121,7 @@ pub(crate) unsafe fn parse_str<'invoke, 'de>( input .add(idx + len) .copy_from_nonoverlapping(buffer.as_ptr(), dst_i); - let v = std::str::from_utf8_unchecked(std::slice::from_raw_parts( + let v = core::str::from_utf8_unchecked(core::slice::from_raw_parts( input.add(idx), len + dst_i, )); diff --git a/src/impls/sse42/stage1.rs b/src/impls/sse42/stage1.rs index 698404f7..c50f3357 100644 --- a/src/impls/sse42/stage1.rs +++ b/src/impls/sse42/stage1.rs @@ -1,3 +1,5 @@ +use alloc::vec::Vec; + use crate::{ Stage1Parse, macros::{static_cast_i32, static_cast_i64, static_cast_u32}, @@ -6,7 +8,7 @@ use crate::{ use std::arch::x86 as arch; #[cfg(target_arch = "x86_64")] -use std::arch::x86_64 as arch; +use core::arch::x86_64 as arch; #[cfg(target_arch = "x86")] use arch::{ diff --git a/src/lib.rs b/src/lib.rs index 1ddf3874..78aded9c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +#![no_std] + #![deny(warnings)] #![cfg_attr(feature = "hints", feature(core_intrinsics))] #![cfg_attr(feature = "portable", feature(portable_simd))] @@ -18,6 +20,8 @@ #[cfg(feature = "serde_impl")] extern crate serde as serde_ext; +extern crate alloc; + #[cfg(feature = "serde_impl")] /// serde related helper functions pub mod serde; @@ -68,7 +72,9 @@ mod stage2; /// simd-json JSON-DOM value pub mod value; -use std::{alloc::dealloc, mem}; +use alloc::{alloc::dealloc}; +use alloc::alloc::{alloc, handle_alloc_error}; +use core::mem; pub use value_trait::StaticNode; pub use crate::error::{Error, ErrorType}; @@ -77,7 +83,7 @@ pub use crate::value::*; pub use value_trait::ValueType; /// simd-json Result type -pub type Result = std::result::Result; +pub type Result = core::result::Result; #[cfg(feature = "known-key")] mod known_key; @@ -85,10 +91,11 @@ mod known_key; pub use known_key::{Error as KnownKeyError, KnownKey}; pub use crate::tape::{Node, Tape}; -use std::alloc::{Layout, alloc, handle_alloc_error}; -use std::ops::{Deref, DerefMut}; -use std::ptr::NonNull; +use core::ops::{Deref, DerefMut}; +use core::ptr::NonNull; +use alloc::vec::Vec; +use core::alloc::Layout; use simdutf8::basic::imp::ChunkedUtf8Validator; /// A struct to hold the buffers for the parser. @@ -332,7 +339,7 @@ pub struct Deserializer<'de> { #[derive(Debug, Clone, Copy)] pub(crate) struct SillyWrapper<'de> { input: *mut u8, - _marker: std::marker::PhantomData<&'de ()>, + _marker: core::marker::PhantomData<&'de ()>, } impl From<*mut u8> for SillyWrapper<'_> { @@ -340,7 +347,7 @@ impl From<*mut u8> for SillyWrapper<'_> { fn from(input: *mut u8) -> Self { Self { input, - _marker: std::marker::PhantomData, + _marker: core::marker::PhantomData, } } } @@ -359,7 +366,7 @@ type ParseStrFn = for<'invoke, 'de> unsafe fn( &'invoke [u8], &'invoke mut [u8], usize, -) -> std::result::Result<&'de str, error::Error>; +) -> core::result::Result<&'de str, error::Error>; #[cfg(all( feature = "runtime-detection", any(target_arch = "x86_64", target_arch = "x86"), @@ -367,7 +374,7 @@ type ParseStrFn = for<'invoke, 'de> unsafe fn( type FindStructuralBitsFn = unsafe fn( input: &[u8], structural_indexes: &mut Vec, -) -> std::result::Result<(), ErrorType>; +) -> core::result::Result<(), ErrorType>; #[derive(Clone, Copy, Debug, PartialEq, Eq)] /// Supported implementations @@ -386,8 +393,8 @@ pub enum Implementation { SIMD128, } -impl std::fmt::Display for Implementation { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for Implementation { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Implementation::Native => write!(f, "Rust Native"), Implementation::StdSimd => write!(f, "std::simd"), @@ -407,9 +414,9 @@ impl Deserializer<'_> { ))] #[must_use] pub fn algorithm() -> Implementation { - if std::is_x86_feature_detected!("avx2") { + if core_detect::is_x86_feature_detected!("avx2") { Implementation::AVX2 - } else if std::is_x86_feature_detected!("sse4.2") { + } else if core_detect::is_x86_feature_detected!("sse4.2") { Implementation::SSE42 } else { #[cfg(feature = "portable")] @@ -490,9 +497,9 @@ impl<'de> Deserializer<'de> { any(target_arch = "x86_64", target_arch = "x86"), ))] pub(crate) fn parse_str_fn() -> ParseStrFn { - if std::is_x86_feature_detected!("avx2") { + if core_detect::is_x86_feature_detected!("avx2") { impls::avx2::parse_str - } else if std::is_x86_feature_detected!("sse4.2") { + } else if core_detect::is_x86_feature_detected!("sse4.2") { impls::sse42::parse_str } else { #[cfg(feature = "portable")] @@ -632,7 +639,7 @@ impl Deserializer<'_> { pub(crate) unsafe fn find_structural_bits_native( input: &[u8], structural_indexes: &mut Vec, - ) -> std::result::Result<(), ErrorType> { + ) -> core::result::Result<(), ErrorType> { match core::str::from_utf8(input) { Ok(_) => (), Err(_) => return Err(ErrorType::InvalidUtf8), @@ -650,9 +657,9 @@ impl Deserializer<'_> { pub(crate) unsafe fn find_structural_bits( input: &[u8], structural_indexes: &mut Vec, - ) -> std::result::Result<(), ErrorType> { + ) -> core::result::Result<(), ErrorType> { unsafe { - use std::sync::atomic::{AtomicPtr, Ordering}; + use core::sync::atomic::{AtomicPtr, Ordering}; static FN: AtomicPtr<()> = AtomicPtr::new(get_fastest as FnRaw); @@ -687,11 +694,11 @@ impl Deserializer<'_> { #[cfg_attr(not(feature = "no-inline"), inline)] fn get_fastest_available_implementation() -> FindStructuralBitsFn { - if std::is_x86_feature_detected!("avx2") - && std::is_x86_feature_detected!("pclmulqdq") + if core_detect::is_x86_feature_detected!("avx2") + && core_detect::is_x86_feature_detected!("pclmulqdq") { find_structural_bits_avx2 - } else if std::is_x86_feature_detected!("sse4.2") { + } else if core_detect::is_x86_feature_detected!("sse4.2") { find_structural_bits_sse42 } else { #[cfg(feature = "portable")] @@ -954,7 +961,7 @@ impl<'de> Deserializer<'de> { pub(crate) unsafe fn _find_structural_bits( input: &[u8], structural_indexes: &mut Vec, - ) -> std::result::Result<(), ErrorType> { + ) -> core::result::Result<(), ErrorType> { let len = input.len(); // 8 is a heuristic number to estimate it turns out a rate of 1/8 structural characters // leads almost never to relocations. @@ -1185,12 +1192,12 @@ impl Deref for AlignedBuf { type Target = [u8]; fn deref(&self) -> &Self::Target { - unsafe { std::slice::from_raw_parts(self.inner.as_ptr(), self.len) } + unsafe { core::slice::from_raw_parts(self.inner.as_ptr(), self.len) } } } impl DerefMut for AlignedBuf { fn deref_mut(&mut self) -> &mut Self::Target { - unsafe { std::slice::from_raw_parts_mut(self.inner.as_ptr(), self.len) } + unsafe { core::slice::from_raw_parts_mut(self.inner.as_ptr(), self.len) } } } diff --git a/src/macros.rs b/src/macros.rs index 07db0644..9a11c0be 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -1277,6 +1277,7 @@ pub(crate) use stry; #[cfg(test)] mod test { + use alloc::vec; use crate::prelude::*; use crate::{BorrowedValue, OwnedValue}; diff --git a/src/serde/se.rs b/src/serde/se.rs index 7aba5b4c..451efc8c 100644 --- a/src/serde/se.rs +++ b/src/serde/se.rs @@ -1,9 +1,12 @@ mod pp; + +use alloc::string::String; +use alloc::vec::Vec; +use core::fmt::Write; use crate::{Error, ErrorType}; pub use pp::*; use serde_ext::ser; -use std::io::Write; -use std::str; + use value_trait::generator::BaseGenerator; macro_rules! iomap { @@ -61,7 +64,7 @@ where &mut self.0 } #[cfg_attr(not(feature = "no-inline"), inline)] - fn write_min(&mut self, _slice: &[u8], min: u8) -> std::io::Result<()> { + fn write_min(&mut self, _slice: &[u8], min: u8) -> SimdResult<()> { self.0.write_all(&[min]) } } diff --git a/src/serde/se/pp.rs b/src/serde/se/pp.rs index f78797ea..0283b885 100644 --- a/src/serde/se/pp.rs +++ b/src/serde/se/pp.rs @@ -1,11 +1,15 @@ +use alloc::string::{String, ToString}; +use alloc::vec::Vec; use crate::{Error, ErrorType, macros::stry}; use serde_ext::ser; -use std::io::Write; -use std::str; +use core::fmt::Write; +use core::str; use value_trait::generator::BaseGenerator; use super::key_must_be_a_string; +type SimdResult = Result; + macro_rules! iomap { ($e:expr_2021) => { ($e).map_err(|err| Error::generic(ErrorType::Io(err))) @@ -16,7 +20,7 @@ macro_rules! iomap { /// # Errors /// when the data can not be written #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn to_vec_pretty(to: &T) -> crate::Result> +pub fn to_vec_pretty(to: &T) -> SimdResult> where T: ser::Serialize + ?Sized, { @@ -73,7 +77,7 @@ where self.writer.write_all(&[min]) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn new_line(&mut self) -> std::io::Result<()> { + fn new_line(&mut self) -> SimdResult<()> { self.write_char(b'\n').and_then(|()| match self.dent { 0 => Ok(()), 1 => self.get_writer().write_all(b" "), @@ -887,6 +891,8 @@ where #[cfg(test)] mod test { #![allow(clippy::ignored_unit_patterns, unused_imports)] + + use alloc::string::String; use crate::OwnedValue as Value; #[cfg(not(target_arch = "wasm32"))] use crate::StaticNode; @@ -908,7 +914,7 @@ mod test { #[test] fn numerical_map_serde() { - use std::collections::HashMap; + use hashbrown::HashMap; #[derive(Clone, Debug, PartialEq, serde::Serialize)] struct Foo { diff --git a/src/value.rs b/src/value.rs index 2d854edc..d87c7514 100644 --- a/src/value.rs +++ b/src/value.rs @@ -59,6 +59,9 @@ pub mod tape; pub mod lazy; +use alloc::vec::Vec; +use core::hash::Hash; +use core::marker::PhantomData; pub use self::borrowed::{ Value as BorrowedValue, to_value as to_borrowed_value, to_value_with_buffers as to_borrowed_value_with_buffers, @@ -69,8 +72,6 @@ pub use self::owned::{ }; use crate::{Buffers, Deserializer, Result}; use halfbrown::HashMap; -use std::hash::Hash; -use std::marker::PhantomData; use tape::Node; pub use value_trait::*; diff --git a/src/value/borrowed.rs b/src/value/borrowed.rs index b3f938fc..0ca105ee 100644 --- a/src/value/borrowed.rs +++ b/src/value/borrowed.rs @@ -24,13 +24,16 @@ mod cmp; mod from; mod serialize; +use alloc::boxed::Box; +use alloc::string::ToString; +use alloc::vec::Vec; use super::ObjectHasher; use crate::{Buffers, prelude::*}; use crate::{Deserializer, Node, Result}; use crate::{cow::Cow, safer_unchecked::GetSaferUnchecked as _}; use halfbrown::HashMap; -use std::fmt; -use std::ops::{Index, IndexMut}; +use core::fmt; +use core::ops::{Index, IndexMut}; /// Representation of a JSON object pub type Object<'value> = HashMap, Value<'value>, ObjectHasher>; @@ -111,7 +114,7 @@ impl<'value> Value<'value> { // value will produce a owned value again see: // https://docs.rs/beef/0.4.4/src/beef/generic.rs.html#379-391 Self::String(s) => unsafe { - std::mem::transmute::, Value<'static>>(Self::String(Cow::from( + core::mem::transmute::, Value<'static>>(Self::String(Cow::from( s.into_owned(), ))) }, @@ -141,7 +144,7 @@ impl<'value> Value<'value> { // value will produce a owned value again see: // https://docs.rs/beef/0.4.4/src/beef/generic.rs.html#379-391 Self::String(s) => unsafe { - std::mem::transmute::, Value<'static>>(Self::String(Cow::from( + core::mem::transmute::, Value<'static>>(Self::String(Cow::from( s.to_string(), ))) }, @@ -270,7 +273,7 @@ impl ValueAsScalar for Value<'_> { #[cfg_attr(not(feature = "no-inline"), inline)] fn as_str(&self) -> Option<&str> { - use std::borrow::Borrow; + use alloc::borrow::Borrow; match self { Self::String(s) => Some(s.borrow()), _ => None, @@ -504,6 +507,9 @@ impl<'tape, 'de> BorrowSliceDeserializer<'tape, 'de> { mod test { #![allow(clippy::ignored_unit_patterns)] #![allow(clippy::cognitive_complexity)] + + use alloc::format; +use alloc::vec; use super::*; #[test] diff --git a/src/value/lazy/array.rs b/src/value/lazy/array.rs index a5d3093a..f3ae4772 100644 --- a/src/value/lazy/array.rs +++ b/src/value/lazy/array.rs @@ -1,4 +1,4 @@ -use std::borrow::Cow; +use alloc::borrow::Cow; use super::Value; use crate::{borrowed, tape}; @@ -17,7 +17,7 @@ pub enum Iter<'borrow, 'tape, 'input> { /// Tape variant Tape(tape::array::Iter<'tape, 'input>), /// Value variant - Value(std::slice::Iter<'borrow, borrowed::Value<'input>>), + Value(core::slice::Iter<'borrow, borrowed::Value<'input>>), } impl<'borrow, 'tape, 'input> Iterator for Iter<'borrow, 'tape, 'input> { @@ -70,6 +70,8 @@ impl<'tape, 'input> Array<'_, 'tape, 'input> { #[cfg(test)] mod test { + use alloc::vec; + use alloc::vec::Vec; use crate::to_tape; use value_trait::base::ValueAsScalar; diff --git a/src/value/lazy/from.rs b/src/value/lazy/from.rs index d44dc994..7827f491 100644 --- a/src/value/lazy/from.rs +++ b/src/value/lazy/from.rs @@ -1,7 +1,9 @@ use super::Value; use crate::StaticNode; use crate::{borrowed, cow::Cow}; -use std::borrow::Cow as StdCow; +use alloc::borrow::Cow as StdCow; +use alloc::string::String; +use alloc::vec::Vec; impl<'value> From> for Value<'_, '_, 'value> { #[cfg_attr(not(feature = "no-inline"), inline)] @@ -43,9 +45,9 @@ impl<'value> From> for Value<'_, '_, 'value> { } #[cfg(not(feature = "beef"))] -impl<'value> From> for Value<'_, '_, 'value> { +impl<'value> From> for Value<'_, '_, 'value> { #[cfg_attr(not(feature = "no-inline"), inline)] - fn from(v: std::borrow::Cow<'value, str>) -> Self { + fn from(v: StdCow<'value, str>) -> Self { Value::Value(StdCow::Owned(borrowed::Value::from(v))) } } diff --git a/src/value/lazy/trait_impls.rs b/src/value/lazy/trait_impls.rs index 843fe261..9016fd04 100644 --- a/src/value/lazy/trait_impls.rs +++ b/src/value/lazy/trait_impls.rs @@ -1,7 +1,6 @@ -use std::{ - borrow::{Borrow, Cow}, +use core::{ + borrow::{Borrow}, hash::Hash, - io::{self, Write}, }; use value_trait::{ diff --git a/src/value/tape.rs b/src/value/tape.rs index 0c5fb214..2fb6a76c 100644 --- a/src/value/tape.rs +++ b/src/value/tape.rs @@ -1,3 +1,5 @@ +use alloc::vec; +use alloc::vec::Vec; /// A tape of a parsed json, all values are extracted and validated and /// can be used without further computation. use value_trait::{StaticNode, TryTypeError, ValueType, base::TypedValue as _}; @@ -31,7 +33,7 @@ impl<'input> Tape<'input> { self.0.clear(); // SAFETY: At this point the tape is empty, so no data in there has a lifetime associated with it, // so we can safely change the lifetime of the tape to 'new - unsafe { std::mem::transmute(self) } + unsafe { core::mem::transmute(self) } } /// Deserializes the tape into a type that implements `serde::Deserialize` From d426560f56768fc0866de6a49ea592a7b7e18074 Mon Sep 17 00:00:00 2001 From: Ygg01 Date: Wed, 2 Sep 2026 22:55:13 +0200 Subject: [PATCH 2/2] STILL WIP --- Cargo.toml | 12 ++- src/impls/avx2/deser.rs | 16 +--- src/impls/native/deser.rs | 18 ++-- src/impls/native/stage1.rs | 3 +- src/impls/sse42/deser.rs | 4 +- src/lib.rs | 17 ++-- src/macros.rs | 4 +- src/numberparse/correct.rs | 16 ++-- src/serde.rs | 72 +++++++------- src/serde/de.rs | 85 ++++++++-------- src/serde/se.rs | 10 +- src/serde/se/pp.rs | 19 ++-- src/serde/value/borrowed.rs | 8 +- src/serde/value/borrowed/de.rs | 13 ++- src/serde/value/borrowed/se.rs | 165 +++++++++++++++++--------------- src/serde/value/owned.rs | 8 +- src/serde/value/owned/de.rs | 17 +++- src/serde/value/owned/se.rs | 162 ++++++++++++++++--------------- src/stage2.rs | 18 ++-- src/stringparse.rs | 2 +- src/value.rs | 6 +- src/value/borrowed.rs | 6 +- src/value/borrowed/cmp.rs | 9 +- src/value/borrowed/from.rs | 11 ++- src/value/borrowed/serialize.rs | 6 +- src/value/lazy.rs | 9 +- src/value/lazy/cmp.rs | 11 ++- src/value/lazy/object.rs | 34 +++---- src/value/lazy/trait_impls.rs | 11 ++- src/value/owned.rs | 16 +++- src/value/owned/cmp.rs | 10 +- src/value/owned/from.rs | 14 ++- src/value/owned/serialize.rs | 5 +- src/value/tape/cmp.rs | 12 +-- src/value/tape/object.rs | 6 +- src/value/tape/trait_impls.rs | 16 ++-- 36 files changed, 462 insertions(+), 389 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 7a515c39..694dd8f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,8 @@ rust-version = "1.88" [dependencies] simdutf8 = { version = "0.1.4", features = ["public_imp", "aarch64_neon"] } + +# no_std necessary crates core_detect = "1.0.0" hashbrown = "0.17.1" @@ -23,14 +25,15 @@ halfbrown = "0.4" ahash = { version = "0.8", optional = true } # serde compatibilty -serde = { version = "1", features = ["derive"], optional = true } -serde_json = { version = "1", optional = true } +serde_core = { version = "1.0.229", optional = true } +serde_json = { version = "1.0.151", optional = true } # perf testing alloc_counter = { version = "0.0.4", optional = true } colored = { version = "3.0", optional = true } getopts = { version = "0.2", optional = true } jemallocator = { version = "0.5", optional = true } +serde = { version = "1.0.229", features = ["derive"] } [target.'cfg(target_arch = "x86_64")'.dependencies] perfcnt = { version = "0.8", optional = true } @@ -61,6 +64,9 @@ harness = false [features] default = ["swar-number-parsing", "serde_impl", "runtime-detection"] + +io = [] + arraybackend = ["halfbrown/arraybackend"] # Forces the `owned::Value` and `borrowed::Value` to deduplicate duplicated keys by letting consecutive keys overwrite previous ones. This comes at a @@ -84,7 +90,7 @@ swar-number-parsing = [] approx-number-parsing = [] # serde compatibility -serde_impl = ["serde", "serde_json", "halfbrown/serde"] +serde_impl = ["serde_core", "serde_json", "halfbrown/serde"] # for testing allocations alloc = ["alloc_counter"] diff --git a/src/impls/avx2/deser.rs b/src/impls/avx2/deser.rs index cf978d0f..65ba94ee 100644 --- a/src/impls/avx2/deser.rs +++ b/src/impls/avx2/deser.rs @@ -2,20 +2,14 @@ use std::arch::x86 as arch; #[cfg(target_arch = "x86_64")] -use std::arch::x86_64 as arch; +use core::arch::x86_64 as arch; use arch::{ __m256i, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8, _mm256_set1_epi8, _mm256_storeu_si256, }; -use crate::{ - Deserializer, Result, SillyWrapper, - error::ErrorType, - macros::static_cast_u32, - safer_unchecked::GetSaferUnchecked, - stringparse::{ESCAPE_MAP, handle_unicode_codepoint}, -}; +use crate::{error::ErrorType, macros::static_cast_u32, safer_unchecked::GetSaferUnchecked, stringparse::{ESCAPE_MAP, handle_unicode_codepoint}, Deserializer, SillyWrapper, SJsonResult}; #[target_feature(enable = "avx2")] #[allow( @@ -29,7 +23,7 @@ pub(crate) unsafe fn parse_str<'invoke, 'de>( data: &'invoke [u8], buffer: &'invoke mut [u8], mut idx: usize, -) -> Result<&'de str> { +) -> SJsonResult<&'de str> { unsafe { use ErrorType::{InvalidEscape, InvalidUnicodeCodepoint}; @@ -73,7 +67,7 @@ pub(crate) unsafe fn parse_str<'invoke, 'de>( len += quote_dist as usize; let v = - std::str::from_utf8_unchecked(std::slice::from_raw_parts(input.add(idx), len)); + core::str::from_utf8_unchecked(core::slice::from_raw_parts(input.add(idx), len)); return Ok(v); // we compare the pointers since we care if they are 'at the same spot' @@ -130,7 +124,7 @@ pub(crate) unsafe fn parse_str<'invoke, 'de>( input .add(idx + len) .copy_from_nonoverlapping(buffer.as_ptr(), dst_i); - let v = std::str::from_utf8_unchecked(std::slice::from_raw_parts( + let v = core::str::from_utf8_unchecked(core::slice::from_raw_parts( input.add(idx), len + dst_i, )); diff --git a/src/impls/native/deser.rs b/src/impls/native/deser.rs index 1bfd47e3..7571cc0a 100644 --- a/src/impls/native/deser.rs +++ b/src/impls/native/deser.rs @@ -1,5 +1,5 @@ use crate::{ - Deserializer, ErrorType, Result, SillyWrapper, + Deserializer, ErrorType, SJsonResult, SillyWrapper, safer_unchecked::GetSaferUnchecked, stringparse::{ESCAPE_MAP, get_unicode_codepoint}, }; @@ -10,7 +10,7 @@ pub(crate) unsafe fn parse_str<'invoke, 'de>( data: &'invoke [u8], _buffer: &'invoke mut [u8], idx: usize, -) -> Result<&'de str> { +) -> SJsonResult<&'de str> { use ErrorType::{InvalidEscape, InvalidUnicodeCodepoint}; let input = input.input; @@ -27,7 +27,7 @@ pub(crate) unsafe fn parse_str<'invoke, 'de>( b = unsafe { *src.get_kinda_unchecked(src_i) }; } if b == b'"' { - let v = unsafe { std::str::from_utf8_unchecked(std::slice::from_raw_parts(input, src_i)) }; + let v = unsafe { core::str::from_utf8_unchecked(core::slice::from_raw_parts(input, src_i)) }; return Ok(v); } @@ -104,7 +104,7 @@ pub(crate) unsafe fn parse_str<'invoke, 'de>( b = unsafe { *src.get_kinda_unchecked(src_i) }; } unsafe { - Ok(std::str::from_utf8_unchecked(std::slice::from_raw_parts( + Ok(core::str::from_utf8_unchecked(core::slice::from_raw_parts( input, dst_i, ))) } @@ -112,9 +112,11 @@ pub(crate) unsafe fn parse_str<'invoke, 'de>( #[cfg(test)] mod test { + use alloc::string::String; + use alloc::vec; use crate::SIMDJSON_PADDING; - fn deser_str(input: &[u8]) -> Result { + fn deser_str(input: &[u8]) -> SJsonResult { let mut input = input.to_vec(); let mut input2 = input.clone(); input2.append(vec![0; SIMDJSON_PADDING * 2].as_mut()); @@ -127,21 +129,21 @@ mod test { } use super::*; #[test] - fn easy_string() -> Result<()> { + fn easy_string() -> SJsonResult<()> { let s = deser_str(&br#""snot""#[..])?; assert_eq!("snot", s); Ok(()) } #[test] - fn string_with_quote() -> Result<()> { + fn string_with_quote() -> SJsonResult<()> { let s = deser_str(&br#""snot says:\n \"badger\"""#[..])?; assert_eq!("snot says:\n \"badger\"", s); Ok(()) } #[test] - fn string_with_utf8() -> Result<()> { + fn string_with_utf8() -> SJsonResult<()> { let s = deser_str(&br#""\u000e""#[..])?; assert_eq!("\u{e}", s); Ok(()) diff --git a/src/impls/native/stage1.rs b/src/impls/native/stage1.rs index 56e140cf..31a315fe 100644 --- a/src/impls/native/stage1.rs +++ b/src/impls/native/stage1.rs @@ -1,5 +1,6 @@ #![allow(clippy::cast_lossless, clippy::cast_sign_loss)] +use alloc::vec::Vec; use crate::{Stage1Parse, macros::static_cast_i32}; type V128 = [u8; 16]; @@ -461,7 +462,7 @@ impl Stage1Parse for SimdInput { idx_64_v[2] + v2, idx_64_v[3] + v3, ]; - unsafe { std::ptr::write_unaligned(base.as_mut_ptr().add(l).cast::<[i32; 4]>(), v) }; + unsafe { core::ptr::write_unaligned(base.as_mut_ptr().add(l).cast::<[i32; 4]>(), v) }; l += 4; } // We have written all the data diff --git a/src/impls/sse42/deser.rs b/src/impls/sse42/deser.rs index 13214deb..4add4b38 100644 --- a/src/impls/sse42/deser.rs +++ b/src/impls/sse42/deser.rs @@ -5,7 +5,7 @@ use core::arch::x86 as arch; use core::arch::x86_64 as arch; use crate::{ - Deserializer, Result, SillyWrapper, + Deserializer, SJsonResult, SillyWrapper, error::ErrorType, safer_unchecked::GetSaferUnchecked, stringparse::{ESCAPE_MAP, handle_unicode_codepoint}, @@ -22,7 +22,7 @@ pub(crate) unsafe fn parse_str<'invoke, 'de>( data: &'invoke [u8], buffer: &'invoke mut [u8], mut idx: usize, -) -> Result<&'de str> { +) -> SJsonResult<&'de str> { unsafe { use ErrorType::{InvalidEscape, InvalidUnicodeCodepoint}; let input = input.input; diff --git a/src/lib.rs b/src/lib.rs index 78aded9c..f0f6892e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -83,7 +83,8 @@ pub use crate::value::*; pub use value_trait::ValueType; /// simd-json Result type -pub type Result = core::result::Result; +pub type SJsonResult = core::result::Result; +pub type StdCow<'value, T> = alloc::borrow::Cow<'value, T>; #[cfg(feature = "known-key")] mod known_key; @@ -160,7 +161,7 @@ impl Buffers { /// /// Will return `Err` if `s` is invalid JSON. #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn to_tape(s: &mut [u8]) -> Result> { +pub fn to_tape(s: &mut [u8]) -> SJsonResult> { Deserializer::from_slice(s).map(Deserializer::into_tape) } @@ -169,7 +170,7 @@ pub fn to_tape(s: &mut [u8]) -> Result> { /// /// Will return `Err` if `s` is invalid JSON. #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn to_tape_with_buffers<'de>(s: &'de mut [u8], buffers: &mut Buffers) -> Result> { +pub fn to_tape_with_buffers<'de>(s: &'de mut [u8], buffers: &mut Buffers) -> SJsonResult> { Deserializer::from_slice_with_buffers(s, buffers).map(Deserializer::into_tape) } @@ -178,7 +179,7 @@ pub fn to_tape_with_buffers<'de>(s: &'de mut [u8], buffers: &mut Buffers) -> Res /// /// Will return `Err` if `s` is invalid JSON. #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn fill_tape<'de>(s: &'de mut [u8], buffers: &mut Buffers, tape: &mut Tape<'de>) -> Result<()> { +pub fn fill_tape<'de>(s: &'de mut [u8], buffers: &mut Buffers, tape: &mut Tape<'de>) -> SJsonResult<()> { tape.0.clear(); Deserializer::fill_tape(s, buffers, &mut tape.0) } @@ -523,7 +524,7 @@ impl<'de> Deserializer<'de> { data: &'invoke [u8], buffer: &'invoke mut [u8], idx: usize, - ) -> Result<&'de str> + ) -> SJsonResult<&'de str> where 'de: 'invoke, { @@ -850,7 +851,7 @@ impl<'de> Deserializer<'de> { /// # Errors /// /// Will return `Err` if `s` is invalid JSON. - pub fn from_slice(input: &'de mut [u8]) -> Result { + pub fn from_slice(input: &'de mut [u8]) -> SJsonResult { let len = input.len(); let mut buffer = Buffers::new(len); @@ -871,7 +872,7 @@ impl<'de> Deserializer<'de> { input: &'de mut [u8], buffer: &mut Buffers, tape: &mut Vec>, - ) -> Result<()> { + ) -> SJsonResult<()> { const LOTS_OF_SPACES: [u8; SIMDINPUT_LENGTH] = [b' '; SIMDINPUT_LENGTH]; let len = input.len(); let simd_safe_len = len + SIMDINPUT_LENGTH; @@ -928,7 +929,7 @@ impl<'de> Deserializer<'de> { /// # Errors /// /// Will return `Err` if `s` is invalid JSON. - pub fn from_slice_with_buffers(input: &'de mut [u8], buffer: &mut Buffers) -> Result { + pub fn from_slice_with_buffers(input: &'de mut [u8], buffer: &mut Buffers) -> SJsonResult { let mut tape: Vec> = Vec::with_capacity(buffer.structural_indexes.len()); Self::fill_tape(input, buffer, &mut tape)?; diff --git a/src/macros.rs b/src/macros.rs index 9a11c0be..22e11e57 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -1267,8 +1267,8 @@ pub(crate) use static_cast_u64; macro_rules! stry { ($e:expr_2021) => { match $e { - ::std::result::Result::Ok(val) => val, - ::std::result::Result::Err(err) => return ::std::result::Result::Err(err), + ::core::result::Result::Ok(val) => val, + ::core::result::Result::Err(err) => return ::core::result::Result::Err(err), } }; } diff --git a/src/numberparse/correct.rs b/src/numberparse/correct.rs index 9f1d9d36..dbe2c832 100644 --- a/src/numberparse/correct.rs +++ b/src/numberparse/correct.rs @@ -12,7 +12,7 @@ use crate::error::Error; #[allow(unused_imports)] use crate::macros::{static_cast_i64, unlikely}; use crate::safer_unchecked::GetSaferUnchecked; -use crate::{Deserializer, ErrorType, Result}; +use crate::{Deserializer, ErrorType, SJsonResult}; macro_rules! get { ($buf:ident, $idx:expr_2021) => { @@ -58,7 +58,7 @@ impl Deserializer<'_> { clippy::cast_possible_truncation, clippy::too_many_lines )] - pub(crate) fn parse_number(idx: usize, buf: &[u8], negative: bool) -> Result { + pub(crate) fn parse_number(idx: usize, buf: &[u8], negative: bool) -> SJsonResult { let start_idx = idx; let mut idx = idx; if negative { @@ -223,7 +223,7 @@ fn parse_large_integer( buf: &[u8], negative: bool, #[allow(unused_variables)] end_index: usize, -) -> Result { +) -> SJsonResult { let mut idx = start_idx; if negative { idx += 1; @@ -330,7 +330,7 @@ fn f64_from_parts( exponent: i32, slice: &[u8], offset: usize, -) -> Result { +) -> SJsonResult { if (-22..=22).contains(&exponent) && significand <= 9_007_199_254_740_991 { let mut f = significand as f64; if exponent < 0 { @@ -379,7 +379,7 @@ fn f64_from_parts( leading_zeroes -= 1; } mantissa &= !(1 << 52); - let real_exponent = (factor_exponent as u64).wrapping_sub(leading_zeroes); + let real_exponent = (factor_exponent).wrapping_sub(leading_zeroes); // we have to check that real_exponent is in range, otherwise we bail out if !(1..=2046).contains(&real_exponent) { return f64_from_parts_slow(slice, offset); @@ -397,10 +397,10 @@ fn f64_from_parts( } #[cold] -fn f64_from_parts_slow(slice: &[u8], offset: usize) -> Result { +fn f64_from_parts_slow(slice: &[u8], offset: usize) -> SJsonResult { // we already validated the content of the slice we only need to translate // the slice to a string and parse it as parse is not defined for a u8 slice - match unsafe { std::str::from_utf8_unchecked(slice).parse::() } { + match unsafe { core::str::from_utf8_unchecked(slice).parse::() } { Ok(val) => { if val.is_infinite() { err!(offset, get!(slice, 0)) @@ -415,6 +415,8 @@ fn f64_from_parts_slow(slice: &[u8], offset: usize) -> Result { #[cfg(test)] mod test { #![allow(clippy::default_trait_access)] + + use alloc::string::String; use crate::error::Error; use crate::value::owned::Value; use crate::value::owned::Value::Static; diff --git a/src/serde.rs b/src/serde.rs index a08000d9..f517ccca 100644 --- a/src/serde.rs +++ b/src/serde.rs @@ -9,16 +9,19 @@ mod de; mod se; mod value; + +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::fmt; +use core::fmt::Formatter; pub use self::se::*; pub use self::value::*; use crate::{BorrowedValue, OwnedValue}; -use crate::{Buffers, Deserializer, Error, ErrorType, Node, Result, macros::stry}; +use crate::{Buffers, Deserializer, Error, ErrorType, Node, SJsonResult, macros::stry}; use serde::de::DeserializeOwned; use serde_ext::Deserialize; -use std::fmt; -use std::io; use value_trait::prelude::*; -type ConvertResult = std::result::Result; +type ConvertResult = core::result::Result; /// Error while converting from or to serde values #[derive(Debug)] @@ -30,8 +33,8 @@ pub enum SerdeConversionError { /// Something horrible went wrong, please open a ticket at Oops, } -impl std::fmt::Display for SerdeConversionError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +impl core::fmt::Display for SerdeConversionError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { use SerdeConversionError::{NanOrInfinity, NumberOutOfBounds, Oops}; match self { NanOrInfinity => write!(f, "JSON can not represent NAN or Infinity values"), @@ -44,7 +47,7 @@ impl std::fmt::Display for SerdeConversionError { } } -impl std::error::Error for SerdeConversionError {} +impl core::error::Error for SerdeConversionError {} /// parses a byte slice using a serde deserializer. /// note that the slice will be rewritten in the process. @@ -53,7 +56,7 @@ impl std::error::Error for SerdeConversionError {} /// /// Will return `Err` if `s` is invalid JSON. #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn from_slice<'a, T>(s: &'a mut [u8]) -> Result +pub fn from_slice<'a, T>(s: &'a mut [u8]) -> SJsonResult where T: Deserialize<'a>, { @@ -70,7 +73,7 @@ where /// /// Will return `Err` if `s` is invalid JSON. #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn from_slice_with_buffers<'a, T>(s: &'a mut [u8], buffers: &mut Buffers) -> Result +pub fn from_slice_with_buffers<'a, T>(s: &'a mut [u8], buffers: &mut Buffers) -> SJsonResult where T: Deserialize<'a>, { @@ -94,7 +97,7 @@ where /// holding the same guarantees as `str::as_bytes_mut` in that after the call &str might include /// invalid utf8 bytes. #[cfg_attr(not(feature = "no-inline"), inline)] -pub unsafe fn from_str<'a, T>(s: &'a mut str) -> Result +pub unsafe fn from_str<'a, T>(s: &'a mut str) -> SJsonResult where T: Deserialize<'a>, { @@ -121,7 +124,7 @@ where /// holding the same guarantees as `str::as_bytes_mut` in that after the call &str might include /// invalid utf8 bytes. #[cfg_attr(not(feature = "no-inline"), inline)] -pub unsafe fn from_str_with_buffers<'a, T>(s: &'a mut str, buffers: &mut Buffers) -> Result +pub unsafe fn from_str_with_buffers<'a, T>(s: &'a mut str, buffers: &mut Buffers) -> SJsonResult where T: Deserialize<'a>, { @@ -147,9 +150,9 @@ where /// Will return `Err` if an IO error is encountered while reading /// rdr or if the readers content is invalid JSON. #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn from_reader(mut rdr: R) -> Result +pub fn from_reader(mut rdr: R) -> SJsonResult where - R: io::Read, + // R: io::Read, T: DeserializeOwned, { let mut data = Vec::new(); @@ -169,9 +172,9 @@ where /// Will return `Err` if an IO error is encountered while reading /// rdr or if the readers content is invalid JSON. #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn from_reader_with_buffers(mut rdr: R, buffers: &mut Buffers) -> Result +pub fn from_reader_with_buffers(mut rdr: R, buffers: &mut Buffers) -> SJsonResult where - R: io::Read, + // R: io::Read, T: DeserializeOwned, { let mut data = Vec::new(); @@ -197,7 +200,7 @@ impl serde_ext::ser::Error for Error { // Functions purely used by serde impl<'de> Deserializer<'de> { #[cfg_attr(not(feature = "no-inline"), inline)] - fn next(&mut self) -> Result> { + fn next(&mut self) -> SJsonResult> { let r = self .tape .get(self.idx) @@ -208,7 +211,7 @@ impl<'de> Deserializer<'de> { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn peek(&self) -> Result> { + fn peek(&self) -> SJsonResult> { self.tape .get(self.idx) .copied() @@ -217,7 +220,7 @@ impl<'de> Deserializer<'de> { #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_sign_loss)] - fn parse_u8(&mut self) -> Result { + fn parse_u8(&mut self) -> SJsonResult { match stry!(self.next()) { Node::Static(s) => s .as_u8() @@ -228,7 +231,7 @@ impl<'de> Deserializer<'de> { #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_sign_loss)] - fn parse_u16(&mut self) -> Result { + fn parse_u16(&mut self) -> SJsonResult { let next = stry!(self.next()); match next { Node::Static(s) => s @@ -240,7 +243,7 @@ impl<'de> Deserializer<'de> { #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_sign_loss)] - fn parse_u32(&mut self) -> Result { + fn parse_u32(&mut self) -> SJsonResult { match stry!(self.next()) { Node::Static(s) => s .as_u32() @@ -251,7 +254,7 @@ impl<'de> Deserializer<'de> { #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_sign_loss)] - fn parse_u64(&mut self) -> Result { + fn parse_u64(&mut self) -> SJsonResult { match stry!(self.next()) { Node::Static(s) => s .as_u64() @@ -262,7 +265,7 @@ impl<'de> Deserializer<'de> { #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_sign_loss)] - fn parse_u128(&mut self) -> Result { + fn parse_u128(&mut self) -> SJsonResult { match stry!(self.next()) { Node::Static(s) => s .as_u128() @@ -273,7 +276,7 @@ impl<'de> Deserializer<'de> { #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_sign_loss)] - fn parse_i8(&mut self) -> Result { + fn parse_i8(&mut self) -> SJsonResult { match stry!(self.next()) { Node::Static(s) => s .as_i8() @@ -284,7 +287,7 @@ impl<'de> Deserializer<'de> { #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_sign_loss)] - fn parse_i16(&mut self) -> Result { + fn parse_i16(&mut self) -> SJsonResult { match stry!(self.next()) { Node::Static(s) => s .as_i16() @@ -295,7 +298,7 @@ impl<'de> Deserializer<'de> { #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_sign_loss)] - fn parse_i32(&mut self) -> Result { + fn parse_i32(&mut self) -> SJsonResult { match stry!(self.next()) { Node::Static(s) => s .as_i32() @@ -306,7 +309,7 @@ impl<'de> Deserializer<'de> { #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_sign_loss)] - fn parse_i64(&mut self) -> Result { + fn parse_i64(&mut self) -> SJsonResult { match stry!(self.next()) { Node::Static(s) => s .as_i64() @@ -317,7 +320,7 @@ impl<'de> Deserializer<'de> { #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_sign_loss)] - fn parse_i128(&mut self) -> Result { + fn parse_i128(&mut self) -> SJsonResult { match stry!(self.next()) { Node::Static(s) => s .as_i128() @@ -328,7 +331,7 @@ impl<'de> Deserializer<'de> { #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_possible_wrap, clippy::cast_precision_loss)] - fn parse_double(&mut self) -> Result { + fn parse_double(&mut self) -> SJsonResult { match stry!(self.next()) { #[allow(clippy::useless_conversion)] // .into() required by ordered-float Node::Static(StaticNode::F64(n)) => Ok(n.into()), @@ -491,7 +494,10 @@ mod test { use halfbrown::{HashMap, hashmap}; use serde::{Deserialize, Serialize}; use serde_json::{Value as SerdeValue, json as sjson, to_string as sto_string}; - use std::collections::BTreeMap; + use alloc::collections::BTreeMap; + use alloc::string::{String, ToString}; + use alloc::vec; + use alloc::vec::Vec; #[derive(Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] struct UnitStruct; @@ -819,7 +825,7 @@ mod test { }); let input: Vec> = vec![None, Some(3_u8)]; let mut v_str = crate::to_string(&input).unwrap(); - dbg!(&v_str); + // dbg!(&v_str); assert_eq!(input, unsafe { crate::from_str::>>(&mut v_str).unwrap() }); @@ -976,16 +982,16 @@ mod test { // assert_eq!(crate::to_string(&hashmap! {3f32 => 3i8}), key_error); // assert_eq!(crate::to_string(&hashmap! {3f64 => 3i8}), key_error); - let mut input = std::collections::HashMap::new(); + let mut input = hashbrown::HashMap::new(); input.insert(128_u8, "3"); let mut input_str = crate::to_string(&input).unwrap(); assert_eq!(input_str, sto_string(&input).unwrap()); assert_eq!( - unsafe { crate::from_str::>(&mut input_str) }, + unsafe { crate::from_str::>(&mut input_str) }, Err(Error::new(0, None, ErrorType::ExpectedSigned)) ); assert_eq!( - unsafe { crate::from_str::>(&mut input_str) }, + unsafe { crate::from_str::>(&mut input_str) }, Err(Error::new(0, None, ErrorType::InvalidNumber)) ); assert_eq!( diff --git a/src/serde/de.rs b/src/serde/de.rs index d819e822..23bb5fd4 100644 --- a/src/serde/de.rs +++ b/src/serde/de.rs @@ -1,8 +1,7 @@ use crate::serde_ext::de::IntoDeserializer; -use crate::{Deserializer, Error, ErrorType, Node, Result, StaticNode, macros::stry}; +use crate::{Deserializer, Error, ErrorType, Node, SJsonResult, StaticNode, macros::stry}; use serde_ext::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor}; use serde_ext::forward_to_deserialize_any; -use std::str; impl<'a, 'de> de::Deserializer<'de> for &'a mut Deserializer<'de> where @@ -14,7 +13,7 @@ where // deserialize as. Not all data formats are able to support this operation. // Formats that support `deserialize_any` are known as self-describing. #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_any(self, visitor: V) -> Result + fn deserialize_any(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -50,7 +49,7 @@ where // mapping it to a Serde data model "struct" type with a special name and a // single field containing the Datetime represented as a string. #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_bool(self, visitor: V) -> Result + fn deserialize_bool(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -63,7 +62,7 @@ where // Refer to the "Understanding deserializer lifetimes" page for information // about the three deserialization flavors of strings in Serde. #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_str(self, visitor: V) -> Result + fn deserialize_str(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -75,7 +74,7 @@ where } #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_string(self, visitor: V) -> Result + fn deserialize_string(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -90,7 +89,7 @@ where // it is invoked with `T=i8`. The next 8 methods are similar. #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_possible_truncation)] - fn deserialize_i8(self, visitor: V) -> Result + fn deserialize_i8(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -99,7 +98,7 @@ where #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_possible_truncation)] - fn deserialize_i16(self, visitor: V) -> Result + fn deserialize_i16(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -108,7 +107,7 @@ where #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_possible_truncation)] - fn deserialize_i32(self, visitor: V) -> Result + fn deserialize_i32(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -116,7 +115,7 @@ where } #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_i64(self, visitor: V) -> Result + fn deserialize_i64(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -124,7 +123,7 @@ where } #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_i128(self, visitor: V) -> Result + fn deserialize_i128(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -133,7 +132,7 @@ where #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_possible_truncation)] - fn deserialize_u8(self, visitor: V) -> Result + fn deserialize_u8(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -142,7 +141,7 @@ where #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_possible_truncation)] - fn deserialize_u16(self, visitor: V) -> Result + fn deserialize_u16(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -151,7 +150,7 @@ where #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_possible_truncation)] - fn deserialize_u32(self, visitor: V) -> Result + fn deserialize_u32(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -159,7 +158,7 @@ where } #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_u64(self, visitor: V) -> Result + fn deserialize_u64(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -167,7 +166,7 @@ where } #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_u128(self, visitor: V) -> Result + fn deserialize_u128(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -176,7 +175,7 @@ where #[cfg_attr(not(feature = "no-inline"), inline)] #[allow(clippy::cast_possible_truncation)] - fn deserialize_f32(self, visitor: V) -> Result + fn deserialize_f32(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -185,7 +184,7 @@ where } #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_f64(self, visitor: V) -> Result + fn deserialize_f64(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -202,7 +201,7 @@ where // more intelligently if possible. #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_option(self, visitor: V) -> Result + fn deserialize_option(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -216,7 +215,7 @@ where // In Serde, unit means an anonymous value containing no data. #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_unit(self, visitor: V) -> Result + fn deserialize_unit(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -230,7 +229,7 @@ where // passing the visitor an "Access" object that gives it the ability to // iterate through the data contained in the sequence. #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_seq(self, visitor: V) -> Result + fn deserialize_seq(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -251,7 +250,7 @@ where // tuple before even looking at the input data. #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_tuple(self, _len: usize, visitor: V) -> Result + fn deserialize_tuple(self, _len: usize, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -267,7 +266,7 @@ where _name: &'static str, _len: usize, visitor: V, - ) -> Result + ) -> SJsonResult where V: Visitor<'de>, { @@ -275,7 +274,7 @@ where } // Unit struct means a named value containing no data. - fn deserialize_unit_struct(self, _name: &'static str, visitor: V) -> Result + fn deserialize_unit_struct(self, _name: &'static str, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -285,7 +284,7 @@ where // As is done here, serializers are encouraged to treat newtype structs as // insignificant wrappers around the data they contain. That means not // parsing anything other than the contained value. - fn deserialize_newtype_struct(self, _name: &'static str, visitor: V) -> Result + fn deserialize_newtype_struct(self, _name: &'static str, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -293,7 +292,7 @@ where } #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_map(self, visitor: V) -> Result + fn deserialize_map(self, visitor: V) -> SJsonResult where V: Visitor<'de>, { @@ -312,7 +311,7 @@ where _name: &'static str, _fields: &'static [&'static str], visitor: V, - ) -> Result + ) -> SJsonResult where V: Visitor<'de>, { @@ -330,7 +329,7 @@ where _name: &'static str, _variants: &'static [&'static str], visitor: V, - ) -> Result + ) -> SJsonResult where V: Visitor<'de>, { @@ -368,7 +367,7 @@ impl<'de> de::EnumAccess<'de> for VariantAccess<'_, 'de> { type Error = Error; type Variant = Self; - fn variant_seed(self, seed: V) -> Result<(V::Value, Self)> + fn variant_seed(self, seed: V) -> SJsonResult<(V::Value, Self)> where V: de::DeserializeSeed<'de>, { @@ -380,25 +379,25 @@ impl<'de> de::EnumAccess<'de> for VariantAccess<'_, 'de> { impl<'de> de::VariantAccess<'de> for VariantAccess<'_, 'de> { type Error = Error; - fn unit_variant(self) -> Result<()> { + fn unit_variant(self) -> SJsonResult<()> { de::Deserialize::deserialize(self.de) } - fn newtype_variant_seed(self, seed: T) -> Result + fn newtype_variant_seed(self, seed: T) -> SJsonResult where T: de::DeserializeSeed<'de>, { seed.deserialize(self.de) } - fn tuple_variant(self, _len: usize, visitor: V) -> Result + fn tuple_variant(self, _len: usize, visitor: V) -> SJsonResult where V: de::Visitor<'de>, { de::Deserializer::deserialize_seq(self.de, visitor) } - fn struct_variant(self, fields: &'static [&'static str], visitor: V) -> Result + fn struct_variant(self, fields: &'static [&'static str], visitor: V) -> SJsonResult where V: de::Visitor<'de>, { @@ -426,7 +425,7 @@ impl<'de> SeqAccess<'de> for CommaSeparated<'_, 'de> { type Error = Error; #[cfg_attr(not(feature = "no-inline"), inline)] - fn next_element_seed(&mut self, seed: T) -> Result> + fn next_element_seed(&mut self, seed: T) -> SJsonResult> where T: DeserializeSeed<'de>, { @@ -449,7 +448,7 @@ impl<'de> MapAccess<'de> for CommaSeparated<'_, 'de> { type Error = Error; #[cfg_attr(not(feature = "no-inline"), inline)] - fn next_key_seed(&mut self, seed: K) -> Result> + fn next_key_seed(&mut self, seed: K) -> SJsonResult> where K: DeserializeSeed<'de>, { @@ -462,7 +461,7 @@ impl<'de> MapAccess<'de> for CommaSeparated<'_, 'de> { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn next_value_seed(&mut self, seed: V) -> Result + fn next_value_seed(&mut self, seed: V) -> SJsonResult where V: DeserializeSeed<'de>, { @@ -487,7 +486,7 @@ struct MapKey<'de: 'a, 'a> { macro_rules! deserialize_integer_key { ($method:ident => $visit:ident; $type:ty) => { - fn $method(self, visitor: V) -> Result + fn $method(self, visitor: V) -> SJsonResult where V: de::Visitor<'de>, { @@ -505,7 +504,7 @@ impl<'de> de::Deserializer<'de> for MapKey<'de, '_> { type Error = Error; #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_any(self, visitor: V) -> Result + fn deserialize_any(self, visitor: V) -> SJsonResult where V: de::Visitor<'de>, { @@ -530,7 +529,7 @@ impl<'de> de::Deserializer<'de> for MapKey<'de, '_> { deserialize_integer_key!(deserialize_u128 => visit_u128; u128); #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_option(self, visitor: V) -> Result + fn deserialize_option(self, visitor: V) -> SJsonResult where V: de::Visitor<'de>, { @@ -539,7 +538,7 @@ impl<'de> de::Deserializer<'de> for MapKey<'de, '_> { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_newtype_struct(self, _name: &'static str, visitor: V) -> Result + fn deserialize_newtype_struct(self, _name: &'static str, visitor: V) -> SJsonResult where V: de::Visitor<'de>, { @@ -552,7 +551,7 @@ impl<'de> de::Deserializer<'de> for MapKey<'de, '_> { name: &'static str, variants: &'static [&'static str], visitor: V, - ) -> Result + ) -> SJsonResult where V: de::Visitor<'de>, { @@ -560,7 +559,7 @@ impl<'de> de::Deserializer<'de> for MapKey<'de, '_> { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_bytes(self, visitor: V) -> Result + fn deserialize_bytes(self, visitor: V) -> SJsonResult where V: de::Visitor<'de>, { @@ -568,7 +567,7 @@ impl<'de> de::Deserializer<'de> for MapKey<'de, '_> { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn deserialize_byte_buf(self, visitor: V) -> Result + fn deserialize_byte_buf(self, visitor: V) -> SJsonResult where V: de::Visitor<'de>, { diff --git a/src/serde/se.rs b/src/serde/se.rs index 451efc8c..e2f95e28 100644 --- a/src/serde/se.rs +++ b/src/serde/se.rs @@ -3,7 +3,7 @@ mod pp; use alloc::string::String; use alloc::vec::Vec; use core::fmt::Write; -use crate::{Error, ErrorType}; +use crate::{Error, ErrorType, SJsonResult}; pub use pp::*; use serde_ext::ser; @@ -19,7 +19,7 @@ macro_rules! iomap { /// # Errors /// when the data can not be written #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn to_vec(to: &T) -> crate::Result> +pub fn to_vec(to: &T) -> SJsonResult> where T: ser::Serialize + ?Sized, { @@ -33,7 +33,7 @@ where /// # Errors /// when the data can not be written #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn to_string(to: &T) -> crate::Result +pub fn to_string(to: &T) -> SJsonResult where T: ser::Serialize + ?Sized, { @@ -44,7 +44,7 @@ where /// # Errors /// when the data can not be written #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn to_writer(writer: W, to: &T) -> crate::Result<()> +pub fn to_writer(writer: W, to: &T) -> SJsonResult<()> where T: ser::Serialize + ?Sized, W: Write, @@ -64,7 +64,7 @@ where &mut self.0 } #[cfg_attr(not(feature = "no-inline"), inline)] - fn write_min(&mut self, _slice: &[u8], min: u8) -> SimdResult<()> { + fn write_min(&mut self, _slice: &[u8], min: u8) -> SJsonResult<()> { self.0.write_all(&[min]) } } diff --git a/src/serde/se/pp.rs b/src/serde/se/pp.rs index 0283b885..c0c0a0f7 100644 --- a/src/serde/se/pp.rs +++ b/src/serde/se/pp.rs @@ -1,6 +1,6 @@ use alloc::string::{String, ToString}; use alloc::vec::Vec; -use crate::{Error, ErrorType, macros::stry}; +use crate::{macros::stry, Error, ErrorType, SJsonResult}; use serde_ext::ser; use core::fmt::Write; use core::str; @@ -8,7 +8,7 @@ use value_trait::generator::BaseGenerator; use super::key_must_be_a_string; -type SimdResult = Result; + macro_rules! iomap { ($e:expr_2021) => { @@ -20,7 +20,7 @@ macro_rules! iomap { /// # Errors /// when the data can not be written #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn to_vec_pretty(to: &T) -> SimdResult> +pub fn to_vec_pretty(to: &T) -> SJsonResult> where T: ser::Serialize + ?Sized, { @@ -34,7 +34,7 @@ where /// # Errors /// when the data can not be written #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn to_string_pretty(to: &T) -> crate::Result +pub fn to_string_pretty(to: &T) -> SJsonResult where T: ser::Serialize + ?Sized, { @@ -45,7 +45,7 @@ where /// # Errors /// when the data can not be written #[cfg_attr(not(feature = "no-inline"), inline)] -pub fn to_writer_pretty(writer: W, to: &T) -> crate::Result<()> +pub fn to_writer_pretty(writer: W, to: &T) -> SJsonResult<()> where T: ser::Serialize + ?Sized, W: Write, @@ -77,7 +77,7 @@ where self.writer.write_all(&[min]) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn new_line(&mut self) -> SimdResult<()> { + fn new_line(&mut self) -> SJsonResult<()> { self.write_char(b'\n').and_then(|()| match self.dent { 0 => Ok(()), 1 => self.get_writer().write_all(b" "), @@ -893,6 +893,7 @@ mod test { #![allow(clippy::ignored_unit_patterns, unused_imports)] use alloc::string::String; + use alloc::vec; use crate::OwnedValue as Value; #[cfg(not(target_arch = "wasm32"))] use crate::StaticNode; @@ -1016,7 +1017,7 @@ mod test { #[test] fn prop_json_encode_decode(val in arb_json_value()) { let mut encoded = crate::to_vec_pretty(&val).expect("to_vec_pretty"); - println!("{}", String::from_utf8_lossy(&encoded.clone())); + // println!("{}", String::from_utf8_lossy(&encoded.clone())); let res: Value = crate::from_slice(encoded.as_mut_slice()).expect("can't convert"); assert_eq!(val, res); } @@ -1034,13 +1035,13 @@ mod test { let mut res = match crate::to_vec_pretty(&v) { Ok(res) => res, Err(e) => { - println!("prettify: {e}"); + // println!("prettify: {e}"); assert_eq!(v, "snot"); vec![] } }; let s = unsafe { String::from_utf8_unchecked(res.clone()) }; - println!("{s}"); + // println!("{s}"); let v2: Value = from_slice(&mut res).expect("generated bad json"); assert_eq!(v, v2); } diff --git a/src/serde/value/borrowed.rs b/src/serde/value/borrowed.rs index 7d7609c1..b761864f 100644 --- a/src/serde/value/borrowed.rs +++ b/src/serde/value/borrowed.rs @@ -1,7 +1,7 @@ mod de; mod se; -use crate::{BorrowedValue, Result}; +use crate::{BorrowedValue, SJsonResult}; use serde_ext::de::Deserialize; use serde_ext::ser::Serialize; @@ -11,7 +11,7 @@ use serde_ext::ser::Serialize; /// # Errors /// /// Will return `Err` if value fails to be turned into a borrowed value -pub fn to_value<'se, T>(value: T) -> Result> +pub fn to_value<'se, T>(value: T) -> SJsonResult> where T: Serialize, { @@ -24,7 +24,7 @@ where /// # Errors /// /// Will return `Err` if `value` can not be deserialized -pub fn from_value<'de, T>(value: BorrowedValue<'de>) -> Result +pub fn from_value<'de, T>(value: BorrowedValue<'de>) -> SJsonResult where T: Deserialize<'de>, { @@ -37,7 +37,7 @@ where /// # Errors /// /// Will return `Err` if `value` fails to be deserialized -pub fn from_refvalue<'de, T>(value: &'de BorrowedValue<'de>) -> Result +pub fn from_refvalue<'de, T>(value: &'de BorrowedValue<'de>) -> SJsonResult where T: Deserialize<'de>, { diff --git a/src/serde/value/borrowed/de.rs b/src/serde/value/borrowed/de.rs index d282df3b..9d380c0f 100644 --- a/src/serde/value/borrowed/de.rs +++ b/src/serde/value/borrowed/de.rs @@ -1,3 +1,7 @@ +use alloc::borrow::ToOwned; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; // A lot of this logic is a re-implementation or copy of serde_json::Value use crate::Error; use crate::ObjectHasher; @@ -14,7 +18,7 @@ use serde_ext::{ }, forward_to_deserialize_any, }; -use std::fmt; +use core::fmt; impl<'de> de::Deserializer<'de> for Value<'de> { type Error = Error; @@ -142,7 +146,7 @@ impl<'de> de::Deserializer<'de> for Value<'de> { } } -struct Array<'de>(std::vec::IntoIter>); +struct Array<'de>(alloc::vec::IntoIter>); // `SeqAccess` is provided to the `Visitor` to give it the ability to iterate // through elements of the sequence. @@ -159,7 +163,7 @@ impl<'de> SeqAccess<'de> for Array<'de> { } } -struct ArrayRef<'de>(std::slice::Iter<'de, Value<'de>>); +struct ArrayRef<'de>(alloc::slice::Iter<'de, Value<'de>>); // `SeqAccess` is provided to the `Visitor` to give it the ability to iterate // through elements of the sequence. @@ -816,6 +820,9 @@ impl<'de> VariantAccess<'de> for VariantRefDeserializer<'de> { #[cfg(test)] mod test { + use alloc::string::{String, ToString}; + use alloc::vec; + use alloc::vec::Vec; use serde::Deserialize; use crate::{borrowed, json, prelude::*}; diff --git a/src/serde/value/borrowed/se.rs b/src/serde/value/borrowed/se.rs index b485b753..4bf47582 100644 --- a/src/serde/value/borrowed/se.rs +++ b/src/serde/value/borrowed/se.rs @@ -1,6 +1,10 @@ +use alloc::borrow::ToOwned; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; use super::to_value; use crate::{ - Error, ErrorType, Result, + Error, ErrorType, SJsonResult, cow::Cow, macros::stry, value::borrowed::{Object, Value}, @@ -9,12 +13,12 @@ use crate::{ObjectHasher, StaticNode}; use serde_ext::ser::{ self, Serialize, SerializeMap as SerializeMapTrait, SerializeSeq as SerializeSeqTrait, }; -use std::marker::PhantomData; +use core::marker::PhantomData; type Impossible = ser::Impossible; impl Serialize for Value<'_> { - fn serialize(&self, serializer: S) -> std::result::Result + fn serialize(&self, serializer: S) -> core::result::Result where S: ser::Serializer, { @@ -74,93 +78,93 @@ impl<'se> serde::Serializer for Serializer<'se> { type SerializeStructVariant = SerializeStructVariant<'se>; #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_bool(self, value: bool) -> Result> { + fn serialize_bool(self, value: bool) -> SJsonResult> { Ok(Value::Static(StaticNode::Bool(value))) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_i8(self, value: i8) -> Result> { + fn serialize_i8(self, value: i8) -> SJsonResult> { self.serialize_i64(i64::from(value)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_i16(self, value: i16) -> Result> { + fn serialize_i16(self, value: i16) -> SJsonResult> { self.serialize_i64(i64::from(value)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_i32(self, value: i32) -> Result> { + fn serialize_i32(self, value: i32) -> SJsonResult> { self.serialize_i64(i64::from(value)) } - fn serialize_i64(self, value: i64) -> Result> { + fn serialize_i64(self, value: i64) -> SJsonResult> { Ok(Value::Static(StaticNode::I64(value))) } #[cfg(feature = "128bit")] - fn serialize_i128(self, value: i128) -> Result> { + fn serialize_i128(self, value: i128) -> SJsonResult> { Ok(Value::Static(StaticNode::I128(value))) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_u8(self, value: u8) -> Result> { + fn serialize_u8(self, value: u8) -> SJsonResult> { self.serialize_u64(u64::from(value)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_u16(self, value: u16) -> Result> { + fn serialize_u16(self, value: u16) -> SJsonResult> { self.serialize_u64(u64::from(value)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_u32(self, value: u32) -> Result> { + fn serialize_u32(self, value: u32) -> SJsonResult> { self.serialize_u64(u64::from(value)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_u64(self, value: u64) -> Result> { + fn serialize_u64(self, value: u64) -> SJsonResult> { Ok(Value::Static(StaticNode::U64(value))) } #[cfg(feature = "128bit")] - fn serialize_u128(self, value: u128) -> Result> { + fn serialize_u128(self, value: u128) -> SJsonResult> { Ok(Value::Static(StaticNode::U128(value))) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_f32(self, value: f32) -> Result> { + fn serialize_f32(self, value: f32) -> SJsonResult> { self.serialize_f64(f64::from(value)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_f64(self, value: f64) -> Result> { + fn serialize_f64(self, value: f64) -> SJsonResult> { Ok(Value::Static(StaticNode::from(value))) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_char(self, value: char) -> Result> { + fn serialize_char(self, value: char) -> SJsonResult> { let mut s = String::new(); s.push(value); self.serialize_str(&s) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_str(self, value: &str) -> Result> { + fn serialize_str(self, value: &str) -> SJsonResult> { Ok(Value::from(value.to_owned())) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_bytes(self, value: &[u8]) -> Result> { + fn serialize_bytes(self, value: &[u8]) -> SJsonResult> { Ok(value.iter().copied().collect()) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_unit(self) -> Result> { + fn serialize_unit(self) -> SJsonResult> { Ok(Value::Static(StaticNode::Null)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_unit_struct(self, _name: &'static str) -> Result> { + fn serialize_unit_struct(self, _name: &'static str) -> SJsonResult> { self.serialize_unit() } @@ -170,12 +174,12 @@ impl<'se> serde::Serializer for Serializer<'se> { _name: &'static str, _variant_index: u32, variant: &'static str, - ) -> Result> { + ) -> SJsonResult> { self.serialize_str(variant) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> Result> + fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> SJsonResult> where T: ?Sized + Serialize, { @@ -188,7 +192,7 @@ impl<'se> serde::Serializer for Serializer<'se> { _variant_index: u32, variant: &'static str, value: &T, - ) -> Result> + ) -> SJsonResult> where T: ?Sized + Serialize, { @@ -199,25 +203,25 @@ impl<'se> serde::Serializer for Serializer<'se> { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_none(self) -> Result> { + fn serialize_none(self) -> SJsonResult> { self.serialize_unit() } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_some(self, value: &T) -> Result> + fn serialize_some(self, value: &T) -> SJsonResult> where T: ?Sized + Serialize, { value.serialize(self) } - fn serialize_seq(self, len: Option) -> Result { + fn serialize_seq(self, len: Option) -> SJsonResult { Ok(SerializeVec { vec: Vec::with_capacity(len.unwrap_or(0)), }) } - fn serialize_tuple(self, len: usize) -> Result { + fn serialize_tuple(self, len: usize) -> SJsonResult { self.serialize_seq(Some(len)) } @@ -225,7 +229,7 @@ impl<'se> serde::Serializer for Serializer<'se> { self, _name: &'static str, len: usize, - ) -> Result { + ) -> SJsonResult { self.serialize_seq(Some(len)) } @@ -235,21 +239,21 @@ impl<'se> serde::Serializer for Serializer<'se> { _variant_index: u32, variant: &'static str, len: usize, - ) -> Result { + ) -> SJsonResult { Ok(SerializeTupleVariant { name: variant, vec: Vec::with_capacity(len), }) } - fn serialize_map(self, len: Option) -> Result { + fn serialize_map(self, len: Option) -> SJsonResult { Ok(SerializeMap { map: Object::with_capacity_and_hasher(len.unwrap_or(0), ObjectHasher::default()), next_key: None, }) } - fn serialize_struct(self, _name: &'static str, len: usize) -> Result { + fn serialize_struct(self, _name: &'static str, len: usize) -> SJsonResult { self.serialize_map(Some(len)) } @@ -259,7 +263,7 @@ impl<'se> serde::Serializer for Serializer<'se> { _variant_index: u32, variant: &'static str, len: usize, - ) -> Result { + ) -> SJsonResult { Ok(SerializeStructVariant { name: variant, map: Object::with_capacity_and_hasher(len, ObjectHasher::default()), @@ -290,7 +294,7 @@ impl<'se> serde::ser::SerializeSeq for SerializeVec<'se> { type Ok = Value<'se>; type Error = Error; - fn serialize_element(&mut self, value: &T) -> Result<()> + fn serialize_element(&mut self, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { @@ -298,7 +302,7 @@ impl<'se> serde::ser::SerializeSeq for SerializeVec<'se> { Ok(()) } - fn end(self) -> Result> { + fn end(self) -> SJsonResult> { Ok(Value::Array(Box::new(self.vec))) } } @@ -307,14 +311,14 @@ impl<'se> serde::ser::SerializeTuple for SerializeVec<'se> { type Ok = Value<'se>; type Error = Error; - fn serialize_element(&mut self, value: &T) -> Result<()> + fn serialize_element(&mut self, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { serde::ser::SerializeSeq::serialize_element(self, value) } - fn end(self) -> Result> { + fn end(self) -> SJsonResult> { serde::ser::SerializeSeq::end(self) } } @@ -323,14 +327,14 @@ impl<'se> serde::ser::SerializeTupleStruct for SerializeVec<'se> { type Ok = Value<'se>; type Error = Error; - fn serialize_field(&mut self, value: &T) -> Result<()> + fn serialize_field(&mut self, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { serde::ser::SerializeSeq::serialize_element(self, value) } - fn end(self) -> Result> { + fn end(self) -> SJsonResult> { serde::ser::SerializeSeq::end(self) } } @@ -339,7 +343,7 @@ impl<'se> serde::ser::SerializeTupleVariant for SerializeTupleVariant<'se> { type Ok = Value<'se>; type Error = Error; - fn serialize_field(&mut self, value: &T) -> Result<()> + fn serialize_field(&mut self, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { @@ -347,7 +351,7 @@ impl<'se> serde::ser::SerializeTupleVariant for SerializeTupleVariant<'se> { Ok(()) } - fn end(self) -> Result> { + fn end(self) -> SJsonResult> { let mut object = Object::with_capacity_and_hasher(1, ObjectHasher::default()); unsafe { object.insert_nocheck(self.name.into(), Value::Array(Box::new(self.vec))) }; @@ -359,7 +363,7 @@ impl<'se> serde::ser::SerializeMap for SerializeMap<'se> { type Ok = Value<'se>; type Error = Error; - fn serialize_key(&mut self, key: &T) -> Result<()> + fn serialize_key(&mut self, key: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { @@ -369,7 +373,7 @@ impl<'se> serde::ser::SerializeMap for SerializeMap<'se> { Ok(()) } - fn serialize_value(&mut self, value: &T) -> Result<()> + fn serialize_value(&mut self, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { @@ -381,7 +385,7 @@ impl<'se> serde::ser::SerializeMap for SerializeMap<'se> { Ok(()) } - fn end(self) -> Result> { + fn end(self) -> SJsonResult> { Ok(Value::Object(Box::new(self.map))) } } @@ -412,63 +416,63 @@ impl<'se> serde_ext::Serializer for MapKeySerializer<'se> { _name: &'static str, _variant_index: u32, variant: &'static str, - ) -> Result { + ) -> SJsonResult { Ok(Cow::from(variant)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> Result + fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> SJsonResult where T: ?Sized + Serialize, { value.serialize(self) } - fn serialize_bool(self, _value: bool) -> Result { + fn serialize_bool(self, _value: bool) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_i8(self, value: i8) -> Result { + fn serialize_i8(self, value: i8) -> SJsonResult { Ok(value.to_string().into()) } - fn serialize_i16(self, value: i16) -> Result { + fn serialize_i16(self, value: i16) -> SJsonResult { Ok(value.to_string().into()) } - fn serialize_i32(self, value: i32) -> Result { + fn serialize_i32(self, value: i32) -> SJsonResult { Ok(value.to_string().into()) } - fn serialize_i64(self, value: i64) -> Result { + fn serialize_i64(self, value: i64) -> SJsonResult { Ok(value.to_string().into()) } - fn serialize_u8(self, value: u8) -> Result { + fn serialize_u8(self, value: u8) -> SJsonResult { Ok(value.to_string().into()) } - fn serialize_u16(self, value: u16) -> Result { + fn serialize_u16(self, value: u16) -> SJsonResult { Ok(value.to_string().into()) } - fn serialize_u32(self, value: u32) -> Result { + fn serialize_u32(self, value: u32) -> SJsonResult { Ok(value.to_string().into()) } - fn serialize_u64(self, value: u64) -> Result { + fn serialize_u64(self, value: u64) -> SJsonResult { Ok(value.to_string().into()) } - fn serialize_f32(self, _value: f32) -> Result { + fn serialize_f32(self, _value: f32) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_f64(self, _value: f64) -> Result { + fn serialize_f64(self, _value: f64) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_char(self, value: char) -> Result { + fn serialize_char(self, value: char) -> SJsonResult { Ok({ let mut s = String::new(); s.push(value); @@ -477,20 +481,20 @@ impl<'se> serde_ext::Serializer for MapKeySerializer<'se> { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_str(self, value: &str) -> Result { + fn serialize_str(self, value: &str) -> SJsonResult { // TODO: we copy `value` here this is not idea but safe Ok(Cow::from(value.to_string())) } - fn serialize_bytes(self, _value: &[u8]) -> Result { + fn serialize_bytes(self, _value: &[u8]) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_unit(self) -> Result { + fn serialize_unit(self) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_unit_struct(self, _name: &'static str) -> Result { + fn serialize_unit_struct(self, _name: &'static str) -> SJsonResult { Err(key_must_be_a_string()) } @@ -500,29 +504,29 @@ impl<'se> serde_ext::Serializer for MapKeySerializer<'se> { _variant_index: u32, _variant: &'static str, _value: &T, - ) -> Result + ) -> SJsonResult where T: ?Sized + Serialize, { Err(key_must_be_a_string()) } - fn serialize_none(self) -> Result { + fn serialize_none(self) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_some(self, _value: &T) -> Result + fn serialize_some(self, _value: &T) -> SJsonResult where T: ?Sized + Serialize, { Err(key_must_be_a_string()) } - fn serialize_seq(self, _len: Option) -> Result { + fn serialize_seq(self, _len: Option) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_tuple(self, _len: usize) -> Result { + fn serialize_tuple(self, _len: usize) -> SJsonResult { Err(key_must_be_a_string()) } @@ -530,7 +534,7 @@ impl<'se> serde_ext::Serializer for MapKeySerializer<'se> { self, _name: &'static str, _len: usize, - ) -> Result { + ) -> SJsonResult { Err(key_must_be_a_string()) } @@ -540,15 +544,15 @@ impl<'se> serde_ext::Serializer for MapKeySerializer<'se> { _variant_index: u32, _variant: &'static str, _len: usize, - ) -> Result { + ) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_map(self, _len: Option) -> Result { + fn serialize_map(self, _len: Option) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { + fn serialize_struct(self, _name: &'static str, _len: usize) -> SJsonResult { Err(key_must_be_a_string()) } @@ -558,7 +562,7 @@ impl<'se> serde_ext::Serializer for MapKeySerializer<'se> { _variant_index: u32, _variant: &'static str, _len: usize, - ) -> Result { + ) -> SJsonResult { Err(key_must_be_a_string()) } } @@ -567,7 +571,7 @@ impl<'se> serde::ser::SerializeStruct for SerializeMap<'se> { type Ok = Value<'se>; type Error = Error; - fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<()> + fn serialize_field(&mut self, key: &'static str, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { @@ -575,7 +579,7 @@ impl<'se> serde::ser::SerializeStruct for SerializeMap<'se> { serde::ser::SerializeMap::serialize_value(self, value) } - fn end(self) -> Result> { + fn end(self) -> SJsonResult> { serde::ser::SerializeMap::end(self) } } @@ -584,7 +588,7 @@ impl<'se> serde::ser::SerializeStructVariant for SerializeStructVariant<'se> { type Ok = Value<'se>; type Error = Error; - fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<()> + fn serialize_field(&mut self, key: &'static str, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { @@ -592,7 +596,7 @@ impl<'se> serde::ser::SerializeStructVariant for SerializeStructVariant<'se> { Ok(()) } - fn end(self) -> Result> { + fn end(self) -> SJsonResult> { let mut object = Object::with_capacity_and_hasher(1, ObjectHasher::default()); unsafe { object.insert_nocheck(self.name.into(), self.map.into()) }; Ok(Value::Object(Box::new(object))) @@ -602,6 +606,11 @@ impl<'se> serde::ser::SerializeStructVariant for SerializeStructVariant<'se> { #[cfg(test)] mod test { #![allow(clippy::ignored_unit_patterns)] + + use alloc::boxed::Box; + use alloc::string::{String, ToString}; + use alloc::{format, vec}; + use alloc::vec::Vec; use super::Value; use crate::{ObjectHasher, borrowed::Object, serde::from_slice}; use serde::{Deserialize, Serialize}; @@ -708,7 +717,7 @@ mod test { let vec2 = crate::serde::to_vec(&o).expect("to_vec"); assert_eq!(vec, vec2); - println!("{}", serde_json::to_string_pretty(&o).expect("json")); + // println!("{}", serde_json::to_string_pretty(&o).expect("json")); let de: Obj = from_slice(&mut vec).expect("from_slice"); assert_eq!(o, de); } @@ -764,7 +773,7 @@ mod test { let mut vec = serde_json::to_vec(&obj).expect("to_vec"); let vec1 = vec.clone(); let vec2 = vec.clone(); - println!("{}", serde_json::to_string_pretty(&obj).expect("json")); + // println!("{}", serde_json::to_string_pretty(&obj).expect("json")); let de: Obj = from_slice(&mut vec).expect("from_slice"); prop_assert_eq!(&obj, &de); diff --git a/src/serde/value/owned.rs b/src/serde/value/owned.rs index ce48a399..423f126b 100644 --- a/src/serde/value/owned.rs +++ b/src/serde/value/owned.rs @@ -2,7 +2,7 @@ mod de; mod se; use crate::OwnedValue; -use crate::Result; +use crate::SJsonResult; use serde_ext::de::DeserializeOwned; use serde_ext::ser::Serialize; @@ -12,7 +12,7 @@ use serde_ext::ser::Serialize; /// # Errors /// /// Will return `Err` if value fails to be turned into a owned value -pub fn to_value(value: T) -> Result +pub fn to_value(value: T) -> SJsonResult where T: Serialize, { @@ -25,7 +25,7 @@ where /// # Errors /// /// Will return `Err` if `value` fails to be deserialized -pub fn from_value(value: OwnedValue) -> Result +pub fn from_value(value: OwnedValue) -> SJsonResult where T: DeserializeOwned, { @@ -38,7 +38,7 @@ where /// # Errors /// /// Will return `Err` if `value` fails to be deserialized -pub fn from_refvalue(value: &OwnedValue) -> Result +pub fn from_refvalue(value: &OwnedValue) -> SJsonResult where T: DeserializeOwned, { diff --git a/src/serde/value/owned/de.rs b/src/serde/value/owned/de.rs index ca92c759..bef591c2 100644 --- a/src/serde/value/owned/de.rs +++ b/src/serde/value/owned/de.rs @@ -1,3 +1,7 @@ +use alloc::borrow::ToOwned; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; // A lot of this logic is a re-implementation or copy of serde_json::Value use crate::ErrorType; use crate::{Error, ObjectHasher}; @@ -13,7 +17,7 @@ use serde_ext::{ }, forward_to_deserialize_any, }; -use std::fmt; + impl<'de> de::Deserializer<'de> for Value { type Error = Error; @@ -130,7 +134,7 @@ impl<'de> de::Deserializer<'de> for Value { } } -struct Array(std::vec::IntoIter); +struct Array(alloc::vec::IntoIter); // `SeqAccess` is provided to the `Visitor` to give it the ability to iterate // through elements of the sequence. @@ -147,7 +151,7 @@ impl<'de> SeqAccess<'de> for Array { } } -struct ArrayRef<'de>(std::slice::Iter<'de, Value>); +struct ArrayRef<'de>(core::slice::Iter<'de, Value>); // `SeqAccess` is provided to the `Visitor` to give it the ability to iterate // through elements of the sequence. @@ -256,7 +260,7 @@ struct ValueVisitor; impl<'de> Visitor<'de> for ValueVisitor { type Value = Value; - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { formatter.write_str("a JSONesque value") } @@ -793,6 +797,9 @@ impl<'de> VariantAccess<'de> for VariantRefDeserializer<'de> { #[cfg(test)] mod test { + use alloc::string::{String, ToString}; + use alloc::vec; + use alloc::vec::Vec; use crate::{json, owned, prelude::*}; use serde::Deserialize; @@ -929,7 +936,7 @@ mod test { config: Option, } impl<'v> serde::Deserialize<'v> for NameAndConfig { - fn deserialize(deserializer: D) -> std::result::Result + fn deserialize(deserializer: D) -> core::result::Result where D: serde::Deserializer<'v>, { diff --git a/src/serde/value/owned/se.rs b/src/serde/value/owned/se.rs index 4ecd87c0..9c923def 100644 --- a/src/serde/value/owned/se.rs +++ b/src/serde/value/owned/se.rs @@ -1,6 +1,10 @@ +use alloc::borrow::ToOwned; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; use super::to_value; use crate::{ - Error, ErrorType, ObjectHasher, Result, StaticNode, + Error, ErrorType, ObjectHasher, SJsonResult, StaticNode, macros::stry, value::owned::{Object, Value}, }; @@ -11,7 +15,7 @@ use serde_ext::ser::{ type Impossible = ser::Impossible; impl Serialize for Value { - fn serialize(&self, serializer: S) -> std::result::Result + fn serialize(&self, serializer: S) -> Result where S: ser::Serializer, { @@ -48,7 +52,7 @@ impl Serialize for Value { #[derive(Default)] pub struct Serializer {} -impl serde::Serializer for Serializer { +impl serde_core::Serializer for Serializer { type Ok = Value; type Error = Error; @@ -61,26 +65,26 @@ impl serde::Serializer for Serializer { type SerializeStructVariant = SerializeStructVariant; #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_bool(self, value: bool) -> Result { + fn serialize_bool(self, value: bool) -> SJsonResult { Ok(Value::Static(StaticNode::Bool(value))) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_i8(self, value: i8) -> Result { + fn serialize_i8(self, value: i8) -> SJsonResult { self.serialize_i64(i64::from(value)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_i16(self, value: i16) -> Result { + fn serialize_i16(self, value: i16) -> SJsonResult { self.serialize_i64(i64::from(value)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_i32(self, value: i32) -> Result { + fn serialize_i32(self, value: i32) -> SJsonResult { self.serialize_i64(i64::from(value)) } - fn serialize_i64(self, value: i64) -> Result { + fn serialize_i64(self, value: i64) -> SJsonResult { Ok(Value::Static(StaticNode::I64(value))) } @@ -90,64 +94,64 @@ impl serde::Serializer for Serializer { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_u8(self, value: u8) -> Result { + fn serialize_u8(self, value: u8) -> SJsonResult { self.serialize_u64(u64::from(value)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_u16(self, value: u16) -> Result { + fn serialize_u16(self, value: u16) -> SJsonResult { self.serialize_u64(u64::from(value)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_u32(self, value: u32) -> Result { + fn serialize_u32(self, value: u32) -> SJsonResult { self.serialize_u64(u64::from(value)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_u64(self, value: u64) -> Result { + fn serialize_u64(self, value: u64) -> SJsonResult { Ok(Value::Static(StaticNode::U64(value))) } #[cfg(feature = "128bit")] - fn serialize_u128(self, value: u128) -> Result { + fn serialize_u128(self, value: u128) -> SJsonResult { Ok(Value::Static(StaticNode::U128(value))) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_f32(self, value: f32) -> Result { + fn serialize_f32(self, value: f32) -> SJsonResult { self.serialize_f64(f64::from(value)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_f64(self, value: f64) -> Result { + fn serialize_f64(self, value: f64) -> SJsonResult { Ok(Value::Static(StaticNode::from(value))) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_char(self, value: char) -> Result { + fn serialize_char(self, value: char) -> SJsonResult { let mut s = String::new(); s.push(value); self.serialize_str(&s) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_str(self, value: &str) -> Result { + fn serialize_str(self, value: &str) -> SJsonResult { Ok(Value::from(value.to_owned())) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_bytes(self, value: &[u8]) -> Result { + fn serialize_bytes(self, value: &[u8]) -> SJsonResult { Ok(value.iter().copied().collect()) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_unit(self) -> Result { + fn serialize_unit(self) -> SJsonResult { Ok(Value::Static(StaticNode::Null)) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_unit_struct(self, _name: &'static str) -> Result { + fn serialize_unit_struct(self, _name: &'static str) -> SJsonResult { self.serialize_unit() } @@ -157,12 +161,12 @@ impl serde::Serializer for Serializer { _name: &'static str, _variant_index: u32, variant: &'static str, - ) -> Result { + ) -> SJsonResult { self.serialize_str(variant) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> Result + fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> SJsonResult where T: ?Sized + Serialize, { @@ -175,7 +179,7 @@ impl serde::Serializer for Serializer { _variant_index: u32, variant: &'static str, value: &T, - ) -> Result + ) -> SJsonResult where T: ?Sized + Serialize, { @@ -185,25 +189,25 @@ impl serde::Serializer for Serializer { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_none(self) -> Result { + fn serialize_none(self) -> SJsonResult { self.serialize_unit() } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_some(self, value: &T) -> Result + fn serialize_some(self, value: &T) -> SJsonResult where T: ?Sized + Serialize, { value.serialize(self) } - fn serialize_seq(self, len: Option) -> Result { + fn serialize_seq(self, len: Option) -> SJsonResult { Ok(SerializeVec { vec: Vec::with_capacity(len.unwrap_or(0)), }) } - fn serialize_tuple(self, len: usize) -> Result { + fn serialize_tuple(self, len: usize) -> SJsonResult { self.serialize_seq(Some(len)) } @@ -211,7 +215,7 @@ impl serde::Serializer for Serializer { self, _name: &'static str, len: usize, - ) -> Result { + ) -> SJsonResult { self.serialize_seq(Some(len)) } @@ -221,21 +225,21 @@ impl serde::Serializer for Serializer { _variant_index: u32, variant: &'static str, len: usize, - ) -> Result { + ) -> SJsonResult { Ok(SerializeTupleVariant { name: variant.to_owned(), vec: Vec::with_capacity(len), }) } - fn serialize_map(self, len: Option) -> Result { + fn serialize_map(self, len: Option) -> SJsonResult { Ok(SerializeMap { map: Object::with_capacity_and_hasher(len.unwrap_or(0), ObjectHasher::default()), next_key: None, }) } - fn serialize_struct(self, _name: &'static str, len: usize) -> Result { + fn serialize_struct(self, _name: &'static str, len: usize) -> SJsonResult { self.serialize_map(Some(len)) } @@ -245,7 +249,7 @@ impl serde::Serializer for Serializer { _variant_index: u32, variant: &'static str, len: usize, - ) -> Result { + ) -> SJsonResult { Ok(SerializeStructVariant { name: variant.to_owned(), map: Object::with_capacity_and_hasher(len, ObjectHasher::default()), @@ -276,7 +280,7 @@ impl serde::ser::SerializeSeq for SerializeVec { type Ok = Value; type Error = Error; - fn serialize_element(&mut self, value: &T) -> Result<()> + fn serialize_element(&mut self, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { @@ -284,7 +288,7 @@ impl serde::ser::SerializeSeq for SerializeVec { Ok(()) } - fn end(self) -> Result { + fn end(self) -> SJsonResult { Ok(Value::Array(Box::new(self.vec))) } } @@ -293,14 +297,14 @@ impl serde::ser::SerializeTuple for SerializeVec { type Ok = Value; type Error = Error; - fn serialize_element(&mut self, value: &T) -> Result<()> + fn serialize_element(&mut self, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { serde::ser::SerializeSeq::serialize_element(self, value) } - fn end(self) -> Result { + fn end(self) -> SJsonResult { serde::ser::SerializeSeq::end(self) } } @@ -309,14 +313,14 @@ impl serde::ser::SerializeTupleStruct for SerializeVec { type Ok = Value; type Error = Error; - fn serialize_field(&mut self, value: &T) -> Result<()> + fn serialize_field(&mut self, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { serde::ser::SerializeSeq::serialize_element(self, value) } - fn end(self) -> Result { + fn end(self) -> SJsonResult { serde::ser::SerializeSeq::end(self) } } @@ -325,7 +329,7 @@ impl serde::ser::SerializeTupleVariant for SerializeTupleVariant { type Ok = Value; type Error = Error; - fn serialize_field(&mut self, value: &T) -> Result<()> + fn serialize_field(&mut self, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { @@ -333,7 +337,7 @@ impl serde::ser::SerializeTupleVariant for SerializeTupleVariant { Ok(()) } - fn end(self) -> Result { + fn end(self) -> SJsonResult { let mut object = Object::with_capacity_and_hasher(1, ObjectHasher::default()); unsafe { object.insert_nocheck(self.name, Value::Array(Box::new(self.vec))) }; Ok(Value::from(object)) @@ -344,7 +348,7 @@ impl serde::ser::SerializeMap for SerializeMap { type Ok = Value; type Error = Error; - fn serialize_key(&mut self, key: &T) -> Result<()> + fn serialize_key(&mut self, key: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { @@ -352,7 +356,7 @@ impl serde::ser::SerializeMap for SerializeMap { Ok(()) } - fn serialize_value(&mut self, value: &T) -> Result<()> + fn serialize_value(&mut self, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { @@ -364,7 +368,7 @@ impl serde::ser::SerializeMap for SerializeMap { Ok(()) } - fn end(self) -> Result { + fn end(self) -> SJsonResult { Ok(Value::from(self.map)) } } @@ -393,63 +397,63 @@ impl serde_ext::Serializer for MapKeySerializer { _name: &'static str, _variant_index: u32, variant: &'static str, - ) -> Result { + ) -> SJsonResult { Ok(variant.to_owned()) } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> Result + fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> SJsonResult where T: ?Sized + Serialize, { value.serialize(self) } - fn serialize_bool(self, _value: bool) -> Result { + fn serialize_bool(self, _value: bool) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_i8(self, value: i8) -> Result { + fn serialize_i8(self, value: i8) -> SJsonResult { Ok(value.to_string()) } - fn serialize_i16(self, value: i16) -> Result { + fn serialize_i16(self, value: i16) -> SJsonResult { Ok(value.to_string()) } - fn serialize_i32(self, value: i32) -> Result { + fn serialize_i32(self, value: i32) -> SJsonResult { Ok(value.to_string()) } - fn serialize_i64(self, value: i64) -> Result { + fn serialize_i64(self, value: i64) -> SJsonResult { Ok(value.to_string()) } - fn serialize_u8(self, value: u8) -> Result { + fn serialize_u8(self, value: u8) -> SJsonResult { Ok(value.to_string()) } - fn serialize_u16(self, value: u16) -> Result { + fn serialize_u16(self, value: u16) -> SJsonResult { Ok(value.to_string()) } - fn serialize_u32(self, value: u32) -> Result { + fn serialize_u32(self, value: u32) -> SJsonResult { Ok(value.to_string()) } - fn serialize_u64(self, value: u64) -> Result { + fn serialize_u64(self, value: u64) -> SJsonResult { Ok(value.to_string()) } - fn serialize_f32(self, _value: f32) -> Result { + fn serialize_f32(self, _value: f32) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_f64(self, _value: f64) -> Result { + fn serialize_f64(self, _value: f64) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_char(self, value: char) -> Result { + fn serialize_char(self, value: char) -> SJsonResult { Ok({ let mut s = String::new(); s.push(value); @@ -458,19 +462,19 @@ impl serde_ext::Serializer for MapKeySerializer { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn serialize_str(self, value: &str) -> Result { + fn serialize_str(self, value: &str) -> SJsonResult { Ok(value.to_owned()) } - fn serialize_bytes(self, _value: &[u8]) -> Result { + fn serialize_bytes(self, _value: &[u8]) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_unit(self) -> Result { + fn serialize_unit(self) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_unit_struct(self, _name: &'static str) -> Result { + fn serialize_unit_struct(self, _name: &'static str) -> SJsonResult { Err(key_must_be_a_string()) } @@ -480,29 +484,29 @@ impl serde_ext::Serializer for MapKeySerializer { _variant_index: u32, _variant: &'static str, _value: &T, - ) -> Result + ) -> SJsonResult where T: ?Sized + Serialize, { Err(key_must_be_a_string()) } - fn serialize_none(self) -> Result { + fn serialize_none(self) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_some(self, _value: &T) -> Result + fn serialize_some(self, _value: &T) -> SJsonResult where T: ?Sized + Serialize, { Err(key_must_be_a_string()) } - fn serialize_seq(self, _len: Option) -> Result { + fn serialize_seq(self, _len: Option) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_tuple(self, _len: usize) -> Result { + fn serialize_tuple(self, _len: usize) -> SJsonResult { Err(key_must_be_a_string()) } @@ -510,7 +514,7 @@ impl serde_ext::Serializer for MapKeySerializer { self, _name: &'static str, _len: usize, - ) -> Result { + ) -> SJsonResult { Err(key_must_be_a_string()) } @@ -520,15 +524,15 @@ impl serde_ext::Serializer for MapKeySerializer { _variant_index: u32, _variant: &'static str, _len: usize, - ) -> Result { + ) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_map(self, _len: Option) -> Result { + fn serialize_map(self, _len: Option) -> SJsonResult { Err(key_must_be_a_string()) } - fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { + fn serialize_struct(self, _name: &'static str, _len: usize) -> SJsonResult { Err(key_must_be_a_string()) } @@ -538,7 +542,7 @@ impl serde_ext::Serializer for MapKeySerializer { _variant_index: u32, _variant: &'static str, _len: usize, - ) -> Result { + ) -> SJsonResult { Err(key_must_be_a_string()) } } @@ -547,7 +551,7 @@ impl serde::ser::SerializeStruct for SerializeMap { type Ok = Value; type Error = Error; - fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<()> + fn serialize_field(&mut self, key: &'static str, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { @@ -555,7 +559,7 @@ impl serde::ser::SerializeStruct for SerializeMap { serde::ser::SerializeMap::serialize_value(self, value) } - fn end(self) -> Result { + fn end(self) -> SJsonResult { serde::ser::SerializeMap::end(self) } } @@ -564,7 +568,7 @@ impl serde::ser::SerializeStructVariant for SerializeStructVariant { type Ok = Value; type Error = Error; - fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<()> + fn serialize_field(&mut self, key: &'static str, value: &T) -> SJsonResult<()> where T: ?Sized + Serialize, { @@ -572,7 +576,7 @@ impl serde::ser::SerializeStructVariant for SerializeStructVariant { Ok(()) } - fn end(self) -> Result { + fn end(self) -> SJsonResult { let mut object = Object::with_capacity_and_hasher(1, ObjectHasher::default()); unsafe { object.insert_nocheck(self.name, Value::from(self.map)) }; Ok(Value::from(object)) @@ -582,6 +586,10 @@ impl serde::ser::SerializeStructVariant for SerializeStructVariant { #[cfg(test)] mod test { #![allow(clippy::ignored_unit_patterns)] + + use alloc::format; +use alloc::string::String; + use alloc::vec::Vec; use crate::serde::from_slice; #[cfg(not(target_arch = "wasm32"))] use crate::serde::{from_str, to_string}; @@ -650,7 +658,7 @@ mod test { let vec2 = crate::serde::to_vec(&o).expect("to_vec"); assert_eq!(vec, vec2); - println!("{}", serde_json::to_string_pretty(&o).expect("json")); + // println!("{}", serde_json::to_string_pretty(&o).expect("json")); let de: Obj = from_slice(&mut vec).expect("from_slice"); assert_eq!(o, de); } @@ -714,7 +722,7 @@ mod test { let mut vec = serde_json::to_vec(&obj).expect("to_vec"); let vec1 = vec.clone(); let vec2 = vec.clone(); - println!("{}", serde_json::to_string_pretty(&obj).expect("json")); + // println!("{}", serde_json::to_string_pretty(&obj).expect("json")); let de: Obj = from_slice(&mut vec).expect("from_slice"); prop_assert_eq!(&obj, &de); diff --git a/src/stage2.rs b/src/stage2.rs index d580a851..7052ca90 100644 --- a/src/stage2.rs +++ b/src/stage2.rs @@ -1,10 +1,12 @@ #![allow(dead_code)] + +use alloc::vec::Vec; use crate::charutils::is_not_structural_or_whitespace; #[allow(unused_imports)] use crate::macros::unlikely; use crate::safer_unchecked::GetSaferUnchecked; use crate::value::tape::Node; -use crate::{Deserializer, Error, ErrorType, InternalError, Result}; +use crate::{Deserializer, Error, ErrorType, InternalError, SJsonResult}; use value_trait::StaticNode; #[cfg_attr(not(feature = "no-inline"), inline)] @@ -112,7 +114,7 @@ impl<'de> Deserializer<'de> { stack: &mut Vec, max_depth: usize, res: &mut Vec>, - ) -> Result<()> { + ) -> SJsonResult<()> { res.clear(); res.reserve(structural_indexes.len()); // While a valid json can have at max len/2 (`[[[]]]`)elements that are relevant @@ -153,15 +155,15 @@ impl<'de> Deserializer<'de> { macro_rules! s2try { ($e:expr_2021) => { match $e { - ::std::result::Result::Ok(val) => val, - ::std::result::Result::Err(err) => { + ::core::result::Result::Ok(val) => val, + ::core::result::Result::Err(err) => { // We need to ensure that rust doesn't // try to free strings that we never // allocated unsafe { res.set_len(r_i); }; - return ::std::result::Result::Err(err); + return ::core::result::Result::Err(err); } } }; @@ -661,8 +663,8 @@ impl<'de> Deserializer<'de> { #[cfg(test)] mod test { - use crate::SIMDJSON_PADDING; - + use alloc::vec; + use crate::{SJsonResult, SIMDJSON_PADDING}; use super::*; #[test] @@ -731,7 +733,7 @@ mod test { } #[test] - fn parse_string() -> Result<()> { + fn parse_string() -> SJsonResult<()> { let mut input = Vec::from(&br#""{\"arg\":\"test\"}""#[..]); let mut input2 = input.clone(); input2.append(vec![0; SIMDJSON_PADDING * 2].as_mut()); diff --git a/src/stringparse.rs b/src/stringparse.rs index f35a9f5e..f062e032 100644 --- a/src/stringparse.rs +++ b/src/stringparse.rs @@ -1,4 +1,4 @@ -use std::ops::Range; +use core::ops::Range; use crate::charutils::{codepoint_to_utf8, hex_to_u32_nocheck}; use crate::error::ErrorType; diff --git a/src/value.rs b/src/value.rs index d87c7514..3864f99f 100644 --- a/src/value.rs +++ b/src/value.rs @@ -70,7 +70,7 @@ pub use self::owned::{ Value as OwnedValue, to_value as to_owned_value, to_value_with_buffers as to_owned_value_with_buffers, }; -use crate::{Buffers, Deserializer, Result}; +use crate::{Buffers, Deserializer, SJsonResult}; use halfbrown::HashMap; use tape::Node; pub use value_trait::*; @@ -91,7 +91,7 @@ pub type ObjectHasher = halfbrown::DefaultHashBuilder; /// # Errors /// /// Will return `Err` if `s` is invalid JSON. -pub fn deserialize<'de, Value, Key>(s: &'de mut [u8]) -> Result +pub fn deserialize<'de, Value, Key>(s: &'de mut [u8]) -> SJsonResult where Value: ValueBuilder<'de> + From> + From> + 'de, Key: Hash + Eq + From<&'de str>, @@ -116,7 +116,7 @@ where pub fn deserialize_with_buffers<'de, Value, Key>( s: &'de mut [u8], buffers: &mut Buffers, -) -> Result +) -> SJsonResult where Value: ValueBuilder<'de> + From> + From> + 'de, Key: Hash + Eq + From<&'de str>, diff --git a/src/value/borrowed.rs b/src/value/borrowed.rs index 0ca105ee..88948434 100644 --- a/src/value/borrowed.rs +++ b/src/value/borrowed.rs @@ -29,7 +29,7 @@ use alloc::string::ToString; use alloc::vec::Vec; use super::ObjectHasher; use crate::{Buffers, prelude::*}; -use crate::{Deserializer, Node, Result}; +use crate::{Deserializer, Node, SJsonResult}; use crate::{cow::Cow, safer_unchecked::GetSaferUnchecked as _}; use halfbrown::HashMap; use core::fmt; @@ -49,7 +49,7 @@ pub type Array<'value> = Vec>; /// # Errors /// /// Will return `Err` if `s` is invalid JSON. -pub fn to_value(s: &mut [u8]) -> Result> { +pub fn to_value(s: &mut [u8]) -> SJsonResult> { match Deserializer::from_slice(s) { Ok(de) => Ok(BorrowDeserializer::from_deserializer(de).parse()), Err(e) => Err(e), @@ -70,7 +70,7 @@ pub fn to_value(s: &mut [u8]) -> Result> { pub fn to_value_with_buffers<'value>( s: &'value mut [u8], buffers: &mut Buffers, -) -> Result> { +) -> SJsonResult> { match Deserializer::from_slice_with_buffers(s, buffers) { Ok(de) => Ok(BorrowDeserializer::from_deserializer(de).parse()), Err(e) => Err(e), diff --git a/src/value/borrowed/cmp.rs b/src/value/borrowed/cmp.rs index 9297661a..7bb39004 100644 --- a/src/value/borrowed/cmp.rs +++ b/src/value/borrowed/cmp.rs @@ -1,3 +1,4 @@ +use alloc::string::String; use super::Value; use crate::OwnedValue; use crate::prelude::*; @@ -170,14 +171,14 @@ where } } -impl<'v, K, T, S> PartialEq> for Value<'v> +impl<'v, K, T, S> PartialEq> for Value<'v> where - K: AsRef + std::hash::Hash + Eq, + K: AsRef + core::hash::Hash + Eq, Value<'v>: PartialEq, - S: std::hash::BuildHasher, + S: core::hash::BuildHasher, { #[cfg_attr(not(feature = "no-inline"), inline)] - fn eq(&self, other: &std::collections::HashMap) -> bool { + fn eq(&self, other: &hashbrown::HashMap) -> bool { self.as_object().is_some_and(|object| { object.len() == other.len() && other diff --git a/src/value/borrowed/from.rs b/src/value/borrowed/from.rs index 7a3da31a..7b6e0534 100644 --- a/src/value/borrowed/from.rs +++ b/src/value/borrowed/from.rs @@ -1,3 +1,6 @@ +use alloc::boxed::Box; +use alloc::string::String; +use alloc::vec::Vec; use super::{Object, Value}; use crate::OwnedValue; use crate::StaticNode; @@ -40,17 +43,17 @@ impl<'value> From<&'value str> for Value<'value> { } #[cfg(feature = "beef")] -impl<'value> From> for Value<'value> { +impl<'value> From> for Value<'value> { #[cfg_attr(not(feature = "no-inline"), inline)] - fn from(c: std::borrow::Cow<'value, str>) -> Self { + fn from(c: Cow<'value, str>) -> Self { Value::String(c.into()) } } #[cfg(not(feature = "beef"))] -impl<'value> From> for Value<'value> { +impl<'value> From> for Value<'value> { #[cfg_attr(not(feature = "no-inline"), inline)] - fn from(c: std::borrow::Cow<'value, str>) -> Self { + fn from(c: Cow<'value, str>) -> Self { Value::String(c) } } diff --git a/src/value/borrowed/serialize.rs b/src/value/borrowed/serialize.rs index f6b92e9c..c518b996 100644 --- a/src/value/borrowed/serialize.rs +++ b/src/value/borrowed/serialize.rs @@ -4,10 +4,12 @@ // // https://github.com/maciejhirsz/json-rust/blob/master/src/codegen.rs +use alloc::string::String; +use alloc::vec::Vec; +use core::fmt::Write; use super::{Object, Value}; use crate::prelude::*; -use std::io; -use std::io::Write; + use value_trait::generator::{ DumpGenerator, PrettyGenerator, PrettyWriterGenerator, WriterGenerator, }; diff --git a/src/value/lazy.rs b/src/value/lazy.rs index 67c8a797..60850724 100644 --- a/src/value/lazy.rs +++ b/src/value/lazy.rs @@ -22,9 +22,10 @@ //! assert_eq!(lazy.get("new").unwrap(), 42); //! ``` +use alloc::borrow::Cow; +use core::fmt; use crate::{borrowed, tape}; -use std::borrow::Cow; -use std::fmt; + /// Lazy implemntation of the array trait and associated functionality pub mod array; @@ -106,7 +107,7 @@ impl<'tape, 'input> Value<'_, 'tape, 'input> { return; } let mut dummy = Value::Tape(tape::Value::null()); - std::mem::swap(self, &mut dummy); + core::mem::swap(self, &mut dummy); let tape = unsafe { dummy.into_tape() }; let value = super::borrowed::BorrowSliceDeserializer::from_tape(tape.0).parse(); @@ -128,7 +129,7 @@ impl<'tape, 'input> Value<'_, 'tape, 'input> { } #[cfg(not(tarpaulin_include))] -impl fmt::Display for Value<'_, '_, '_> { +impl core::fmt::Display for Value<'_, '_, '_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match &self { Value::Tape(tape) => write!(f, "{tape:?}"), diff --git a/src/value/lazy/cmp.rs b/src/value/lazy/cmp.rs index 5e0efc0c..b122b392 100644 --- a/src/value/lazy/cmp.rs +++ b/src/value/lazy/cmp.rs @@ -1,4 +1,5 @@ -use std::borrow::Borrow; +use alloc::borrow::Borrow; +use alloc::string::String; use value_trait::{base::ValueAsScalar, derived::TypedScalarValue}; use super::Value; @@ -129,14 +130,14 @@ impl PartialEq for Value<'_, '_, '_> { } } -impl PartialEq> for Value<'_, '_, '_> +impl PartialEq> for Value<'_, '_, '_> where - K: Borrow + std::hash::Hash + Eq, + K: Borrow + core::hash::Hash + Eq, for<'b, 't, 'i> T: PartialEq>, - S: std::hash::BuildHasher, + S: core::hash::BuildHasher, { #[cfg_attr(not(feature = "no-inline"), inline)] - fn eq(&self, other: &std::collections::HashMap) -> bool { + fn eq(&self, other: &hashbrown::HashMap) -> bool { let Some(object) = self.as_object() else { return false; }; diff --git a/src/value/lazy/object.rs b/src/value/lazy/object.rs index 77da71e0..fe772617 100644 --- a/src/value/lazy/object.rs +++ b/src/value/lazy/object.rs @@ -1,10 +1,8 @@ -use std::{ - borrow::{Borrow, Cow}, - hash::Hash, -}; - +use alloc::borrow::Cow; +use core::borrow::Borrow; +use core::hash::Hash; use super::Value; -use crate::{borrowed, tape}; +use crate::{borrowed, tape, StdCow}; /// Wrapper around the tape that allows interacting with it via a `Object`-like API. pub enum Object<'borrow, 'tape, 'input> { @@ -18,7 +16,7 @@ pub enum Iter<'borrow, 'tape, 'input> { /// Tape variant Tape(tape::object::Iter<'tape, 'input>), /// Value variant - Value(halfbrown::Iter<'borrow, crate::cow::Cow<'input, str>, borrowed::Value<'input>>), + Value(halfbrown::Iter<'borrow, StdCow<'input, str>, borrowed::Value<'input>>), } /// Iterator over the keys of an object @@ -124,7 +122,7 @@ impl<'borrow> Iterator for Keys<'borrow, '_, '_> { fn next(&mut self) -> Option { match self { Keys::Tape(t) => t.next(), - Keys::Value(v) => v.next().map(std::convert::AsRef::as_ref), + Keys::Value(v) => v.next().map(AsRef::as_ref), } } } @@ -141,12 +139,14 @@ impl<'borrow, 'tape, 'input> Iterator for Values<'borrow, 'tape, 'input> { #[cfg(test)] mod test { + use alloc::vec; + use alloc::vec::Vec; use value_trait::base::ValueAsScalar; - use crate::to_tape; + use crate::{to_tape, SJsonResult}; #[test] - fn get_ints() -> crate::Result<()> { + fn get_ints() -> SJsonResult<()> { let mut input = br#"{"snot": 1, "badger":2, "cake":3, "cookie":4}"#.to_vec(); let t = to_tape(input.as_mut_slice())?; let v = t.as_value(); @@ -160,7 +160,7 @@ mod test { } #[test] - fn get_container() -> crate::Result<()> { + fn get_container() -> SJsonResult<()> { let mut input = br#"{"snot": 1, "badger":[2, 2.5], "cake":{"frosting": 3}, "cookie":4}"#.to_vec(); let t = to_tape(input.as_mut_slice())?; @@ -179,7 +179,7 @@ mod test { Ok(()) } #[test] - fn iter_ints() -> crate::Result<()> { + fn iter_ints() -> SJsonResult<()> { let mut input = br#"{"snot": 1, "badger":2, "cake":3, "cookie":4}"#.to_vec(); let t = to_tape(input.as_mut_slice())?; let v = t.as_value(); @@ -198,7 +198,7 @@ mod test { } #[test] - fn keys_ints() -> crate::Result<()> { + fn keys_ints() -> SJsonResult<()> { let mut input = br#"{"snot": 1, "badger":2, "cake":3, "cookie":4}"#.to_vec(); let t = to_tape(input.as_mut_slice())?; let v = t.as_value(); @@ -213,7 +213,7 @@ mod test { } #[test] - fn values_ints() -> crate::Result<()> { + fn values_ints() -> SJsonResult<()> { let mut input = br#"{"snot": 1, "badger":2, "cake":3, "cookie":4}"#.to_vec(); let t = to_tape(input.as_mut_slice())?; let v = t.as_value(); @@ -228,7 +228,7 @@ mod test { Ok(()) } #[test] - fn iter_container() -> crate::Result<()> { + fn iter_container() -> SJsonResult<()> { let mut input = br#"{"snot": 1, "badger":[2, 2.5], "cake":{"frosting": 3}, "cookie":4}"#.to_vec(); let t = to_tape(input.as_mut_slice())?; @@ -251,7 +251,7 @@ mod test { Ok(()) } #[test] - fn keys_container() -> crate::Result<()> { + fn keys_container() -> SJsonResult<()> { let mut input = br#"{"snot": 1, "badger":[2, 2.5], "cake":{"frosting": 3}, "cookie":4}"#.to_vec(); let t = to_tape(input.as_mut_slice())?; @@ -267,7 +267,7 @@ mod test { } #[test] - fn values_container() -> crate::Result<()> { + fn values_container() -> SJsonResult<()> { let mut input = br#"{"snot": 1, "badger":[2, 2.5], "cake":{"frosting": 3}, "cookie":4}"#.to_vec(); let t = to_tape(input.as_mut_slice())?; diff --git a/src/value/lazy/trait_impls.rs b/src/value/lazy/trait_impls.rs index 9016fd04..1f74de27 100644 --- a/src/value/lazy/trait_impls.rs +++ b/src/value/lazy/trait_impls.rs @@ -1,8 +1,11 @@ use core::{ - borrow::{Borrow}, + hash::Hash, }; - +use alloc::borrow::{ Cow, Borrow}; +use alloc::string::String; +use alloc::vec::Vec; +use core::fmt::Write; use value_trait::{ TryTypeError, ValueBuilder, ValueType, base::{ @@ -823,7 +826,7 @@ impl Writable for Value<'_, '_, '_> { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn write<'writer, W>(&self, w: &mut W) -> io::Result<()> + fn write<'writer, W>(&self, w: &mut W) -> core::fmt::Result where W: 'writer + Write, { @@ -834,7 +837,7 @@ impl Writable for Value<'_, '_, '_> { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn write_pp<'writer, W>(&self, w: &mut W) -> io::Result<()> + fn write_pp<'writer, W>(&self, w: &mut W) -> core::fmt::Result where W: 'writer + Write, { diff --git a/src/value/owned.rs b/src/value/owned.rs index 47d2194d..2674c212 100644 --- a/src/value/owned.rs +++ b/src/value/owned.rs @@ -23,12 +23,16 @@ mod cmp; mod from; mod serialize; +use alloc::boxed::Box; +use alloc::string::String; +use alloc::vec::Vec; +use core::fmt; +use core::ops::{Index, IndexMut}; use super::ObjectHasher; use crate::{Buffers, prelude::*}; -use crate::{Deserializer, Node, Result}; +use crate::{Deserializer, Node, SJsonResult}; use halfbrown::HashMap; -use std::fmt; -use std::ops::{Index, IndexMut}; + /// Representation of a JSON object pub type Object = HashMap; @@ -43,7 +47,7 @@ pub type Object = HashMap; /// # Errors /// /// Will return `Err` if `s` is invalid JSON. -pub fn to_value(s: &mut [u8]) -> Result { +pub fn to_value(s: &mut [u8]) -> SJsonResult { match Deserializer::from_slice(s) { Ok(de) => Ok(OwnedDeserializer::from_deserializer(de).parse()), Err(e) => Err(e), @@ -62,7 +66,7 @@ pub fn to_value(s: &mut [u8]) -> Result { /// # Errors /// /// Will return `Err` if `s` is invalid JSON. -pub fn to_value_with_buffers(s: &mut [u8], buffers: &mut Buffers) -> Result { +pub fn to_value_with_buffers(s: &mut [u8], buffers: &mut Buffers) -> SJsonResult { match Deserializer::from_slice_with_buffers(s, buffers) { Ok(de) => Ok(OwnedDeserializer::from_deserializer(de).parse()), Err(e) => Err(e), @@ -352,6 +356,8 @@ impl<'de> OwnedDeserializer<'de> { #[cfg(test)] mod test { #![allow(clippy::cognitive_complexity, clippy::ignored_unit_patterns)] + + use alloc::vec; use super::*; #[test] diff --git a/src/value/owned/cmp.rs b/src/value/owned/cmp.rs index 7a68cbeb..fedf7836 100644 --- a/src/value/owned/cmp.rs +++ b/src/value/owned/cmp.rs @@ -1,3 +1,5 @@ +use alloc::string::String; +use core::hash::{BuildHasher, Hash}; use super::Value; use crate::{BorrowedValue, prelude::*}; @@ -180,14 +182,14 @@ where self.as_array().is_some_and(|t| t.eq(other)) } } -impl PartialEq> for Value +impl PartialEq> for Value where - K: AsRef + std::hash::Hash + Eq, + K: AsRef + Hash + Eq, Value: PartialEq, - S: std::hash::BuildHasher, + S: BuildHasher, { #[cfg_attr(not(feature = "no-inline"), inline)] - fn eq(&self, other: &std::collections::HashMap) -> bool { + fn eq(&self, other: &hashbrown::HashMap) -> bool { self.as_object().is_some_and(|object| { object.len() == other.len() && other diff --git a/src/value/owned/from.rs b/src/value/owned/from.rs index 54b9368a..a23fa913 100644 --- a/src/value/owned/from.rs +++ b/src/value/owned/from.rs @@ -1,5 +1,9 @@ +use alloc::borrow::ToOwned; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; use super::{Object, Value}; -use crate::{BorrowedValue, StaticNode}; +use crate::{BorrowedValue, StaticNode, StdCow}; impl From> for Value { #[cfg_attr(not(feature = "no-inline"), inline)] @@ -38,9 +42,9 @@ impl From<&str> for Value { } } -impl<'value> From> for Value { +impl<'value> From> for Value { #[cfg_attr(not(feature = "no-inline"), inline)] - fn from(c: std::borrow::Cow<'value, str>) -> Self { + fn from(c: StdCow<'value, str>) -> Self { Self::String(c.to_string()) } } @@ -214,9 +218,9 @@ impl From for Value { } } -impl From> for Value { +impl From> for Value { #[cfg_attr(not(feature = "no-inline"), inline)] - fn from(v: std::collections::HashMap) -> Self { + fn from(v: hashbrown::HashMap) -> Self { Self::from(v.into_iter().collect::()) } } diff --git a/src/value/owned/serialize.rs b/src/value/owned/serialize.rs index 14193dbd..f4527d16 100644 --- a/src/value/owned/serialize.rs +++ b/src/value/owned/serialize.rs @@ -4,10 +4,11 @@ // // https://github.com/maciejhirsz/json-rust/blob/master/src/codegen.rs +use alloc::string::String; +use alloc::vec::Vec; +use core::fmt::Write; use super::{Object, Value}; use crate::prelude::*; -use std::io; -use std::io::Write; use value_trait::generator::{ DumpGenerator, PrettyGenerator, PrettyWriterGenerator, WriterGenerator, }; diff --git a/src/value/tape/cmp.rs b/src/value/tape/cmp.rs index 15872372..02247900 100644 --- a/src/value/tape/cmp.rs +++ b/src/value/tape/cmp.rs @@ -1,5 +1,5 @@ -use std::borrow::Borrow; - +use alloc::borrow::Borrow; +use alloc::string::String; use value_trait::{base::ValueAsScalar, derived::TypedScalarValue}; use super::Value; @@ -148,14 +148,14 @@ impl PartialEq for Value<'_, '_> { } } -impl<'input, K, T, S> PartialEq> for Value<'_, 'input> +impl<'input, K, T, S> PartialEq> for Value<'_, 'input> where - K: Borrow + std::hash::Hash + Eq, + K: Borrow + core::hash::Hash + Eq, for<'i> T: PartialEq>, - S: std::hash::BuildHasher, + S: core::hash::BuildHasher, { #[cfg_attr(not(feature = "no-inline"), inline)] - fn eq(&self, other: &std::collections::HashMap) -> bool { + fn eq(&self, other: &hashbrown::HashMap) -> bool { let Some(object) = self.as_object() else { return false; }; diff --git a/src/value/tape/object.rs b/src/value/tape/object.rs index 425f29a9..687a9837 100644 --- a/src/value/tape/object.rs +++ b/src/value/tape/object.rs @@ -1,5 +1,5 @@ -use std::{borrow::Borrow, hash::Hash}; - +use core::borrow::Borrow; +use core::hash::Hash; use super::Value; use crate::Node; @@ -119,6 +119,8 @@ impl<'tape, 'input> Iterator for Values<'tape, 'input> { #[cfg(test)] mod test { + use alloc::vec; + use alloc::vec::Vec; use value_trait::base::ValueAsScalar; use crate::to_tape; diff --git a/src/value/tape/trait_impls.rs b/src/value/tape/trait_impls.rs index 67f60997..d0b76387 100644 --- a/src/value/tape/trait_impls.rs +++ b/src/value/tape/trait_impls.rs @@ -1,7 +1,9 @@ -use std::{ +use alloc::string::String; +use alloc::vec::Vec; +use core::fmt::Write; +use core::{ borrow::Borrow, hash::Hash, - io::{self, Write}, }; use value_trait::{ @@ -16,7 +18,7 @@ use value_trait::{ }, }; -use crate::Node; +use crate::{Node, SJsonResult}; use super::{Array, Object, Value}; @@ -680,7 +682,7 @@ impl Writable for Value<'_, '_> { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn write<'writer, W>(&self, w: &mut W) -> io::Result<()> + fn write<'writer, W>(&self, w: &mut W) -> core::fmt::Result where W: 'writer + Write, { @@ -689,7 +691,7 @@ impl Writable for Value<'_, '_> { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn write_pp<'writer, W>(&self, w: &mut W) -> io::Result<()> + fn write_pp<'writer, W>(&self, w: &mut W) -> core::fmt::Result where W: 'writer + Write, { @@ -702,7 +704,7 @@ trait Generator: BaseGenerator { type T: Write; #[cfg_attr(not(feature = "no-inline"), inline)] - fn write_object(&mut self, object: &Object) -> io::Result<()> { + fn write_object(&mut self, object: &Object) -> core::fmt::Result { if object.is_empty() { self.write(b"{}") } else { @@ -734,7 +736,7 @@ trait Generator: BaseGenerator { } #[cfg_attr(not(feature = "no-inline"), inline)] - fn write_json(&mut self, json: &Value) -> io::Result<()> { + fn write_json(&mut self, json: &Value) -> core::fmt::Result { //FIXME no expect match *json.0.first().expect("invalid JSON") { Node::Static(StaticNode::Null) => self.write(b"null"),