rust-embedded-community / serde-json-core

`serde-json` for `no_std` programs
Apache License 2.0
161 stars 59 forks source link

Serialize into externally allocated buffer #35

Closed MathiasKoch closed 3 years ago

MathiasKoch commented 4 years ago

It would be nice to have the option of passing in a byte slice to be used in serialization, rather than the internal buffer.

Usecase example:

pub fn as_json(&self, buf: &mut [u8]) -> Result<usize, ()> {
    let json = serde_json_core::to_vec::<consts::U1024, _>(&self).map_err(|_e| ())?;
    let len = json.len();
    buf[..len].copy_from_slice(&json);
    Ok(len)
}

Would be awesome to be able to:

pub fn as_json(&self, buf: &mut [u8]) -> Result<usize, ()> {
    let len = serde_json_core::to_slice(&self, &buf).map_err(|_e| ())?;
    Ok(len)
}

Where to_slice would just populate buf[0..len] with the serialized output.