Skip to content

Commit

Permalink
Reduce amount of syscalls and memory allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
escritorio-gustavo committed May 22, 2024
1 parent 939041e commit a3ed6d8
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions ts-rs/src/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,24 +144,31 @@ pub(crate) fn export_to<T: TS + ?Sized + 'static, P: AsRef<Path>>(path: P) -> Re

file.seek(SeekFrom::Start(NOTE.len().try_into().unwrap()))?;

let mut buf = String::new();
file.read_to_string(&mut buf)?;
let content_len = usize::try_from(file.metadata()?.len()).unwrap() - NOTE.len();
let mut original_contents = String::with_capacity(content_len);
file.read_to_string(&mut original_contents)?;

let imports = imports
.lines()
.filter(|x| !buf.contains(x))
.filter(|x| !original_contents.contains(x))
.collect::<String>();

file.seek(SeekFrom::Start(NOTE.len().try_into().unwrap()))?;

file.write_all(imports.as_bytes())?;
let buffer_size =
imports.as_bytes().len() + decl.as_bytes().len() + content_len + 3;

let mut buffer = String::with_capacity(buffer_size);

buffer.push_str(&imports);
if !imports.is_empty() {
file.write_all(b"\n")?;
buffer.push('\n');
}
file.write_all(buf.as_bytes())?;
buffer.push_str(&original_contents);
buffer.push_str("\n\n");
buffer.push_str(decl);

file.write_all(b"\n\n")?;
file.write_all(decl.as_bytes())?;
file.write_all(buffer.as_bytes())?;

entry.insert(type_name);
}
Expand Down

0 comments on commit a3ed6d8

Please sign in to comment.