From bb08a9842c1d5dbe7dcf4e58c027ba28472532e2 Mon Sep 17 00:00:00 2001 From: Kerollmops Date: Sun, 13 May 2018 15:49:52 +0200 Subject: [PATCH] feat: Use `BTreeMap` instead of a custom algo --- src/map.rs | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/src/map.rs b/src/map.rs index a68867eb7..7f2575b81 100644 --- a/src/map.rs +++ b/src/map.rs @@ -2,6 +2,8 @@ use bincode; use fst::{self, Automaton}; use serde::de::DeserializeOwned; use serde::ser::Serialize; +use std::collections::BTreeMap; +use std::collections::btree_map::Entry; use std::fs::File; use std::io::{Write, BufReader}; use std::ops::Range; @@ -109,7 +111,7 @@ impl Values { #[derive(Debug)] pub struct MapBuilder { - map: Vec<(String, u64)>, + map: BTreeMap, // This makes many memory indirections but it is only used // at index time, not kept for query time. values: Vec>, @@ -118,26 +120,23 @@ pub struct MapBuilder { impl MapBuilder { pub fn new() -> Self { Self { - map: Vec::new(), + map: BTreeMap::new(), values: Vec::new(), } } pub fn insert>(&mut self, key: S, value: T) { let key = key.into(); - match self.map.binary_search_by_key(&key.as_str(), |&(ref k, _)| k) { - Ok(index) => { - let (_, index) = self.map[index]; - let values = &mut self.values[index as usize]; - - values.push(value); - }, - Err(index) => { + match self.map.entry(key) { + Entry::Vacant(e) => { self.values.push(vec![value]); - let values_index = (self.values.len() - 1) as u64; - - let value = (key, values_index); - self.map.insert(index, value); + let index = (self.values.len() - 1) as u64; + e.insert(index); + }, + Entry::Occupied(e) => { + let index = *e.get(); + let values = &mut self.values[index as usize]; + values.push(value); }, } }