Skip to content

Add Formatter::write_byte_array #1039

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

Merged
merged 7 commits into from
Jul 12, 2023
Merged

Conversation

dtolnay
Copy link
Member

@dtolnay dtolnay commented Jul 12, 2023

Example that writes bytes as base64 JSON strings:

// [dependencies]
// base64 = "0.21"
// serde = { version = "1", features = ["derive"] }
// serde_bytes = "0.11"
// serde_json = "1"

use serde::Serialize;
use std::io::{self, Write};

#[derive(Serialize)]
struct Struct {
    #[serde(with = "serde_bytes")]
    buf: Vec<u8>,
}

struct Base64Formatter;

impl serde_json::ser::Formatter for Base64Formatter {
    fn write_byte_array<W>(&mut self, writer: &mut W, value: &[u8]) -> io::Result<()>
    where
        W: ?Sized + io::Write,
    {
        writer.write_all(b"\"")?;
        let engine = &base64::engine::general_purpose::STANDARD_NO_PAD;
        let mut encoder = base64::write::EncoderWriter::new(writer, engine);
        encoder.write_all(value)?;
        let writer = encoder.finish()?;
        writer.write_all(b"\"")
    }
}

fn main() -> serde_json::Result<()> {
    let thing = Struct {
        buf: b".....\xed..\x1e\n.".to_vec(),
    };

    let out = io::stdout();
    let mut ser = serde_json::Serializer::with_formatter(out, Base64Formatter);
    thing.serialize(&mut ser)?;
    Ok(())
}
{"buf":"Li4uLi7tLi4eCi4"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

1 participant