feat(common): Add an API to create a SourceFile without allocation (#7029)

This commit is contained in:
Donny/강동윤 2023-03-07 23:47:21 +09:00 committed by GitHub
parent e93c79b479
commit 81495f5f21
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 6 deletions

View File

@ -202,7 +202,17 @@ impl SourceMap {
/// Creates a new source_file.
/// This does not ensure that only one SourceFile exists per file name.
pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc<SourceFile> {
pub fn new_source_file(&self, filename: FileName, mut src: String) -> Lrc<SourceFile> {
remove_bom(&mut src);
self.new_source_file_from(filename, Lrc::new(src))
}
/// Creates a new source_file.
/// This does not ensure that only one SourceFile exists per file name.
///
/// `src` should not have UTF8 BOM
pub fn new_source_file_from(&self, filename: FileName, src: Lrc<String>) -> Lrc<SourceFile> {
// The path is used to determine the directory for loading submodules and
// include files, so it must be before remapping.
// Note that filename may not be a valid path, eg it may be `<anon>` etc,
@ -224,7 +234,7 @@ impl SourceMap {
let start_pos = self.next_start_pos(src.len());
let source_file = Lrc::new(SourceFile::new(
let source_file = Lrc::new(SourceFile::new_from(
filename,
was_remapped,
unmapped_path,

View File

@ -869,6 +869,25 @@ impl SourceFile {
unmapped_path: FileName,
mut src: String,
start_pos: BytePos,
) -> SourceFile {
remove_bom(&mut src);
Self::new_from(
name,
name_was_remapped,
unmapped_path,
Lrc::new(src),
start_pos,
)
}
/// `src` should not have UTF8 BOM
pub fn new_from(
name: FileName,
name_was_remapped: bool,
unmapped_path: FileName,
src: Lrc<String>,
start_pos: BytePos,
) -> SourceFile {
debug_assert_ne!(
start_pos,
@ -876,8 +895,6 @@ impl SourceFile {
"BytePos::DUMMY is reserved and `SourceFile` should not use it"
);
remove_bom(&mut src);
let src_hash = {
let mut hasher: StableHasher = StableHasher::new();
hasher.write(src.as_bytes());
@ -898,7 +915,7 @@ impl SourceFile {
name_was_remapped,
unmapped_path: Some(unmapped_path),
crate_of_origin: 0,
src: Lrc::new(src),
src,
src_hash,
start_pos,
end_pos: Pos::from_usize(end_pos),
@ -988,7 +1005,7 @@ impl SourceFile {
}
/// Remove utf-8 BOM if any.
fn remove_bom(src: &mut String) {
pub(super) fn remove_bom(src: &mut String) {
if src.starts_with('\u{feff}') {
src.drain(..3);
}