Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add some examples #1

Merged
merged 2 commits into from
Mar 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ repository = "https://github.com/kaleidawave/simple-json-parser"

[lib]
path = "lib.rs"

[lints.clippy]
pedantic = "deny"

6 changes: 3 additions & 3 deletions examples/package_json.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use simple_json_parser::parse;
use simple_json_parser::{parse, JSONParseError};

fn main() {
let content = r#"{
Expand Down Expand Up @@ -83,7 +83,7 @@ fn main() {

let result = parse(content, |keys, value| eprintln!("{keys:?} -> {value:?}"));

if let Err((idx, err)) = result {
eprintln!("{err:?} @ {idx}")
if let Err(JSONParseError { at, reason }) = result {
eprintln!("{reason:?} @ {at}");
}
}
64 changes: 64 additions & 0 deletions examples/to_object.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
use std::collections::HashMap;

use simple_json_parser::{parse, JSONKey, RootJSONValue};

fn main() -> Result<(), Box<dyn std::error::Error>> {
let path = std::env::args().nth(1).ok_or("Expected first argument")?;
let content = std::fs::read_to_string(path)?;

pub type Object = HashMap<String, Value>;

#[derive(Debug)]
pub enum Value {
Object(Object),
String(String),
Number(String),
Boolean(bool),
Null,
}

impl Value {
pub fn new_empty_object() -> Self {
Self::Object(HashMap::new())
}

pub fn set<'a>(&'a mut self, keys: &'a [JSONKey<'a>], value: RootJSONValue<'a>) {
if let Value::Object(ref mut obj) = self {
if let [last] = keys {
let name = match last {
JSONKey::Slice(s) => (*s).to_string(),
JSONKey::Index(i) => i.to_string(),
};
let value = match value {
RootJSONValue::String(s) => Value::String(s.to_string()),
RootJSONValue::Number(n) => Value::Number(n.to_string()),
RootJSONValue::True => Value::Boolean(true),
RootJSONValue::False => Value::Boolean(false),
RootJSONValue::Null => Value::Null,
};
let existing = obj.insert(name, value);
debug_assert!(existing.is_none());
} else if let [first, others @ ..] = keys {
let name = match first {
JSONKey::Slice(s) => (*s).to_string(),
JSONKey::Index(i) => i.to_string(),
};
obj.entry(name)
.or_insert_with(Value::new_empty_object)
.set(others, value);
} else {
unreachable!("empty keys")
}
} else {
unreachable!()
}
}
}

let mut root = Value::new_empty_object();

parse(&content, |keys, value| root.set(keys, value))?;

eprintln!("Object:\n{root:#?}");
Ok(())
}
76 changes: 76 additions & 0 deletions examples/to_object_unsafe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
//! Uses iterations rather than recursion to build a object map. Unfortunately at the cost of using `unsafe`

use std::collections::HashMap;

use simple_json_parser::{parse, JSONKey, RootJSONValue};

fn main() -> Result<(), Box<dyn std::error::Error>> {
let path = std::env::args().nth(1).ok_or("Expected first argument")?;
let content = std::fs::read_to_string(path)?;

pub type Object = HashMap<String, Value>;

#[derive(Debug)]
pub enum Value {
Object(Object),
String(String),
Number(String),
Boolean(bool),
Null,
}

impl Value {
pub fn new_empty_object() -> Self {
Self::Object(HashMap::new())
}
}

let mut root = Object::new();

let _res = parse(&content, |keys, value| {
let [path @ .., end] = keys else {
unreachable!("empty key change")
};
let pointer = &mut root;

let mut to_add_to: *mut Object = pointer;

for key in path {
let name = match key {
JSONKey::Slice(s) => (*s).to_string(),
JSONKey::Index(i) => i.to_string(),
};
if let Some(Value::Object(ref mut obj)) =
unsafe { (to_add_to.as_mut().unwrap()).get_mut(&name) }
{
to_add_to = obj;
} else {
let value = unsafe {
(to_add_to.as_mut().unwrap())
.entry(name)
.or_insert_with(Value::new_empty_object)
};
if let Value::Object(ref mut obj) = value {
to_add_to = obj;
}
}
}
let name = match end {
JSONKey::Slice(s) => (*s).to_string(),
JSONKey::Index(i) => i.to_string(),
};
let value = match value {
RootJSONValue::String(s) => Value::String(s.to_string()),
RootJSONValue::Number(n) => Value::Number(n.to_string()),
RootJSONValue::True => Value::Boolean(true),
RootJSONValue::False => Value::Boolean(false),
RootJSONValue::Null => Value::Null,
};
unsafe {
(to_add_to.as_mut().unwrap()).insert(name, value);
}
});

eprintln!("Object:\n{root:#?}");
Ok(())
}
Loading
Loading