id_prefix: add IdIndex method that looks up unambiguous key

resolve_prefix_with() is changed to return both key and values.
This commit is contained in:
Yuya Nishihara 2023-05-23 17:36:28 +09:00
parent e93ff5815c
commit 44927be7c9
2 changed files with 18 additions and 7 deletions

View file

@ -124,6 +124,7 @@ impl ChangeIdIndex for ChangeIdIndexImpl<'_> {
fn resolve_prefix(&self, prefix: &HexPrefix) -> PrefixResolution<Vec<CommitId>> {
self.pos_by_change
.resolve_prefix_with(prefix, |pos| self.index.entry_by_pos(*pos).commit_id())
.map(|(_, commit_ids)| commit_ids)
}
fn shortest_unique_prefix_len(&self, change_id: &ChangeId) -> usize {

View file

@ -163,22 +163,25 @@ where
/// Looks up entries with the given prefix, and collects values if matched
/// entries have unambiguous keys.
pub fn resolve_prefix_with<U>(
&self,
pub fn resolve_prefix_with<'a, B, U>(
&'a self,
prefix: &HexPrefix,
mut value_mapper: impl FnMut(&V) -> U,
) -> PrefixResolution<Vec<U>> {
mut value_mapper: impl FnMut(&'a V) -> U,
) -> PrefixResolution<(&'a K, B)>
where
B: FromIterator<U>,
{
if prefix.min_prefix_bytes().is_empty() {
// We consider an empty prefix ambiguous even if the index has a single entry.
return PrefixResolution::AmbiguousMatch;
}
let mut range = self.resolve_prefix_range(prefix).peekable();
if let Some((first_key, _)) = range.peek().copied() {
let maybe_entries: Option<Vec<_>> = range
let maybe_values: Option<B> = range
.map(|(k, v)| (k == first_key).then(|| value_mapper(v)))
.collect();
if let Some(entries) = maybe_entries {
PrefixResolution::SingleMatch(entries)
if let Some(values) = maybe_values {
PrefixResolution::SingleMatch((first_key, values))
} else {
PrefixResolution::AmbiguousMatch
}
@ -187,6 +190,12 @@ where
}
}
/// Looks up unambiguous key with the given prefix.
pub fn resolve_prefix_to_key<'a>(&'a self, prefix: &HexPrefix) -> PrefixResolution<&'a K> {
self.resolve_prefix_with(prefix, |_| ())
.map(|(key, ())| key)
}
/// Looks up entries with the given prefix, and collects values if matched
/// entries have unambiguous keys.
pub fn resolve_prefix_to_values(&self, prefix: &HexPrefix) -> PrefixResolution<Vec<V>>
@ -194,6 +203,7 @@ where
V: Clone,
{
self.resolve_prefix_with(prefix, |v: &V| v.clone())
.map(|(_, values)| values)
}
/// Iterates over entries with the given prefix.