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

Escape DEL character as \u007f #939

Closed
wants to merge 1 commit into from
Closed

Escape DEL character as \u007f #939

wants to merge 1 commit into from

Conversation

sashka
Copy link

@sashka sashka commented Oct 17, 2022

No description provided.

Copy link
Member

@dtolnay dtolnay left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any more context you could provide on this change?

@sashka
Copy link
Author

sashka commented Oct 17, 2022

I'm working on a translator for huge machine readable XML to human readable (and editable) JSON and back again. A part of this XML is a hardware keyboard layout, so the user have to be able to see and edit unprintable characters. The most annoying is in my case is the DEL char, which is used pretty broadly.

With this patch I'm trying to fix an extremely specific use case (thousands of cases per file) without breaking anything to the rest of library users.

It'd be great to have a formatter with customizable escape table, but I'm not that good Rust developer so far.

@dtolnay
Copy link
Member

dtolnay commented Oct 17, 2022

You should plug in a formatter that escapes exactly what you want escaped. Something like the following. You can delegate the other Formatter methods to serde_json::ser::PrettyFormatter if you also want indentation.

use serde::Serialize;
use serde_json::json;
use serde_json::ser::CharEscape;
use std::io::{self, Write};

struct EscapedDelFormatter;

impl serde_json::ser::Formatter for EscapedDelFormatter {
    fn write_string_fragment<W>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()>
    where
        W: ?Sized + Write,
    {
        for (i, fragment) in fragment.split('\x7f').enumerate() {
            if i > 0 {
                self.write_char_escape(writer, CharEscape::AsciiControl(0x7f))?;
            }
            writer.write_all(fragment.as_bytes())?;
        }
        Ok(())
    }
}

fn main() {
    let value = json!({ "thing": "as\x7fdf" });
    let mut buf = Vec::new();
    let mut ser = serde_json::Serializer::with_formatter(&mut buf, EscapedDelFormatter);
    value.serialize(&mut ser).unwrap();
    buf.push(b'\n');
    io::stdout().write_all(&buf).unwrap();
}

@dtolnay dtolnay closed this Oct 17, 2022
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.

None yet

2 participants