Skip to content

Commit

Permalink
Merge pull request #1 from bearcove/mixed
Browse files Browse the repository at this point in the history
Add example for deserializing mixed arrays
  • Loading branch information
fasterthanlime authored Jul 29, 2024
2 parents ca4e615 + 116b02c commit 9e860b9
Show file tree
Hide file tree
Showing 8 changed files with 558 additions and 262 deletions.
12 changes: 3 additions & 9 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,6 @@ jobs:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Run tests
run: cargo run
- uses: actions/checkout@v4
- name: Run tests (including doctests)
run: cargo test
2 changes: 1 addition & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "merde_json"
version = "0.1.0"
version = "1.0.0"
edition = "2021"
authors = ["Amos Wenger <amos@bearcove.net>"]
description = "Serialize and deserialize JSON with jiter and declarative macros"
Expand Down
99 changes: 99 additions & 0 deletions examples/mixed.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
use std::borrow::Cow;

use jiter::JsonArray;
use merde_json::{
Fantome, JsonArrayExt, JsonDeserialize, JsonSerialize, JsonSerializer, JsonValue, JsonValueExt,
ToRustValue,
};

#[derive(Debug, PartialEq)]
struct MixedArray<'src, 'val> {
_boo: Fantome<'src, 'val>,

items: Vec<&'val JsonValue<'src>>,
}
merde_json::derive! {
impl(JsonSerialize, JsonDeserialize) for MixedArray { items }
}

#[derive(Debug, PartialEq)]
struct MixedArray2<'src, 'val> {
_boo: Fantome<'src, 'val>,

items: &'val JsonArray<'src>,
}
merde_json::derive! {
impl(JsonSerialize, JsonDeserialize) for MixedArray2 { items }
}

#[derive(Debug, PartialEq)]
struct Items<'src, 'val> {
_boo: Fantome<'src, 'val>,

number: u32,
string: Cow<'val, str>,
boolean: bool,
}

impl<'src, 'val> JsonDeserialize<'src, 'val> for Items<'src, 'val>
where
'src: 'val,
{
fn json_deserialize(
value: Option<&'val JsonValue<'src>>,
) -> Result<Self, merde_json::MerdeJsonError> {
let arr = value
.ok_or(merde_json::MerdeJsonError::MissingValue)?
.as_array()?;

Ok(Items {
_boo: Default::default(),

number: arr.must_get(0)?,
string: arr.must_get(1)?,
boolean: arr.must_get(2)?,
})
}
}

impl JsonSerialize for Items<'_, '_> {
fn json_serialize(&self, serializer: &mut JsonSerializer) {
serializer
.write_arr()
.elem(&self.number)
.elem(&self.string)
.elem(&self.boolean);
}
}

#[derive(Debug, PartialEq)]
struct MixedArray3<'src, 'val> {
_boo: Fantome<'src, 'val>,

items: Items<'src, 'val>,
}
merde_json::derive! {
impl(JsonSerialize, JsonDeserialize) for MixedArray3 { items }
}

fn main() {
let input = r#"
{
"items": [
42, "foo", true
]
}
"#;

let ma = merde_json::from_str(input).unwrap();
let ma: MixedArray = ma.to_rust_value().unwrap();
println!("{:?}", ma);

let ma = merde_json::from_str(input).unwrap();
let ma: MixedArray2 = ma.to_rust_value().unwrap();
println!("{:?}", ma);

let ma = merde_json::from_str(input).unwrap();
let ma: MixedArray3 = ma.to_rust_value().unwrap();
println!("{:?}", ma);
}
26 changes: 13 additions & 13 deletions examples/simple.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{borrow::Cow, marker::PhantomData};
use std::borrow::Cow;

use merde_json::{JsonSerialize, ToRustValue};
use merde_json::{Fantome, JsonSerialize, ToRustValue};

fn main() {
let input = r#"
Expand Down Expand Up @@ -35,13 +35,13 @@ fn main() {

#[allow(dead_code)]
#[derive(Debug, PartialEq, Eq)]
struct Address<'a> {
street: Cow<'a, str>,
city: Cow<'a, str>,
state: Cow<'a, str>,
zip: u16,
struct Address<'src, 'val> {
_boo: Fantome<'src, 'val>,

_phantom: PhantomData<&'a ()>,
street: Cow<'val, str>,
city: Cow<'val, str>,
state: Cow<'val, str>,
zip: u16,
}

merde_json::derive! {
Expand All @@ -55,12 +55,12 @@ merde_json::derive! {

#[allow(dead_code)]
#[derive(Debug, PartialEq, Eq)]
struct Person<'a> {
name: Cow<'a, str>,
age: u8,
address: Address<'a>,
struct Person<'src, 'val> {
_boo: Fantome<'src, 'val>,

_phantom: PhantomData<&'a ()>,
name: Cow<'val, str>,
age: u8,
address: Address<'src, 'val>,
}

merde_json::derive! {
Expand Down
61 changes: 61 additions & 0 deletions examples/to_static.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use std::borrow::Cow;

use merde_json::{Fantome, ToRustValue, ToStatic};

#[allow(dead_code)]
#[derive(Debug, PartialEq, Eq)]
struct Address<'src, 'val> {
_boo: Fantome<'src, 'val>,

street: Cow<'val, str>,
city: Cow<'val, str>,
state: Cow<'val, str>,
zip: u16,
}

merde_json::derive! {
impl (JsonDeserialize, ToStatic) for Address {
street,
city,
state,
zip
}
}

#[allow(dead_code)]
#[derive(Debug, PartialEq, Eq)]
struct Person<'src, 'val> {
_boo: Fantome<'src, 'val>,

name: Cow<'val, str>,
age: u8,
address: Address<'src, 'val>,
}

merde_json::derive! {
impl (JsonDeserialize, ToStatic) for Person { name, age, address }
}

fn get_person() -> Person<'static, 'static> {
let input = r#"
{
"name": "John Doe",
"age": 42,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": 12345
}
}
"#;

let person = merde_json::from_str(input).unwrap();
let person: Person = person.to_rust_value().unwrap();
person.to_static()
}

fn main() {
let person = get_person();
println!("{:?}", person);
}
15 changes: 15 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ pub enum MerdeJsonError {
/// We expected an object to have a certain property, but it was missing.
MissingProperty(&'static str),

/// We tried to access an array index that was out of bounds.
IndexOutOfBounds {
/// The index we tried to access.
index: usize,
/// The length of the array.
len: usize,
},

/// We encountered a property that we didn't expect.
UnknownProperty(String),

Expand Down Expand Up @@ -82,6 +90,13 @@ impl std::fmt::Display for MerdeJsonError {
MerdeJsonError::MissingProperty(prop) => {
write!(f, "Missing property: {}", prop)
}
MerdeJsonError::IndexOutOfBounds { index, len: length } => {
write!(
f,
"Index out of bounds: index {} is not valid for length {}",
index, length
)
}
MerdeJsonError::UnknownProperty(prop) => {
write!(f, "Unknown property: {}", prop)
}
Expand Down
Loading

0 comments on commit 9e860b9

Please sign in to comment.