Skip to content

Commit cbd1286

Browse files
authored
Merge pull request #519 from dtolnay/binarysearch
Convert SourceMap scan to binary search
2 parents fdc853a + fab4cb6 commit cbd1286

File tree

1 file changed

+27
-21
lines changed

1 file changed

+27
-21
lines changed

src/fallback.rs

Lines changed: 27 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ use alloc::collections::BTreeMap;
1111
use core::cell::RefCell;
1212
#[cfg(span_locations)]
1313
use core::cmp;
14+
#[cfg(all(span_locations, not(fuzzing)))]
15+
use core::cmp::Ordering;
1416
use core::fmt::{self, Debug, Display, Write};
1517
use core::mem::ManuallyDrop;
1618
#[cfg(span_locations)]
@@ -455,35 +457,39 @@ impl SourceMap {
455457
span
456458
}
457459

458-
fn filepath(&self, span: Span) -> String {
459-
for (i, file) in self.files.iter().enumerate() {
460-
if file.span_within(span) {
461-
return if i == 0 {
462-
"<unspecified>".to_owned()
463-
} else {
464-
format!("<parsed string {}>", i)
465-
};
460+
fn find(&self, span: Span) -> usize {
461+
match self.files.binary_search_by(|file| {
462+
if file.span.hi < span.lo {
463+
Ordering::Less
464+
} else if file.span.lo > span.hi {
465+
Ordering::Greater
466+
} else {
467+
assert!(file.span_within(span));
468+
Ordering::Equal
466469
}
470+
}) {
471+
Ok(i) => i,
472+
Err(_) => unreachable!("Invalid span with no related FileInfo!"),
467473
}
468-
unreachable!("Invalid span with no related FileInfo!");
469474
}
470475

471-
fn fileinfo(&self, span: Span) -> &FileInfo {
472-
for file in &self.files {
473-
if file.span_within(span) {
474-
return file;
475-
}
476+
fn filepath(&self, span: Span) -> String {
477+
let i = self.find(span);
478+
if i == 0 {
479+
"<unspecified>".to_owned()
480+
} else {
481+
format!("<parsed string {}>", i)
476482
}
477-
unreachable!("Invalid span with no related FileInfo!");
483+
}
484+
485+
fn fileinfo(&self, span: Span) -> &FileInfo {
486+
let i = self.find(span);
487+
&self.files[i]
478488
}
479489

480490
fn fileinfo_mut(&mut self, span: Span) -> &mut FileInfo {
481-
for file in &mut self.files {
482-
if file.span_within(span) {
483-
return file;
484-
}
485-
}
486-
unreachable!("Invalid span with no related FileInfo!");
491+
let i = self.find(span);
492+
&mut self.files[i]
487493
}
488494
}
489495

0 commit comments

Comments
 (0)