Skip to content

Commit a9111f5

Browse files
committed
Factor Mappings a bit better
1 parent e018c79 commit a9111f5

File tree

1 file changed

+15
-36
lines changed

1 file changed

+15
-36
lines changed

src/machine.rs

+15-36
Original file line numberDiff line numberDiff line change
@@ -320,57 +320,36 @@ impl Mappings {
320320
self.v.iter()
321321
}
322322

323+
fn binary_search(&self, addr: Size) -> Result<usize, usize> {
324+
self.v.binary_search_by(|map| {
325+
if map.range.start > addr {
326+
Ordering::Greater
327+
} else if map.range.end < addr {
328+
Ordering::Less
329+
} else {
330+
Ordering::Equal
331+
}
332+
})
333+
}
334+
323335
pub fn insert(&mut self, new: Mapping) {
324-
let idx = self
325-
.v
326-
.binary_search_by(|map| {
327-
if map.range.start > new.range.start {
328-
Ordering::Greater
329-
} else if map.range.end < new.range.start {
330-
Ordering::Less
331-
} else {
332-
Ordering::Equal
333-
}
334-
})
335-
.unwrap_err();
336+
let idx = self.binary_search(new.range.start).unwrap_err();
336337
self.v.insert(idx, new);
337338
}
338339

339340
pub fn remove(&mut self, addr: Size) -> Option<Mapping> {
340341
if !self.v.get(0)?.contains(addr) && !self.v.last()?.contains(addr) {
341342
return None;
342343
}
343-
let idx = self
344-
.v
345-
.binary_search_by(|map| {
346-
if map.range.start > addr {
347-
Ordering::Greater
348-
} else if map.range.end < addr {
349-
Ordering::Less
350-
} else {
351-
Ordering::Equal
352-
}
353-
})
354-
.ok()?;
344+
let idx = self.binary_search(addr).ok()?;
355345
Some(self.v.remove(idx))
356346
}
357347

358348
pub fn get(&self, addr: Size) -> Option<&Mapping> {
359349
if !self.v.get(0)?.contains(addr) && !self.v.last()?.contains(addr) {
360350
return None;
361351
}
362-
let idx = self
363-
.v
364-
.binary_search_by(|map| {
365-
if map.range.start > addr {
366-
Ordering::Greater
367-
} else if map.range.end < addr {
368-
Ordering::Less
369-
} else {
370-
Ordering::Equal
371-
}
372-
})
373-
.ok()?;
352+
let idx = self.binary_search(addr).ok()?;
374353
self.v.get(idx)
375354
}
376355
}

0 commit comments

Comments
 (0)