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

fix(sourcemap): fix pre-calculation of required segments for building JSON #4490

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions crates/oxc_sourcemap/src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ pub fn encode(sourcemap: &SourceMap) -> JSONSourceMap {
// Here using `serde_json::to_string` to serialization `names/source_contents/sources`.
// It will escape the string to avoid invalid JSON string.
pub fn encode_to_string(sourcemap: &SourceMap) -> Result<String> {
let mut contents = PreAllocatedString::new(
10 + sourcemap.names.len() * 2
+ sourcemap.sources.len() * 2
+ sourcemap.source_contents.as_ref().map_or(0, |sources| sources.len() * 2 + 1)
+ if let Some(x) = &sourcemap.x_google_ignore_list { x.len() * 2 } else { 0 },
);
let max_segments = 12
+ sourcemap.names.len() * 2
+ sourcemap.sources.len() * 2
+ sourcemap.source_contents.as_ref().map_or(0, |sources| sources.len() * 2 + 1)
+ sourcemap.x_google_ignore_list.as_ref().map_or(0, |x| x.len() * 2 + 1);
let mut contents = PreAllocatedString::new(max_segments);

contents.push("{\"version\":3,".into());
if let Some(file) = sourcemap.get_file() {
Expand All @@ -51,7 +51,7 @@ pub fn encode_to_string(sourcemap: &SourceMap) -> Result<String> {
contents.push("\"names\":[".into());
contents.push_list(sourcemap.names.iter().map(to_json_string))?;

contents.push(Cow::Borrowed("],\"sources\":["));
contents.push("],\"sources\":[".into());
contents.push_list(sourcemap.sources.iter().map(to_json_string))?;

// Quote `source_content` in parallel
Expand Down Expand Up @@ -79,6 +79,9 @@ pub fn encode_to_string(sourcemap: &SourceMap) -> Result<String> {
contents.push(serialize_sourcemap_mappings(sourcemap).into());
contents.push("\"}".into());

// Check we calculated number of segments required correctly
debug_assert!(contents.num_segments() <= max_segments);

Ok(contents.consume())
}

Expand Down Expand Up @@ -234,6 +237,10 @@ impl<'a> PreAllocatedString<'a> {
buf.extend(self.buf);
buf
}

fn num_segments(&self) -> usize {
self.buf.len()
}
}

#[test]
Expand Down
Loading