Skip to content

Commit

Permalink
Merge pull request #58 from mina86/a
Browse files Browse the repository at this point in the history
Make library no_std and introduce std and unstable features
  • Loading branch information
chipshort authored Aug 4, 2023
2 parents a34f5f2 + 2b24610 commit 5629f42
Show file tree
Hide file tree
Showing 9 changed files with 91 additions and 81 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,17 @@ project adheres to [Semantic Versioning](http://semver.org/).

### Changed

- Introduce `std` (enabled by default) and `unstable` features ([#58]). They
enable corresponding serde’s features and if either is enabled, `Error`
implements `std::error::Error` trait. By itself, `serde-json-wasm` is now
`no_std`; it’s up to serde’s features whether the entire build is. **Please
note:** this potentially breaks `default-features = false` builds.

- Serialize / deserialize `u128`/`i128` types as numbers instead of strings
([#59]).<br/> **Please note:** this breaks deserialization of `u128`/`i128`
serialized with older versions of `serde-json-wasm`.

[#58]: https://github.com/CosmWasm/serde-json-wasm/pull/58
[#59]: https://github.com/CosmWasm/serde-json-wasm/pull/59

## [0.5.1] - 2023-04-11
Expand Down
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,13 @@ exclude = [
]

[dependencies]
serde = { version = "^1.0.80", default-features = false, features = ["alloc"] }
serde = { version = "^1.0.181", default-features = false, features = ["alloc"] }

[dev-dependencies]
serde_derive = "^1.0.80"
serde_json = "^1.0.99"

[features]
default = ["std"]
std = ["serde/std"]
unstable = ["serde/unstable"]
30 changes: 13 additions & 17 deletions src/de/errors.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
use alloc::string::{String, ToString};

use serde::de;
use std::{error, fmt};

/// Deserialization result
pub type Result<T> = core::result::Result<T, Error>;

/// This type represents all possible errors that can occur when deserializing JSON data
/// This type represents all possible errors that can occur when deserializing
/// JSON data
///
/// It implements [`std::error::Error`] trait so long as either `std` or
/// `unstable` features are enabled. `std` is enabled by default and disabling
/// it makes the crate `no_std`. `unstable` makes it necessary to build code
/// with nightly compiler.
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
Expand Down Expand Up @@ -72,27 +79,16 @@ pub enum Error {
Custom(String),
}

impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
None
}

fn description(&self) -> &str {
"(use display)"
}
}
impl de::StdError for Error {}

impl de::Error for Error {
fn custom<T>(msg: T) -> Self
where
T: fmt::Display,
{
fn custom<T: core::fmt::Display>(msg: T) -> Self {
Error::Custom(msg.to_string())
}
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"{}",
Expand Down
12 changes: 9 additions & 3 deletions src/de/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ mod map;
mod seq;
mod unescape;

use alloc::string::String;

pub use errors::{Error, Result};

use serde::de::{self, Visitor};

use self::enum_::{StructVariantAccess, UnitVariantAccess};
use self::map::MapAccess;
use self::seq::SeqAccess;
use std::str::from_utf8;

/// Deserializer will parse serde-json-wasm flavored JSON into a
/// serde-annotated struct
Expand Down Expand Up @@ -126,7 +127,7 @@ impl<'a> Deserializer<'a> {
)?))
} else {
Ok(StringLike::Borrowed(
from_utf8(&self.slice[start..end])
core::str::from_utf8(&self.slice[start..end])
.map_err(|_| Error::InvalidUnicodeCodePoint)?,
))
};
Expand Down Expand Up @@ -651,6 +652,11 @@ where
#[cfg(test)]
mod tests {
use super::from_str;

use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use serde_derive::{Deserialize, Serialize};

#[derive(Debug, Deserialize, PartialEq)]
Expand Down Expand Up @@ -1103,7 +1109,7 @@ mod tests {

#[test]
fn numbered_key_maps() {
use std::collections::BTreeMap;
use alloc::collections::BTreeMap;

// u8
let mut ranking: BTreeMap<u8, String> = BTreeMap::new();
Expand Down
4 changes: 3 additions & 1 deletion src/de/unescape.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use std::convert::TryFrom;
use alloc::string::String;
use alloc::vec::Vec;
use core::convert::TryFrom;

use super::errors::{Error, Result};

Expand Down
23 changes: 18 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,15 @@
#![deny(missing_docs)]
#![deny(rust_2018_compatibility)]
#![deny(rust_2018_idioms)]
// Note: Even though we declare the crate as `no_std`, by default `std` feature
// is enabled which enables serde’s `std` feature which makes our dependency
// non-`no_std`. This `no_std` declaration only makes sure that our code
// doesn’t depend on `std` directly (except for tests).
#![no_std]

extern crate alloc;
#[cfg(test)]
extern crate std;

pub mod de;
pub mod ser;
Expand All @@ -65,7 +74,11 @@ pub use self::ser::{to_string, to_vec};

#[cfg(test)]
mod test {
use std::collections::BTreeMap;
use alloc::borrow::ToOwned;
use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use super::*;
use serde_derive::{Deserialize, Serialize};
Expand Down Expand Up @@ -104,7 +117,7 @@ mod test {
fn can_serde() {
let min = Item {
model: Model::Comment,
title: "".to_string(),
title: String::new(),
content: None,
list: vec![],
published: false,
Expand All @@ -121,12 +134,12 @@ mod test {
},
title: "Nice message".to_string(),
content: Some("Happy \"blogging\" 👏\n\n\tCheers, I'm out\0\0\0".to_string()),
list: vec![0, 1, 2, 3, 42, 154841, std::u32::MAX],
list: vec![0, 1, 2, 3, 42, 154841, u32::MAX],
published: true,
comments: vec![CommentId(2), CommentId(700)],
stats: Stats {
views: std::u64::MAX,
score: std::i64::MIN,
views: u64::MAX,
score: i64::MIN,
},
balances,
};
Expand Down
6 changes: 2 additions & 4 deletions src/ser/map.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::fmt;

use serde::{ser, Serialize};

use crate::ser::{Error, Result, Serializer};
Expand Down Expand Up @@ -55,7 +53,7 @@ struct MapKeySerializer<'a> {
}

pub(crate) fn key_must_be_a_string() -> Error {
Error::Custom("JSON object key is required to be a string type.".to_string())
Error::Custom("JSON object key is required to be a string type.".into())
}

macro_rules! serialize_unsigned_key {
Expand Down Expand Up @@ -252,7 +250,7 @@ impl<'a> ser::Serializer for MapKeySerializer<'a> {

fn collect_str<T>(self, _value: &T) -> Result<()>
where
T: ?Sized + fmt::Display,
T: ?Sized + core::fmt::Display,
{
unreachable!()
}
Expand Down
Loading

0 comments on commit 5629f42

Please sign in to comment.