From f5dccc96fdfdcadb177e64bb9357b901f6606e40 Mon Sep 17 00:00:00 2001 From: Boshen Date: Tue, 30 Apr 2024 23:11:22 +0800 Subject: [PATCH] refactor(coverage): avoid an `String::from_utf8` over head during serialization (#3145) --- crates/oxc_ast/src/serialize.rs | 12 +++++++++--- tasks/coverage/src/suite.rs | 4 ++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/oxc_ast/src/serialize.rs b/crates/oxc_ast/src/serialize.rs index fbbf1bccd..3d334f5cd 100644 --- a/crates/oxc_ast/src/serialize.rs +++ b/crates/oxc_ast/src/serialize.rs @@ -28,11 +28,17 @@ impl serde_json::ser::Formatter for EcmaFormatter { impl<'a> Program<'a> { /// # Panics pub fn to_json(&self) -> String { - let buf = std::vec::Vec::new(); - let mut ser = serde_json::Serializer::with_formatter(buf, crate::serialize::EcmaFormatter); - self.serialize(&mut ser).unwrap(); + let ser = self.serializer(); String::from_utf8(ser.into_inner()).unwrap() } + + /// # Panics + pub fn serializer(&self) -> serde_json::Serializer, EcmaFormatter> { + let buf = std::vec::Vec::new(); + let mut ser = serde_json::Serializer::with_formatter(buf, EcmaFormatter); + self.serialize(&mut ser).unwrap(); + ser + } } impl Serialize for RegExpFlags { diff --git a/tasks/coverage/src/suite.rs b/tasks/coverage/src/suite.rs index 445958664..f844bf907 100644 --- a/tasks/coverage/src/suite.rs +++ b/tasks/coverage/src/suite.rs @@ -322,8 +322,8 @@ pub trait Case: Sized + Sync + Send + UnwindSafe { return res; } - // Make sure serialization doesn't crash for ast and hir, also for code coverage. - let _json = parser_ret.program.to_json(); + // Make sure serialization doesn't crash; also for code coverage. + let _serializer = parser_ret.program.serializer(); let program = allocator.alloc(parser_ret.program); let semantic_ret = SemanticBuilder::new(source_text, source_type)