-
Notifications
You must be signed in to change notification settings - Fork 290
Add ensure_ascii
option
#1689
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
Open
Viicos
wants to merge
2
commits into
main
Choose a base branch
from
ensure-ascii
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add ensure_ascii
option
#1689
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
use std::borrow::Cow; | ||
use std::fmt::Debug; | ||
use std::io::{self, Write}; | ||
|
||
use pyo3::exceptions::PyTypeError; | ||
use pyo3::prelude::*; | ||
|
@@ -9,7 +10,7 @@ use pyo3::{intern, PyTraverseError, PyVisit}; | |
|
||
use enum_dispatch::enum_dispatch; | ||
use serde::Serialize; | ||
use serde_json::ser::PrettyFormatter; | ||
use serde_json::ser::{Formatter, PrettyFormatter}; | ||
|
||
use crate::build_tools::py_schema_err; | ||
use crate::build_tools::py_schema_error_type; | ||
|
@@ -432,6 +433,87 @@ impl Serialize for PydanticSerializer<'_> { | |
} | ||
} | ||
|
||
struct EscapeNonAsciiFormatter; | ||
|
||
impl Formatter for EscapeNonAsciiFormatter { | ||
fn write_string_fragment<W: ?Sized + Write>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()> { | ||
let mut input = fragment; | ||
|
||
while let Some((idx, non_ascii_char)) = input.chars().enumerate().find(|(_, c)| !c.is_ascii()) { | ||
if idx > 0 { | ||
// write all ascii characters before the non-ascii one | ||
let ascii_run = &input[..idx]; | ||
writer.write_all(ascii_run.as_bytes()).unwrap(); | ||
} | ||
|
||
let codepoint = non_ascii_char as u32; | ||
if codepoint < 0xFFFF { | ||
// write basic codepoint as single escape | ||
write!(writer, "\\u{codepoint:04x}").unwrap(); | ||
} else { | ||
// encode extended plane character as utf16 pair | ||
for escape in non_ascii_char.encode_utf16(&mut [0; 2]) { | ||
write!(writer, "\\u{escape:04x}").unwrap(); | ||
} | ||
} | ||
|
||
input = &input[(idx + non_ascii_char.len_utf8())..]; | ||
} | ||
|
||
// write any ascii trailer | ||
writer.write_all(fragment.as_bytes())?; | ||
Ok(()) | ||
} | ||
} | ||
|
||
struct EscapeNonAsciiPrettyFormatter<'a> { | ||
pretty: PrettyFormatter<'a>, | ||
escape_non_ascii: EscapeNonAsciiFormatter, | ||
} | ||
|
||
impl<'a> EscapeNonAsciiPrettyFormatter<'a> { | ||
pub fn with_indent(indent: &'a [u8]) -> Self { | ||
Self { | ||
pretty: PrettyFormatter::with_indent(indent), | ||
escape_non_ascii: EscapeNonAsciiFormatter, | ||
} | ||
} | ||
} | ||
|
||
macro_rules! defer { | ||
($formatter:ident, $fun:ident) => { | ||
fn $fun<W>(&mut self, writer: &mut W) -> io::Result<()> | ||
where | ||
W: ?Sized + io::Write, | ||
{ | ||
self.$formatter.$fun(writer) | ||
} | ||
}; | ||
($formatter:ident, $fun:ident, $val:ty) => { | ||
fn $fun<W>(&mut self, writer: &mut W, val: $val) -> io::Result<()> | ||
where | ||
W: ?Sized + io::Write, | ||
{ | ||
self.$formatter.$fun(writer, val) | ||
} | ||
}; | ||
} | ||
|
||
#[allow(clippy::needless_lifetimes)] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Looks like a false positive from Clippy? There are already a bunch. |
||
impl Formatter for EscapeNonAsciiPrettyFormatter<'_> { | ||
defer!(escape_non_ascii, write_string_fragment, &str); | ||
defer!(pretty, begin_array); | ||
defer!(pretty, end_array); | ||
defer!(pretty, begin_array_value, bool); | ||
defer!(pretty, end_array_value); | ||
defer!(pretty, begin_object); | ||
defer!(pretty, end_object); | ||
defer!(pretty, begin_object_key, bool); | ||
defer!(pretty, end_object_key); | ||
defer!(pretty, begin_object_value); | ||
defer!(pretty, end_object_value); | ||
} | ||
|
||
#[allow(clippy::too_many_arguments)] | ||
pub(crate) fn to_json_bytes( | ||
value: &Bound<'_, PyAny>, | ||
|
@@ -440,25 +522,40 @@ pub(crate) fn to_json_bytes( | |
exclude: Option<&Bound<'_, PyAny>>, | ||
extra: &Extra, | ||
indent: Option<usize>, | ||
ensure_ascii: bool, | ||
expected_json_size: usize, | ||
) -> PyResult<Vec<u8>> { | ||
let serializer = PydanticSerializer::new(value, serializer, include, exclude, extra); | ||
|
||
let writer: Vec<u8> = Vec::with_capacity(expected_json_size); | ||
let bytes = match indent { | ||
Some(indent) => { | ||
|
||
let bytes = match (indent, ensure_ascii) { | ||
(Some(indent), true) => { | ||
let indent = vec![b' '; indent]; | ||
let formatter = EscapeNonAsciiPrettyFormatter::with_indent(&indent); | ||
let mut ser = PythonSerializer::with_formatter(writer, formatter); | ||
serializer.serialize(&mut ser).map_err(se_err_py_err)?; | ||
ser.into_inner() | ||
} | ||
(Some(indent), false) => { | ||
let indent = vec![b' '; indent]; | ||
let formatter = PrettyFormatter::with_indent(&indent); | ||
let mut ser = PythonSerializer::with_formatter(writer, formatter); | ||
serializer.serialize(&mut ser).map_err(se_err_py_err)?; | ||
ser.into_inner() | ||
} | ||
None => { | ||
(None, true) => { | ||
let mut ser = PythonSerializer::with_formatter(writer, EscapeNonAsciiFormatter); | ||
serializer.serialize(&mut ser).map_err(se_err_py_err)?; | ||
ser.into_inner() | ||
} | ||
(None, false) => { | ||
let mut ser = PythonSerializer::new(writer); | ||
serializer.serialize(&mut ser).map_err(se_err_py_err)?; | ||
ser.into_inner() | ||
} | ||
}; | ||
|
||
Ok(bytes) | ||
} | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.