dtolnay / miniserde Goto Github PK
View Code? Open in Web Editor NEWData structure serialization library with several opposite design goals from Serde
License: Apache License 2.0
Data structure serialization library with several opposite design goals from Serde
License: Apache License 2.0
It looks like there is no implementation for Serialize / Deserialze of chars?
Is there a specific reason for that?
I believe that the implementation of ignore
in miniserde is unsafe. It casts a global static into a mutable reference which means there will be multiple references alive at once. At the same time it’s a zero sized type which can give out multiple addresses so I’m not sure how this works. I made a minimal repo example and miri complains:
use std::mem::transmute;
trait Magic {
fn do_magic(&mut self);
}
struct Vodoo;
impl Magic for Vodoo {
fn do_magic(&mut self) {
println!("interesting");
}
}
fn vodoo() -> &'static mut dyn Magic {
unsafe {
transmute::<_, &mut Vodoo>(&mut Vodoo)
}
}
fn main() {
vodoo().do_magic();
}
Produces this:
error: Undefined Behavior: type validation failed: encountered a dangling reference (use-after-free)
[--> src/main.rs:22:5
](https://play.rust-lang.org/#) |
22 | vodoo().do_magic();
| ^^^^^^^ type validation failed: encountered a dangling reference (use-after-free)
|
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
// serde_json = "=1.0.38"
// miniserde = "=0.1.9"
fn main() {
println!("{:?}", miniserde::json::from_str::<bool>(" true && false "));
println!("{:?}", serde_json::from_str::<bool>(" true && false "));
}
$ cargo +stable run
Ok(true)
Err(Error("trailing characters", line: 1, column: 7))
This behavior differs from serde_json
but I didn't see it documented so I assume it's not intended behavior.
(Very cool library by the way)
When publishing to crates.io, is it possible to somehow exclude the benchmarks directory, or even limit the larger benchmarks from being uploaded?
In fuchsia we'd like to experiment with using miniserde to reduce binary size compared to our json use-cases, but the size of the benchmarks is a blocker for vendoring into the project.
Currently on stable Rust it is not possible to rename derives when you import them. Also derives are required to be imported at the crate root. Together these mean that if anyone needs to use Serde's derives and Miniserde's derives in the same crate, those derives need to have different names.
Rust 1.30 brings the ability to rename derives when importing as well as importing derives at the submodule level. So Miniserde can expose Serialize
and Deserialize
derives and leave it up to the user to de-conflict by renaming in the case that they also want to use Serde derives.
I am trying to deserialize a json string which can have various format. For this basically, we need to deserialize string containing json, into Value
object. I followed docs, however looks like it is not possible to work with Value
object, like docs say it will - (In this case docs are referring to serde_json
) docs.
I would love to use miniserde
, however I am very not sure how to use this library and docs are not helpful much. My non-working snippet:
use miniserde::{json, Serialize, Deserialize};
fn main() {
let my_json_data = r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;
let deserialized : json::Value = json::from_str(my_json_data).unwrap();
println!("[+] Early quitting! {:#?}", deserialized["name"]);
The line at the bottom throws following error:
error[E0608]: cannot index into a value of type `miniserde::json::Value`
Hi, first of all, thanks for making/maintaining this library. It has been super helpful while learning rust.
Is there any way to mark a field optional?
For instance:
pub struct Something {
name: String,
data: Vec<String>,
}
Lets say the JSON can be either
{
"name" : "Someone",
"data": []
}
or
{
"name" : "Someone"
}
Is there any way to mark a field optional?
Thanks
Feature request: could the README.md please assert that the encoded structure of the same data will not change over time as the crate or dependent crates are updated? This would allow an application to write files, and be sure that those same files can be read later, under later versions of code.
Similarly, it would be great to guarantee that the storage is the same when used on different architectures, where, for example, the definition of usize might (hypothetically) vary.
My use case is actually simple enough that I'm inclined to directly write the encoding. But these things I've asked for are things that seem to have general value.
Hi there!
I'm currently using miniserde
for a project of mine which requires to be as lightweight as possible ; and so far I've been enjoying it!
But I have one little problem, and it is that PathBuf
is not supported for serialization. Now, due to the way Rust works, I cannot implement the serialization / deserialization traits myself given it's an external trait.
Would it be possible to add support for this data structure? Or is there a trivial workaround for this?
Thanks in advance for your help!
Hello, Is there a plan to support this?
With this example
use miniserde::MiniDeserialize;
#[derive(Debug, MiniDeserialize)]
struct Foo {
item: u64,
}
clippy gives the following diagnostic
$ cargo clippy
Checking minitest v0.1.0 (/Volumes/rust/minitest)
warning: transmute from a reference to a reference
--> src/lib.rs:3:17
|
3 | #[derive(Debug, MiniDeserialize)]
| ^^^^^^^^^^^^^^^
|
= note: #[warn(clippy::transmute_ptr_to_ptr)] on by default
= help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/v0.0.212/index.html#transmute_ptr_to_ptr
Finished dev [unoptimized + debuginfo] target(s) in 2.56s
Like these:
macro_rules! miniserialize_for_display {
($t:ty) => {
impl miniserde::Serialize for $t {
fn begin(&self) -> miniserde::ser::Fragment {
miniserde::ser::Fragment::Str(std::borrow::Cow::Owned(format!("{}",self)))
}
}
};
}
macro_rules! minideserialize_for_fromstr {
($t:ty) => {
impl miniserde::Deserialize for $t {
fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
make_place!(Place);
impl miniserde::de::Visitor for Place<$t> {
fn string(&mut self, s: &str) -> miniserde::Result<()> {
match std::str::FromStr::from_str(s) {
Ok(x) => {
self.out = Some(x);
Ok(())
},
Err(_) => Err(miniserde::Error),
}
}
}
Place::new(out)
}
}
};
}
Combined with strum it should provide easy miniserde for enums.
Would you be open to PRs adding support for more types? Here are some that would be useful in our project.
For some of them I already have hacked together some code. Would you be open to such PRs?
Would you consider a pull request that made ryu
and itoa
optional? This would make the top-level library optionally have zero dependencies, for a small hit on performance.
This library is otherwise perfect for my usecase!
Different: JSON only
Feature requests are practically guaranteed to be rejected.
That means, for example, there will be no CBOR (or something like that), which in turn means there will be no proper binary blob support. That probably limits usefullness of the library where it could be a good fit otherwise (e.g. something embedded).
As miniserde is intended to be locked to JSON, maybe it should be named after JSON instead, like minijson
?
I have a crate that has > 10_000 types that map a huge API and needs JSON serialization.
The compile time with serde
proper is pretty severe, and miniserde would be a great improvement.
While I wouldn't need any fancy json <-> Rust enum mapping, I would really need support for basic C-style enums represented as strings.
I could map them as regular strings, create From
/Into
impls and provide accessor methods that map the strings to respective enums, but that would create so much overhead and probably error-prone code that it is a no-go. (or write a custom (proc) macro on top, but that creates a few complications that imo are prohibitive).
Would support for simple string-enum mappings be something that could be considered?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.