pub trait IterateBounds {
fn into_bounds(self) -> (Option<Vec<u8>>, Option<Vec<u8>>);
}
impl IterateBounds for std::ops::RangeFull {
fn into_bounds(self) -> (Option<Vec<u8>>, Option<Vec<u8>>) {
(None, None)
}
}
impl<K: Into<Vec<u8>>> IterateBounds for std::ops::Range<K> {
fn into_bounds(self) -> (Option<Vec<u8>>, Option<Vec<u8>>) {
(Some(self.start.into()), Some(self.end.into()))
}
}
impl<K: Into<Vec<u8>>> IterateBounds for std::ops::RangeFrom<K> {
fn into_bounds(self) -> (Option<Vec<u8>>, Option<Vec<u8>>) {
(Some(self.start.into()), None)
}
}
impl<K: Into<Vec<u8>>> IterateBounds for std::ops::RangeTo<K> {
fn into_bounds(self) -> (Option<Vec<u8>>, Option<Vec<u8>>) {
(None, Some(self.end.into()))
}
}
#[derive(Clone, Copy)]
pub struct PrefixRange<K>(pub K);
impl<K: Into<Vec<u8>>> IterateBounds for PrefixRange<K> {
fn into_bounds(self) -> (Option<Vec<u8>>, Option<Vec<u8>>) {
let start = self.0.into();
if start.is_empty() {
(None, None)
} else {
let end = next_prefix(&start);
(Some(start), end)
}
}
}
fn next_prefix(prefix: &[u8]) -> Option<Vec<u8>> {
let ffs = prefix
.iter()
.rev()
.take_while(|&&byte| byte == u8::MAX)
.count();
let next = &prefix[..(prefix.len() - ffs)];
if next.is_empty() {
None
} else {
let mut next = next.to_vec();
*next.last_mut().unwrap() += 1;
Some(next)
}
}
#[test]
fn test_prefix_range() {
fn test(start: &[u8], end: Option<&[u8]>) {
let got = PrefixRange(start).into_bounds();
assert_eq!((Some(start), end), (got.0.as_deref(), got.1.as_deref()));
}
let empty: &[u8] = &[];
assert_eq!((None, None), PrefixRange(empty).into_bounds());
test(b"\xff", None);
test(b"\xff\xff\xff\xff", None);
test(b"a", Some(b"b"));
test(b"a\xff\xff\xff", Some(b"b"));
}