From 0d24811451dbd1c69ac42bbb5dedc6c24f92d92e Mon Sep 17 00:00:00 2001 From: Lewin Bormann Date: Sat, 15 Jun 2024 13:10:27 +0200 Subject: [PATCH] clippy refactoring --- examples/mcpe/src/main.rs | 8 ++-- src/asyncdb.rs | 2 +- src/block_builder.rs | 4 +- src/cache.rs | 22 ++++----- src/cmp.rs | 1 - src/db_iter.rs | 22 ++++----- src/disk_env.rs | 31 ++++++++----- src/error.rs | 15 ++----- src/filter.rs | 8 +--- src/key_types.rs | 25 +++-------- src/log.rs | 11 +++-- src/mem_env.rs | 86 ++++++++++++++++++----------------- src/memtable.rs | 13 +++--- src/merging_iter.rs | 50 ++++++++------------- src/options.rs | 29 +++++++----- src/skipmap.rs | 94 +++++++++++++++++---------------------- src/snapshot.rs | 2 +- src/table_builder.rs | 40 ++++++++--------- src/table_cache.rs | 10 ++--- src/table_reader.rs | 37 ++++++--------- src/version.rs | 71 +++++++++++++++-------------- 21 files changed, 263 insertions(+), 318 deletions(-) diff --git a/examples/mcpe/src/main.rs b/examples/mcpe/src/main.rs index 830a38a..e6895a1 100644 --- a/examples/mcpe/src/main.rs +++ b/examples/mcpe/src/main.rs @@ -5,8 +5,8 @@ use rusty_leveldb::{Compressor, CompressorList, Options, DB}; use std::rc::Rc; /// A zlib compressor that with zlib wrapper -/// -/// This is use for old world format +/// +/// This is use for old world format struct ZlibCompressor(u8); impl ZlibCompressor { @@ -67,10 +67,10 @@ pub fn mcpe_options(compression_level: u8) -> Options { // Mojang create a custom [compressor list](https://github.com/reedacartwright/rbedrock/blob/fb32a899da4e15c1aaa0d6de2b459e914e183516/src/leveldb-mcpe/include/leveldb/options.h#L123) // Sample config for compressor list can be find in [here](https://github.com/reedacartwright/rbedrock/blob/fb32a899da4e15c1aaa0d6de2b459e914e183516/src/leveldb-mcpe/mcpe_sample_setup.cpp#L24-L28) - // + // // Their compression id can be find in [here](https://github.com/reedacartwright/rbedrock/blob/fb32a899da4e15c1aaa0d6de2b459e914e183516/src/leveldb-mcpe/include/leveldb/zlib_compressor.h#L38) // and [here](https://github.com/reedacartwright/rbedrock/blob/fb32a899da4e15c1aaa0d6de2b459e914e183516/src/leveldb-mcpe/include/leveldb/zlib_compressor.h#L48) - // + // // Compression id will be use in [here](https://github.com/reedacartwright/rbedrock/blob/fb32a899da4e15c1aaa0d6de2b459e914e183516/src/leveldb-mcpe/table/format.cc#L125-L150) let mut list = CompressorList::new(); list.set_with_id(0, NoneCompressor::default()); diff --git a/src/asyncdb.rs b/src/asyncdb.rs index a28cf7a..ad02a85 100644 --- a/src/asyncdb.rs +++ b/src/asyncdb.rs @@ -234,7 +234,7 @@ impl AsyncDB { Request::GetAt { snapshot, key } => { let snapshot_id = snapshot.0; if let Some(snapshot) = snapshots.get(&snapshot_id) { - let ok = db.get_at(&snapshot, &key); + let ok = db.get_at(snapshot, &key); match ok { Err(e) => { message.resp_channel.send(Response::Error(e)).ok(); diff --git a/src/block_builder.rs b/src/block_builder.rs index 613940c..b5baca7 100644 --- a/src/block_builder.rs +++ b/src/block_builder.rs @@ -73,7 +73,7 @@ impl BlockBuilder { } } else { self.restarts.push(self.buffer.len() as u32); - self.last_key.resize(0, 0); + self.last_key.clear(); self.restart_counter = 0; } @@ -105,7 +105,7 @@ impl BlockBuilder { // 1. Append RESTARTS for r in self.restarts.iter() { self.buffer - .write_fixedint(*r as u32) + .write_fixedint(*r) .expect("write to buffer failed"); } diff --git a/src/cache.rs b/src/cache.rs index 8955f2f..a080b0f 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -77,7 +77,7 @@ impl LRUList { assert!(self.head.prev.is_some()); self.head.prev = last.prev; self.count -= 1; - (*last).data.take() + last.data.take() } else { None } @@ -214,7 +214,7 @@ impl Cache { pub fn get<'a>(&'a mut self, key: &CacheKey) -> Option<&'a T> { match self.map.get(key) { None => None, - Some(&(ref elem, ref lru_handle)) => { + Some((elem, lru_handle)) => { self.list.reinsert_front(*lru_handle); Some(elem) } @@ -347,19 +347,19 @@ mod tests { let handle2 = lru.insert(22); let handle3 = lru.insert(244); - assert_eq!(lru._testing_head_ref().map(|r| (*r)).unwrap(), 244); + assert_eq!(lru._testing_head_ref().copied().unwrap(), 244); lru.reinsert_front(handle1); - assert_eq!(lru._testing_head_ref().map(|r| (*r)).unwrap(), 56); + assert_eq!(lru._testing_head_ref().copied().unwrap(), 56); lru.reinsert_front(handle3); - assert_eq!(lru._testing_head_ref().map(|r| (*r)).unwrap(), 244); + assert_eq!(lru._testing_head_ref().copied().unwrap(), 244); lru.reinsert_front(handle2); - assert_eq!(lru._testing_head_ref().map(|r| (*r)).unwrap(), 22); + assert_eq!(lru._testing_head_ref().copied().unwrap(), 22); assert_eq!(lru.remove_last(), Some(56)); assert_eq!(lru.remove_last(), Some(244)); @@ -370,7 +370,7 @@ mod tests { fn test_blockcache_lru_reinsert_2() { let mut lru = LRUList::::new(); - let handles = vec![ + let handles = [ lru.insert(0), lru.insert(1), lru.insert(2), @@ -382,10 +382,10 @@ mod tests { lru.insert(8), ]; - for i in 0..9 { + (0..9).for_each(|i| { lru.reinsert_front(handles[i]); - assert_eq!(lru._testing_head_ref().map(|x| *x), Some(i)); - } + assert_eq!(lru._testing_head_ref().copied(), Some(i)); + }); } #[test] @@ -395,7 +395,7 @@ mod tests { let handle = lru.insert(3); lru.reinsert_front(handle); - assert_eq!(lru._testing_head_ref().map(|x| *x), Some(3)); + assert_eq!(lru._testing_head_ref().copied(), Some(3)); assert_eq!(lru.remove_last(), Some(3)); assert_eq!(lru.remove_last(), None); assert_eq!(lru.remove_last(), None); diff --git a/src/cmp.rs b/src/cmp.rs index a6f5c70..06ff4d7 100644 --- a/src/cmp.rs +++ b/src/cmp.rs @@ -180,7 +180,6 @@ impl Cmp for MemtableKeyCmp { mod tests { use super::*; use key_types::LookupKey; - use types; #[test] fn test_cmp_defaultcmp_shortest_sep() { diff --git a/src/db_iter.rs b/src/db_iter.rs index 006a3f3..88c9bcf 100644 --- a/src/db_iter.rs +++ b/src/db_iter.rs @@ -9,8 +9,6 @@ use std::cmp::Ordering; use std::mem; use std::rc::Rc; -use rand; - const READ_BYTES_PERIOD: isize = 1048576; /// DBIterator is an iterator over the contents of a database. @@ -464,18 +462,14 @@ mod tests { // xx5 should not be visible. db.put(b"xx5", b"223").unwrap(); - let expected: HashMap, Vec> = HashMap::from_iter( - vec![ - (b"xx1".to_vec(), b"111".to_vec()), - (b"xx4".to_vec(), b"222".to_vec()), - (b"aaa".to_vec(), b"val1".to_vec()), - (b"cab".to_vec(), b"val2".to_vec()), - ] - .into_iter(), - ); - let non_existing: HashSet> = HashSet::from_iter( - vec![b"gca".to_vec(), b"xx2".to_vec(), b"xx5".to_vec()].into_iter(), - ); + let expected: HashMap, Vec> = HashMap::from_iter(vec![ + (b"xx1".to_vec(), b"111".to_vec()), + (b"xx4".to_vec(), b"222".to_vec()), + (b"aaa".to_vec(), b"val1".to_vec()), + (b"cab".to_vec(), b"val2".to_vec()), + ]); + let non_existing: HashSet> = + HashSet::from_iter(vec![b"gca".to_vec(), b"xx2".to_vec(), b"xx5".to_vec()]); let mut iter = db.new_iter_at(ss.clone()).unwrap(); for (k, v) in LdbIteratorIter::wrap(&mut iter) { diff --git a/src/disk_env.rs b/src/disk_env.rs index f271bb0..b0fecfa 100644 --- a/src/disk_env.rs +++ b/src/disk_env.rs @@ -17,6 +17,12 @@ pub struct PosixDiskEnv { locks: Arc>>, } +impl Default for PosixDiskEnv { + fn default() -> Self { + Self::new() + } +} + impl PosixDiskEnv { pub fn new() -> PosixDiskEnv { PosixDiskEnv { @@ -44,19 +50,20 @@ impl Env for PosixDiskEnv { )) } fn open_random_access_file(&self, p: &Path) -> Result> { - Ok(fs::OpenOptions::new() + fs::OpenOptions::new() .read(true) .open(p) .map(|f| { let b: Box = Box::new(f); b }) - .map_err(|e| map_err_with_name("open (randomaccess)", p, e))?) + .map_err(|e| map_err_with_name("open (randomaccess)", p, e)) } fn open_writable_file(&self, p: &Path) -> Result> { Ok(Box::new( fs::OpenOptions::new() .create(true) + .truncate(true) .write(true) .append(false) .open(p) @@ -67,7 +74,6 @@ impl Env for PosixDiskEnv { Ok(Box::new( fs::OpenOptions::new() .create(true) - .write(true) .append(true) .open(p) .map_err(|e| map_err_with_name("open (append)", p, e))?, @@ -96,27 +102,28 @@ impl Env for PosixDiskEnv { } fn delete(&self, p: &Path) -> Result<()> { - Ok(fs::remove_file(p).map_err(|e| map_err_with_name("delete", p, e))?) + fs::remove_file(p).map_err(|e| map_err_with_name("delete", p, e)) } fn mkdir(&self, p: &Path) -> Result<()> { - Ok(fs::create_dir_all(p).map_err(|e| map_err_with_name("mkdir", p, e))?) + fs::create_dir_all(p).map_err(|e| map_err_with_name("mkdir", p, e)) } fn rmdir(&self, p: &Path) -> Result<()> { - Ok(fs::remove_dir_all(p).map_err(|e| map_err_with_name("rmdir", p, e))?) + fs::remove_dir_all(p).map_err(|e| map_err_with_name("rmdir", p, e)) } fn rename(&self, old: &Path, new: &Path) -> Result<()> { - Ok(fs::rename(old, new).map_err(|e| map_err_with_name("rename", old, e))?) + fs::rename(old, new).map_err(|e| map_err_with_name("rename", old, e)) } fn lock(&self, p: &Path) -> Result { let mut locks = self.locks.lock().unwrap(); - if locks.contains_key(&p.to_str().unwrap().to_string()) { - Err(Status::new(StatusCode::AlreadyExists, "Lock is held")) - } else { + if let std::collections::hash_map::Entry::Vacant(e) = + locks.entry(p.to_str().unwrap().to_string()) + { let f = fs::OpenOptions::new() .write(true) .create(true) + .truncate(true) .open(p) .map_err(|e| map_err_with_name("lock", p, e))?; @@ -136,11 +143,13 @@ impl Env for PosixDiskEnv { _ => (), }; - locks.insert(p.to_str().unwrap().to_string(), f); + e.insert(f); let lock = FileLock { id: p.to_str().unwrap().to_string(), }; Ok(lock) + } else { + Err(Status::new(StatusCode::AlreadyExists, "Lock is held")) } } fn unlock(&self, l: FileLock) -> Result<()> { diff --git a/src/error.rs b/src/error.rs index 0467d91..bf48b6b 100644 --- a/src/error.rs +++ b/src/error.rs @@ -5,11 +5,6 @@ use std::io; use std::result; use std::sync; -#[cfg(feature = "fs")] -use errno; - -use snap; - /// StatusCode describes various failure modes of database operations. #[derive(Clone, Debug, PartialEq)] #[allow(dead_code)] @@ -63,12 +58,10 @@ impl Error for Status { impl Status { pub fn new(code: StatusCode, msg: &str) -> Status { - let err; - if msg.is_empty() { - err = format!("{:?}", code) - } else { - err = format!("{:?}: {}", code, msg); - } + let err = match msg.is_empty() { + true => format!("{:?}", code), + false => format!("{:?}: {}", code, msg), + }; Status { code, err } } pub fn annotate>(self, msg: S) -> Status { diff --git a/src/filter.rs b/src/filter.rs index 3417e71..11ca4bf 100644 --- a/src/filter.rs +++ b/src/filter.rs @@ -104,11 +104,8 @@ impl BloomPolicy { assert!(limit - ix < 4); if limit - ix > 0 { - let mut i = 0; - - for b in data[ix..].iter() { + for (i, b) in data[ix..].iter().enumerate() { h = h.overflowing_add((*b as u32) << (8 * i)).0; - i += 1; } h = (h as u64 * m as u64) as u32; @@ -276,9 +273,8 @@ mod tests { intoffs.push(intdata.len()); intdata.extend_from_slice(ikey.internal_key()); }); - let filter = fpol.create_filter(&intdata, &intoffs); - filter + fpol.create_filter(&intdata, &intoffs) } #[test] diff --git a/src/key_types.rs b/src/key_types.rs index 9dfd732..483f731 100644 --- a/src/key_types.rs +++ b/src/key_types.rs @@ -111,11 +111,8 @@ pub fn build_memtable_key(key: &[u8], value: &[u8], t: ValueType, seq: SequenceN let keysize = key.len() + U64_SPACE; let valsize = value.len(); - let mut buf = Vec::new(); - buf.resize( - keysize + valsize + keysize.required_space() + valsize.required_space(), - 0, - ); + let mut buf = + vec![0_u8; keysize + valsize + keysize.required_space() + valsize.required_space()]; { let mut writer = buf.as_mut_slice(); @@ -135,7 +132,7 @@ pub fn build_memtable_key(key: &[u8], value: &[u8], t: ValueType, seq: SequenceN /// If the key only contains (keylen, key, tag), the vallen and val offset return values will be /// meaningless. pub fn parse_memtable_key(mkey: MemtableKey) -> (usize, usize, u64, usize, usize) { - let (keylen, mut i): (usize, usize) = VarInt::decode_var(&mkey).unwrap(); + let (keylen, mut i): (usize, usize) = VarInt::decode_var(mkey).unwrap(); let keyoff = i; i += keylen - 8; @@ -152,13 +149,9 @@ pub fn parse_memtable_key(mkey: MemtableKey) -> (usize, usize, u64, usize, usize } /// cmp_memtable_key efficiently compares two memtable keys by only parsing what's actually needed. -pub fn cmp_memtable_key<'a, 'b>( - ucmp: &dyn Cmp, - a: MemtableKey<'a>, - b: MemtableKey<'b>, -) -> Ordering { - let (alen, aoff): (usize, usize) = VarInt::decode_var(&a).unwrap(); - let (blen, boff): (usize, usize) = VarInt::decode_var(&b).unwrap(); +pub fn cmp_memtable_key(ucmp: &dyn Cmp, a: MemtableKey<'_>, b: MemtableKey<'_>) -> Ordering { + let (alen, aoff): (usize, usize) = VarInt::decode_var(a).unwrap(); + let (blen, boff): (usize, usize) = VarInt::decode_var(b).unwrap(); let userkey_a = &a[aoff..aoff + alen - 8]; let userkey_b = &b[boff..boff + blen - 8]; @@ -189,11 +182,7 @@ pub fn parse_internal_key(ikey: InternalKey) -> (ValueType, SequenceNumber, User /// cmp_internal_key efficiently compares keys in InternalKey format by only parsing the parts that /// are actually needed for a comparison. -pub fn cmp_internal_key<'a, 'b>( - ucmp: &dyn Cmp, - a: InternalKey<'a>, - b: InternalKey<'b>, -) -> Ordering { +pub fn cmp_internal_key(ucmp: &dyn Cmp, a: InternalKey<'_>, b: InternalKey<'_>) -> Ordering { match ucmp.cmp(&a[0..a.len() - 8], &b[0..b.len() - 8]) { Ordering::Less => Ordering::Less, Ordering::Greater => Ordering::Greater, diff --git a/src/log.rs b/src/log.rs index 55dd72c..f3388ce 100644 --- a/src/log.rs +++ b/src/log.rs @@ -222,8 +222,8 @@ mod tests { #[test] fn test_crc_sanity() { - assert_eq!(0x8a9136aa, crc::crc32(&[0_u8; 32])); - assert_eq!(0x62a8ab43, crc::crc32(&[0xff_u8; 32])); + assert_eq!(0x8a9136aa, crc::crc32([0_u8; 32])); + assert_eq!(0x62a8ab43, crc::crc32([0xff_u8; 32])); } #[test] @@ -251,8 +251,7 @@ mod tests { "and my third", ]; - let mut dst = Vec::new(); - dst.resize(1024, 0 as u8); + let mut dst = vec![0_u8; 1024]; { let mut lw = LogWriter::new(Cursor::new(dst.as_mut_slice())); @@ -278,7 +277,7 @@ mod tests { #[test] fn test_reader() { - let data = vec![ + let data = [ "abcdefghi".as_bytes().to_vec(), // fits one block of 17 "123456789012".as_bytes().to_vec(), // spans two blocks of 17 "0101010101010101010101".as_bytes().to_vec(), @@ -308,7 +307,7 @@ mod tests { loop { let r = lr.read(&mut dst); - if !r.is_ok() { + if r.is_err() { panic!("{}", r.unwrap_err()); } else if r.unwrap() == 0 { break; diff --git a/src/mem_env.rs b/src/mem_env.rs index fad51c7..8f867ba 100644 --- a/src/mem_env.rs +++ b/src/mem_env.rs @@ -25,7 +25,7 @@ impl RandomAccess for BufferBackedFile { } else { dst.len() }; - (&mut dst[0..to_read]).copy_from_slice(&self[off..off + to_read]); + dst[0..to_read].copy_from_slice(&self[off..off + to_read]); Ok(to_read) } } @@ -67,7 +67,7 @@ impl Read for MemFileReader { dst.len() }; - (&mut dst[0..to_read]).copy_from_slice(&buf[self.1..self.1 + to_read]); + dst[0..to_read].copy_from_slice(&buf[self.1..self.1 + to_read]); self.1 += to_read; Ok(to_read) } @@ -94,10 +94,10 @@ impl Write for MemFileWriter { let remaining = buf.len() - self.1; if src.len() <= remaining { // src fits into buffer. - (&mut buf[self.1..self.1 + src.len()]).copy_from_slice(src); + buf[self.1..self.1 + src.len()].copy_from_slice(src); } else { // src doesn't fit; first copy what fits, then append the rest/ - (&mut buf[self.1..self.1 + remaining]).copy_from_slice(&src[0..remaining]); + buf[self.1..self.1 + remaining].copy_from_slice(&src[0..remaining]); buf.extend_from_slice(&src[remaining..src.len()]); } } @@ -180,7 +180,7 @@ impl MemFS { let mut children = Vec::new(); for k in fs.keys() { if k.starts_with(&prefix) { - children.push(Path::new(k.strip_prefix(&prefix).unwrap_or(&k)).to_owned()); + children.push(Path::new(k.strip_prefix(&prefix).unwrap_or(k)).to_owned()); } } Ok(children) @@ -276,6 +276,12 @@ impl MemFS { /// performance will be better than what a disk environment delivers. pub struct MemEnv(MemFS); +impl Default for MemEnv { + fn default() -> Self { + Self::new() + } +} + impl MemEnv { pub fn new() -> MemEnv { MemEnv(MemFS::new()) @@ -414,26 +420,26 @@ mod tests { let path = Path::new("/a/b/hello.txt"); { - let mut w = fs.open_w(&path, false, false).unwrap(); + let mut w = fs.open_w(path, false, false).unwrap(); write!(w, "Hello").unwrap(); // Append. - let mut w2 = fs.open_w(&path, true, false).unwrap(); + let mut w2 = fs.open_w(path, true, false).unwrap(); write!(w2, "World").unwrap(); } { - let mut r = MemFileReader::new(fs.open(&path, false).unwrap(), 0); + let mut r = MemFileReader::new(fs.open(path, false).unwrap(), 0); let mut s = String::new(); assert_eq!(r.read_to_string(&mut s).unwrap(), 10); assert_eq!(s, "HelloWorld"); - let mut r2 = MemFileReader::new(fs.open(&path, false).unwrap(), 2); + let mut r2 = MemFileReader::new(fs.open(path, false).unwrap(), 2); s.clear(); assert_eq!(r2.read_to_string(&mut s).unwrap(), 8); assert_eq!(s, "lloWorld"); } - assert_eq!(fs.size_of_(&path).unwrap(), 10); - assert!(fs.exists_(&path).unwrap()); - assert!(!fs.exists_(&Path::new("/non/existing/path")).unwrap()); + assert_eq!(fs.size_of_(path).unwrap(), 10); + assert!(fs.exists_(path).unwrap()); + assert!(!fs.exists_(Path::new("/non/existing/path")).unwrap()); } #[test] @@ -442,28 +448,28 @@ mod tests { let path = Path::new("/a/b/hello.txt"); { - let mut w0 = fs.open_w(&path, false, true).unwrap(); + let mut w0 = fs.open_w(path, false, true).unwrap(); write!(w0, "Garbage").unwrap(); // Truncate. - let mut w = fs.open_w(&path, false, true).unwrap(); + let mut w = fs.open_w(path, false, true).unwrap(); write!(w, "Xyz").unwrap(); // Write to the beginning. - let mut w2 = fs.open_w(&path, false, false).unwrap(); + let mut w2 = fs.open_w(path, false, false).unwrap(); write!(w2, "OverwritingEverythingWithGarbage").unwrap(); // Overwrite the overwritten stuff. write!(w, "Xyz").unwrap(); assert!(w.flush().is_ok()); } { - let mut r = MemFileReader::new(fs.open(&path, false).unwrap(), 0); + let mut r = MemFileReader::new(fs.open(path, false).unwrap(), 0); let mut s = String::new(); assert_eq!(r.read_to_string(&mut s).unwrap(), 32); assert_eq!(s, "OveXyzitingEverythingWithGarbage"); } - assert!(fs.exists_(&path).unwrap()); - assert_eq!(fs.size_of_(&path).unwrap(), 32); - assert!(!fs.exists_(&Path::new("/non/existing/path")).unwrap()); + assert!(fs.exists_(path).unwrap()); + assert_eq!(fs.size_of_(path).unwrap(), 32); + assert!(!fs.exists_(Path::new("/non/existing/path")).unwrap()); } #[test] @@ -475,33 +481,33 @@ mod tests { // Make file/remove file. { - let mut w = fs.open_w(&path, false, false).unwrap(); + let mut w = fs.open_w(path, false, false).unwrap(); write!(w, "Hello").unwrap(); } - assert!(fs.exists_(&path).unwrap()); - assert_eq!(fs.size_of_(&path).unwrap(), 5); - fs.delete_(&path).unwrap(); - assert!(!fs.exists_(&path).unwrap()); - assert!(fs.delete_(&nonexist).is_err()); + assert!(fs.exists_(path).unwrap()); + assert_eq!(fs.size_of_(path).unwrap(), 5); + fs.delete_(path).unwrap(); + assert!(!fs.exists_(path).unwrap()); + assert!(fs.delete_(nonexist).is_err()); // rename_ file. { - let mut w = fs.open_w(&path, false, false).unwrap(); + let mut w = fs.open_w(path, false, false).unwrap(); write!(w, "Hello").unwrap(); } - assert!(fs.exists_(&path).unwrap()); - assert!(!fs.exists_(&newpath).unwrap()); - assert_eq!(fs.size_of_(&path).unwrap(), 5); - assert!(fs.size_of_(&newpath).is_err()); + assert!(fs.exists_(path).unwrap()); + assert!(!fs.exists_(newpath).unwrap()); + assert_eq!(fs.size_of_(path).unwrap(), 5); + assert!(fs.size_of_(newpath).is_err()); - fs.rename_(&path, &newpath).unwrap(); + fs.rename_(path, newpath).unwrap(); - assert!(!fs.exists_(&path).unwrap()); - assert!(fs.exists_(&newpath).unwrap()); - assert_eq!(fs.size_of_(&newpath).unwrap(), 5); - assert!(fs.size_of_(&path).is_err()); + assert!(!fs.exists_(path).unwrap()); + assert!(fs.exists_(newpath).unwrap()); + assert_eq!(fs.size_of_(newpath).unwrap(), 5); + assert!(fs.size_of_(path).is_err()); - assert!(fs.rename_(&nonexist, &path).is_err()); + assert!(fs.rename_(nonexist, path).is_err()); } fn s2p(x: &str) -> PathBuf { @@ -519,14 +525,14 @@ mod tests { ); for p in &[&path1, &path2, &path3] { - fs.open_w(*p, false, false).unwrap(); + fs.open_w(p, false, false).unwrap(); } - let children = fs.children_of(&Path::new("/a")).unwrap(); + let children = fs.children_of(Path::new("/a")).unwrap(); assert!( (children == vec![s2p("1.txt"), s2p("2.txt")]) || (children == vec![s2p("2.txt"), s2p("1.txt")]) ); - let children = fs.children_of(&Path::new("/a/")).unwrap(); + let children = fs.children_of(Path::new("/a/")).unwrap(); assert!( (children == vec![s2p("1.txt"), s2p("2.txt")]) || (children == vec![s2p("2.txt"), s2p("1.txt")]) @@ -565,7 +571,7 @@ mod tests { { let mut f = fs.open_w(p, true, true).unwrap(); - f.write("abcdef".as_bytes()).expect("write failed"); + f.write_all("abcdef".as_bytes()).expect("write failed"); } // Locking on new file. diff --git a/src/memtable.rs b/src/memtable.rs index e67bac3..bf73d80 100644 --- a/src/memtable.rs +++ b/src/memtable.rs @@ -36,7 +36,7 @@ impl MemTable { self.map.approx_memory() } - pub fn add<'a>(&mut self, seq: SequenceNumber, t: ValueType, key: UserKey<'a>, value: &[u8]) { + pub fn add(&mut self, seq: SequenceNumber, t: ValueType, key: UserKey<'_>, value: &[u8]) { self.map .insert(build_memtable_key(key, value, t, seq), Vec::new()) } @@ -120,7 +120,7 @@ impl LdbIterator for MemtableIterator { } if self.skipmapiter.current(key, val) { - let (keylen, keyoff, _, vallen, valoff) = parse_memtable_key(&key); + let (keylen, keyoff, _, vallen, valoff) = parse_memtable_key(key); val.clear(); val.extend_from_slice(&key[valoff..valoff + vallen]); // zero-allocation truncation. @@ -302,7 +302,7 @@ mod tests { let mt = get_memtable(); let mut iter = mt.iter(); - let expected = vec![ + let expected = [ "123".as_bytes(), /* i.e., the abc entry with * higher sequence number comes first */ "122".as_bytes(), @@ -311,11 +311,8 @@ mod tests { "125".as_bytes(), "126".as_bytes(), ]; - let mut i = 0; - - for (k, v) in LdbIteratorIter::wrap(&mut iter) { + for (i, (k, v)) in LdbIteratorIter::wrap(&mut iter).enumerate() { assert_eq!(v, expected[i]); - i += 1; } } @@ -378,7 +375,7 @@ mod tests { #[test] fn test_memtable_iterator_behavior() { let mut mt = MemTable::new(options::for_test().cmp); - let entries = vec![ + let entries = [ (115, "abc", "122"), (120, "abd", "123"), (121, "abe", "124"), diff --git a/src/merging_iter.rs b/src/merging_iter.rs index b9a88f4..b5dd9f2 100644 --- a/src/merging_iter.rs +++ b/src/merging_iter.rs @@ -103,18 +103,16 @@ impl MergingIter { } fn find(&mut self, direction: SL) { - if self.iters.len() == 0 { + if self.iters.is_empty() { // Iterator stays invalid. return; } - let ord; - - if direction == SL::Smallest { - ord = Ordering::Less; + let ord = if direction == SL::Smallest { + Ordering::Less } else { - ord = Ordering::Greater; - } + Ordering::Greater + }; let mut next_ix = 0; let (mut current, mut smallest, mut valscratch) = (vec![], vec![], vec![]); @@ -210,16 +208,12 @@ mod tests { let mut miter = MergingIter::new(Rc::new(Box::new(DefaultCmp)), vec![Box::new(iter)]); - loop { - if let Some((k, v)) = miter.next() { - if let Some((k2, v2)) = iter2.next() { - assert_eq!(k, k2); - assert_eq!(v, v2); - } else { - panic!("Expected element from iter2"); - } + while let Some((k, v)) = miter.next() { + if let Some((k2, v2)) = iter2.next() { + assert_eq!(k, k2); + assert_eq!(v, v2); } else { - break; + panic!("Expected element from iter2"); } } } @@ -235,16 +229,12 @@ mod tests { vec![Box::new(iter), Box::new(iter2)], ); - loop { - if let Some((k, v)) = miter.next() { - if let Some((k2, v2)) = miter.next() { - assert_eq!(k, k2); - assert_eq!(v, v2); - } else { - panic!("Odd number of elements"); - } + while let Some((k, v)) = miter.next() { + if let Some((k2, v2)) = miter.next() { + assert_eq!(k, k2); + assert_eq!(v, v2); } else { - break; + panic!("Odd number of elements"); } } } @@ -317,19 +307,17 @@ mod tests { fn test_merging_real() { let val = "def".as_bytes(); - let it1 = TestLdbIter::new(vec![(&b("aba"), val), (&b("abc"), val), (&b("abe"), val)]); - let it2 = TestLdbIter::new(vec![(&b("abb"), val), (&b("abd"), val)]); - let expected = vec![b("aba"), b("abb"), b("abc"), b("abd"), b("abe")]; + let it1 = TestLdbIter::new(vec![(b("aba"), val), (b("abc"), val), (b("abe"), val)]); + let it2 = TestLdbIter::new(vec![(b("abb"), val), (b("abd"), val)]); + let expected = [b("aba"), b("abb"), b("abc"), b("abd"), b("abe")]; let mut iter = MergingIter::new( Rc::new(Box::new(DefaultCmp)), vec![Box::new(it1), Box::new(it2)], ); - let mut i = 0; - for (k, _) in LdbIteratorIter::wrap(&mut iter) { + for (i, (k, _)) in LdbIteratorIter::wrap(&mut iter).enumerate() { assert_eq!(k, expected[i]); - i += 1; } } diff --git a/src/options.rs b/src/options.rs index 2502d46..7af2371 100644 --- a/src/options.rs +++ b/src/options.rs @@ -114,11 +114,14 @@ impl CompressorList { self.0[id as usize].is_some() } - pub fn get(&self, id: u8) -> Result<&Box> { - self.0[id as usize].as_ref().ok_or_else(|| Status { - code: StatusCode::NotSupported, - err: format!("invalid compression id `{}`", id), - }) + pub fn get(&self, id: u8) -> Result<&dyn Compressor> { + self.0[id as usize] + .as_ref() + .map(AsRef::as_ref) + .ok_or_else(|| Status { + code: StatusCode::NotSupported, + err: format!("invalid compression id `{}`", id), + }) } } @@ -134,14 +137,16 @@ impl Default for CompressorList { /// Returns Options that will cause a database to exist purely in-memory instead of being stored on /// disk. This is useful for testing or ephemeral databases. pub fn in_memory() -> Options { - let mut opt = Options::default(); - opt.env = Rc::new(Box::new(MemEnv::new())); - opt + Options { + env: Rc::new(Box::new(MemEnv::new())), + ..Options::default() + } } pub fn for_test() -> Options { - let mut o = Options::default(); - o.env = Rc::new(Box::new(MemEnv::new())); - o.log = Some(share(infolog::stderr())); - o + Options { + env: Rc::new(Box::new(MemEnv::new())), + log: Some(share(infolog::stderr())), + ..Options::default() + } } diff --git a/src/skipmap.rs b/src/skipmap.rs index 8d75b76..53bde43 100644 --- a/src/skipmap.rs +++ b/src/skipmap.rs @@ -77,6 +77,11 @@ impl SkipMap { pub fn len(&self) -> usize { self.map.borrow().len } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } pub fn approx_memory(&self) -> usize { self.map.borrow().approx_mem } @@ -111,7 +116,7 @@ impl InnerSkipMap { fn contains(&self, key: &[u8]) -> bool { if let Some(n) = self.get_greater_or_equal(key) { - n.key.starts_with(&key) + n.key.starts_with(key) } else { false } @@ -172,12 +177,9 @@ impl InnerSkipMap { if let Some(next) = (*current).skips[level] { let ord = self.cmp.cmp((*next).key.as_slice(), key); - match ord { - Ordering::Less => { - current = next; - continue; - } - _ => (), + if let Ordering::Less = ord { + current = next; + continue; } } } @@ -210,9 +212,9 @@ impl InnerSkipMap { let mut level = MAX_HEIGHT - 1; let mut current = self.head.as_mut() as *mut Node; // Set previous node for all levels to current node. - for i in 0..prevs.len() { + (0..prevs.len()).for_each(|i| { prevs[i] = Some(current); - } + }); // Find the node after which we want to insert the new node; this is the node with the key // immediately smaller than the key to be inserted. @@ -253,14 +255,14 @@ impl InnerSkipMap { }); let newp = new.as_mut() as *mut Node; - for i in 0..new_height { + (0..new_height).for_each(|i| { if let Some(prev) = prevs[i] { unsafe { new.skips[i] = (*prev).skips[i]; (*prev).skips[i] = Some(newp); } } - } + }); let added_mem = size_of::() + size_of::>() * new.skips.len() @@ -408,79 +410,63 @@ pub mod tests { #[test] fn test_contains() { let skm = make_skipmap(); - assert!(skm.contains(&"aby".as_bytes().to_vec())); - assert!(skm.contains(&"abc".as_bytes().to_vec())); - assert!(skm.contains(&"abz".as_bytes().to_vec())); - assert!(!skm.contains(&"ab{".as_bytes().to_vec())); - assert!(!skm.contains(&"123".as_bytes().to_vec())); - assert!(!skm.contains(&"aaa".as_bytes().to_vec())); - assert!(!skm.contains(&"456".as_bytes().to_vec())); + assert!(skm.contains(b"aby")); + assert!(skm.contains(b"abc")); + assert!(skm.contains(b"abz")); + assert!(!skm.contains(b"ab{")); + assert!(!skm.contains(b"123")); + assert!(!skm.contains(b"aaa")); + assert!(!skm.contains(b"456")); } #[test] fn test_find() { let skm = make_skipmap(); assert_eq!( - skm.map - .borrow() - .get_greater_or_equal(&"abf".as_bytes().to_vec()) - .unwrap() - .key, - "abf".as_bytes().to_vec() + skm.map.borrow().get_greater_or_equal(b"abf").unwrap().key, + b"abf" ); - assert!(skm - .map - .borrow() - .get_greater_or_equal(&"ab{".as_bytes().to_vec()) - .is_none()); + assert!(skm.map.borrow().get_greater_or_equal(b"ab{").is_none()); assert_eq!( - skm.map - .borrow() - .get_greater_or_equal(&"aaa".as_bytes().to_vec()) - .unwrap() - .key, - "aba".as_bytes().to_vec() + skm.map.borrow().get_greater_or_equal(b"aaa").unwrap().key, + b"aba" ); assert_eq!( skm.map .borrow() - .get_greater_or_equal(&"ab".as_bytes()) + .get_greater_or_equal(b"ab") .unwrap() .key .as_slice(), - "aba".as_bytes() + b"aba" ); assert_eq!( skm.map .borrow() - .get_greater_or_equal(&"abc".as_bytes()) + .get_greater_or_equal(b"abc") .unwrap() .key .as_slice(), - "abc".as_bytes() + b"abc" ); - assert!(skm - .map - .borrow() - .get_next_smaller(&"ab0".as_bytes()) - .is_none()); + assert!(skm.map.borrow().get_next_smaller(b"ab0").is_none()); assert_eq!( skm.map .borrow() - .get_next_smaller(&"abd".as_bytes()) + .get_next_smaller(b"abd") .unwrap() .key .as_slice(), - "abc".as_bytes() + b"abc" ); assert_eq!( skm.map .borrow() - .get_next_smaller(&"ab{".as_bytes()) + .get_next_smaller(b"ab{") .unwrap() .key .as_slice(), - "abz".as_bytes() + b"abz" ); } @@ -491,7 +477,7 @@ pub mod tests { let skm = SkipMap::new(cmp); let mut it = skm.iter(); - it.seek("abc".as_bytes()); + it.seek(b"abc"); assert!(!it.valid()); } @@ -546,19 +532,19 @@ pub mod tests { iter.next(); assert!(iter.valid()); assert_eq!(current_key_val(&iter).unwrap().0, "aba".as_bytes().to_vec()); - iter.seek(&"abz".as_bytes().to_vec()); + iter.seek(b"abz"); assert_eq!( current_key_val(&iter).unwrap(), ("abz".as_bytes().to_vec(), "def".as_bytes().to_vec()) ); // go back to beginning - iter.seek(&"aba".as_bytes().to_vec()); + iter.seek(b"aba"); assert_eq!( current_key_val(&iter).unwrap(), - ("aba".as_bytes().to_vec(), "def".as_bytes().to_vec()) + (b"aba".to_vec(), b"def".to_vec()) ); - iter.seek(&"".as_bytes().to_vec()); + iter.seek(b""); assert!(iter.valid()); iter.prev(); assert!(!iter.valid()); @@ -588,7 +574,7 @@ pub mod tests { assert!(iter.valid()); iter.prev(); assert!(!iter.valid()); - iter.seek(&"abc".as_bytes()); + iter.seek(b"abc"); iter.prev(); assert_eq!( current_key_val(&iter).unwrap(), diff --git a/src/snapshot.rs b/src/snapshot.rs index a5a6449..9f597ad 100644 --- a/src/snapshot.rs +++ b/src/snapshot.rs @@ -29,7 +29,7 @@ pub struct Snapshot { impl Snapshot { pub fn sequence(&self) -> SequenceNumber { - (*self.inner).seq + self.inner.seq } } diff --git a/src/table_builder.rs b/src/table_builder.rs index 534d92e..63447dd 100644 --- a/src/table_builder.rs +++ b/src/table_builder.rs @@ -62,12 +62,12 @@ impl Footer { let s1 = self.meta_index.encode_to(to); let s2 = self.index.encode_to(&mut to[s1..]); - for i in s1 + s2..FOOTER_LENGTH { + (s1 + s2..FOOTER_LENGTH).for_each(|i| { to[i] = 0; - } - for i in FOOTER_LENGTH..FULL_FOOTER_LENGTH { + }); + (FOOTER_LENGTH..FULL_FOOTER_LENGTH).for_each(|i| { to[i] = MAGIC_FOOTER_ENCODED[i - FOOTER_LENGTH]; - } + }); } } @@ -145,7 +145,7 @@ impl TableBuilder { } /// Add a key to the table. The key as to be lexically greater or equal to the last one added. - pub fn add<'a>(&mut self, key: InternalKey<'a>, val: &[u8]) -> Result<()> { + pub fn add(&mut self, key: InternalKey<'_>, val: &[u8]) -> Result<()> { assert!(self.data_block.is_some()); if !self.prev_block_last_key.is_empty() { @@ -170,11 +170,11 @@ impl TableBuilder { /// Writes an index entry for the current data_block where `next_key` is the first key of the /// next block. /// Calls write_block() for writing the block to disk. - fn write_data_block<'b>(&mut self, next_key: InternalKey<'b>) -> Result<()> { + fn write_data_block(&mut self, next_key: InternalKey<'_>) -> Result<()> { assert!(self.data_block.is_some()); let block = self.data_block.take().unwrap(); - let sep = self.opt.cmp.find_shortest_sep(&block.last_key(), next_key); + let sep = self.opt.cmp.find_shortest_sep(block.last_key(), next_key); self.prev_block_last_key = Vec::from(block.last_key()); let contents = block.finish(); @@ -183,7 +183,7 @@ impl TableBuilder { let handle = self.write_block(contents, (self.opt.compressor, compressor))?; - let mut handle_enc = [0 as u8; 16]; + let mut handle_enc = [0_u8; 16]; let enc_len = handle.encode_to(&mut handle_enc); self.index_block @@ -203,7 +203,7 @@ impl TableBuilder { fn write_block( &mut self, block: BlockContents, - compressor_id_pair: (u8, &Box), + compressor_id_pair: (u8, &dyn Compressor), ) -> Result { let (ctype, compressor) = compressor_id_pair; let data = compressor.encode(block)?; @@ -213,8 +213,8 @@ impl TableBuilder { digest.update(&data); digest.update(&[ctype; TABLE_BLOCK_COMPRESS_LEN]); - self.dst.write(&data)?; - self.dst.write(&[ctype; TABLE_BLOCK_COMPRESS_LEN])?; + self.dst.write_all(&data)?; + self.dst.write_all(&[ctype; TABLE_BLOCK_COMPRESS_LEN])?; self.dst.write_fixedint(mask_crc(digest.finalize()))?; let handle = BlockHandle::new(self.offset, data.len()); @@ -252,13 +252,10 @@ impl TableBuilder { let fblock_data = fblock.finish(); let fblock_handle = self.write_block( fblock_data, - ( - compressor::NoneCompressor::ID, - &(Box::new(compressor::NoneCompressor) as Box), - ), + (compressor::NoneCompressor::ID, &compressor::NoneCompressor), )?; - let mut handle_enc = [0 as u8; 16]; + let mut handle_enc = [0_u8; 16]; let enc_len = fblock_handle.encode_to(&mut handle_enc); meta_ix_block.add(filter_key.as_bytes(), &handle_enc[0..enc_len]); @@ -310,13 +307,13 @@ mod tests { opt.compressor = compressor::SnappyCompressor::ID; let mut b = TableBuilder::new_raw(opt, &mut d); - let data = vec![ + let data = [ ("abc", "def"), ("abe", "dee"), ("bcd", "asa"), ("dcc", "a00"), ]; - let data2 = vec![ + let data2 = [ ("abd", "def"), ("abf", "dee"), ("ccd", "asa"), @@ -324,9 +321,8 @@ mod tests { ]; for i in 0..data.len() { - b.add(&data[i].0.as_bytes(), &data[i].1.as_bytes()).unwrap(); - b.add(&data2[i].0.as_bytes(), &data2[i].1.as_bytes()) - .unwrap(); + b.add(data[i].0.as_bytes(), data[i].1.as_bytes()).unwrap(); + b.add(data2[i].0.as_bytes(), data2[i].1.as_bytes()).unwrap(); } let estimate = b.size_estimate(); @@ -347,7 +343,7 @@ mod tests { let mut b = TableBuilder::new_raw(opt, &mut d); // Test two equal consecutive keys - let data = vec![ + let data = [ ("abc", "def"), ("abc", "dee"), ("bcd", "asa"), diff --git a/src/table_cache.rs b/src/table_cache.rs index 9830b92..1ab1389 100644 --- a/src/table_cache.rs +++ b/src/table_cache.rs @@ -44,10 +44,10 @@ impl TableCache { } } - pub fn get<'a>( + pub fn get( &mut self, file_num: FileNum, - key: InternalKey<'a>, + key: InternalKey<'_>, ) -> Result, Vec)>> { let tbl = self.get_table(file_num)?; tbl.get(key) @@ -66,11 +66,11 @@ impl TableCache { fn open_table(&mut self, file_num: FileNum) -> Result { let name = table_file_name(&self.dbname, file_num); let path = Path::new(&name); - let file_size = self.opts.env.size_of(&path)?; + let file_size = self.opts.env.size_of(path)?; if file_size == 0 { return err(StatusCode::InvalidData, "file is empty"); } - let file = Rc::new(self.opts.env.open_random_access_file(&path)?); + let file = Rc::new(self.opts.env.open_random_access_file(path)?); // No SSTable file name compatibility. let table = Table::new(self.opts.clone(), file, file_size)?; self.cache.insert(&filenum_to_key(file_num), table.clone()); @@ -119,7 +119,7 @@ mod tests { let w = o.env.open_writable_file(p).unwrap(); let mut b = TableBuilder::new_raw(o, w); - let data = vec![ + let data = [ ("abc", "def"), ("abd", "dee"), ("bcd", "asa"), diff --git a/src/table_reader.rs b/src/table_reader.rs index ad34633..b021f28 100644 --- a/src/table_reader.rs +++ b/src/table_reader.rs @@ -182,7 +182,7 @@ impl Table { /// This is done this way because some key types, like internal keys, will not result in an /// exact match; it depends on other comparators than the one that the table reader knows /// whether a match is acceptable. - pub fn get<'a>(&self, key: InternalKey<'a>) -> Result, Vec)>> { + pub fn get(&self, key: InternalKey<'_>) -> Result, Vec)>> { let mut index_iter = self.indexblock.iter(); index_iter.seek(key); @@ -431,7 +431,7 @@ mod tests { opt.block_size = 32; opt.filter_policy = Rc::new(Box::new(BloomPolicy::new(4))); - let mut i = 1 as u64; + let mut i = 1_u64; let data: Vec<(Vec, &'static str)> = build_data() .into_iter() .map(|(k, v)| { @@ -444,7 +444,7 @@ mod tests { // Uses InternalKeyCmp let mut b = TableBuilder::new(opt, &mut d); - for &(ref k, ref v) in data.iter() { + for (k, v) in data.iter() { b.add(k.as_slice(), v.as_bytes()).unwrap(); } @@ -468,11 +468,9 @@ mod tests { let table = Table::new_raw(opt, wrap_buffer(src), size).unwrap(); let mut iter = table.iter(); - let expected_offsets = vec![0, 0, 0, 44, 44, 44, 89]; - let mut i = 0; - for (k, _) in LdbIteratorIter::wrap(&mut iter) { + let expected_offsets = [0, 0, 0, 44, 44, 44, 89]; + for (i, (k, _)) in LdbIteratorIter::wrap(&mut iter).enumerate() { assert_eq!(expected_offsets[i], table.approx_offset_of(&k)); - i += 1; } // Key-past-last returns offset of metaindex block. @@ -559,14 +557,9 @@ mod tests { assert!(table.filters.is_some()); let filter_reader = table.filters.clone().unwrap(); let mut iter = table.iter(); - - loop { - if let Some((k, _)) = iter.next() { - assert!(filter_reader.key_may_match(iter.current_block_off, &k)); - assert!(!filter_reader.key_may_match(iter.current_block_off, b"somerandomkey")); - } else { - break; - } + while let Some((k, _)) = iter.next() { + assert!(filter_reader.key_may_match(iter.current_block_off, &k)); + assert!(!filter_reader.key_may_match(iter.current_block_off, b"somerandomkey")); } } @@ -726,16 +719,12 @@ mod tests { let mut iter = table.iter(); - loop { - if let Some((k, _)) = iter.next() { - let lk = LookupKey::new(&k, 123); - let userkey = lk.user_key(); + while let Some((k, _)) = iter.next() { + let lk = LookupKey::new(&k, 123); + let userkey = lk.user_key(); - assert!(filter_reader.key_may_match(iter.current_block_off, userkey)); - assert!(!filter_reader.key_may_match(iter.current_block_off, b"somerandomkey")); - } else { - break; - } + assert!(filter_reader.key_may_match(iter.current_block_off, userkey)); + assert!(!filter_reader.key_may_match(iter.current_block_off, b"somerandomkey")); } } diff --git a/src/version.rs b/src/version.rs index f076019..bd80955 100644 --- a/src/version.rs +++ b/src/version.rs @@ -57,7 +57,7 @@ impl Version { /// get returns the value for the specified key using the persistent tables contained in this /// Version. #[allow(unused_assignments)] - pub fn get<'a>(&self, key: InternalKey<'a>) -> Result, GetStats)>> { + pub fn get(&self, key: InternalKey<'_>) -> Result, GetStats)>> { let levels = self.get_overlapping(key); let ikey = key; let ukey = parse_internal_key(ikey).2; @@ -67,13 +67,12 @@ impl Version { level: 0, }; - for level in 0..levels.len() { - let files = &levels[level]; + for (level, files) in levels.iter().enumerate() { let mut last_read = None; let mut last_read_level: usize = 0; for f in files { if last_read.is_some() && stats.file.is_none() { - stats.file = last_read.clone(); + stats.file.clone_from(&last_read); stats.level = last_read_level; } last_read_level = level; @@ -101,7 +100,7 @@ impl Version { } /// get_overlapping returns the files overlapping key in each level. - fn get_overlapping<'a>(&self, key: InternalKey<'a>) -> [Vec; NUM_LEVELS] { + fn get_overlapping(&self, key: InternalKey<'_>) -> [Vec; NUM_LEVELS] { let mut levels: [Vec; NUM_LEVELS] = Default::default(); let ikey = key; let ukey = parse_internal_key(key).2; @@ -124,7 +123,7 @@ impl Version { levels[0].sort_by(|a, b| b.borrow().num.cmp(&a.borrow().num)); let icmp = InternalKeyCmp(self.user_cmp.clone()); - for level in 1..NUM_LEVELS { + (1..NUM_LEVELS).for_each(|level| { let files = &self.files[level]; if let Some(ix) = find_file(&icmp, files, ikey) { let f = files[ix].borrow(); @@ -133,7 +132,7 @@ impl Version { levels[level].push(files[ix].clone()); } } - } + }); levels } @@ -162,7 +161,7 @@ impl Version { acc } - pub fn pick_memtable_output_level<'a, 'b>(&self, min: UserKey<'a>, max: UserKey<'b>) -> usize { + pub fn pick_memtable_output_level(&self, min: UserKey<'_>, max: UserKey<'_>) -> usize { let mut level = 0; if !self.overlap_in_level(0, min, max) { // Go to next level as long as there is no overlap in that level and a limited overlap @@ -278,11 +277,11 @@ impl Version { } /// overlapping_inputs returns all files that may contain keys between begin and end. - pub fn overlapping_inputs<'a, 'b>( + pub fn overlapping_inputs( &self, level: usize, - begin: InternalKey<'a>, - end: InternalKey<'b>, + begin: InternalKey<'_>, + end: InternalKey<'_>, ) -> Vec { assert!(level < NUM_LEVELS); let (mut ubegin, mut uend) = ( @@ -498,14 +497,14 @@ pub fn total_size<'a, I: Iterator>(files: I) -> usize } /// key_is_after_file returns true if the given user key is larger than the largest key in f. -fn key_is_after_file<'a>(cmp: &InternalKeyCmp, key: UserKey<'a>, f: &FileMetaHandle) -> bool { +fn key_is_after_file(cmp: &InternalKeyCmp, key: UserKey<'_>, f: &FileMetaHandle) -> bool { let f = f.borrow(); let ulargest = parse_internal_key(&f.largest).2; !key.is_empty() && cmp.cmp_inner(key, ulargest) == Ordering::Greater } /// key_is_before_file returns true if the given user key is larger than the largest key in f. -fn key_is_before_file<'a>(cmp: &InternalKeyCmp, key: UserKey<'a>, f: &FileMetaHandle) -> bool { +fn key_is_before_file(cmp: &InternalKeyCmp, key: UserKey<'_>, f: &FileMetaHandle) -> bool { let f = f.borrow(); let usmallest = parse_internal_key(&f.smallest).2; !key.is_empty() && cmp.cmp_inner(key, usmallest) == Ordering::Less @@ -514,10 +513,10 @@ fn key_is_before_file<'a>(cmp: &InternalKeyCmp, key: UserKey<'a>, f: &FileMetaHa /// find_file returns the index of the file in files that potentially contains the internal key /// key. files must not overlap and be ordered ascendingly. If no file can contain the key, None is /// returned. -fn find_file<'a>( +fn find_file( cmp: &InternalKeyCmp, files: &[FileMetaHandle], - key: InternalKey<'a>, + key: InternalKey<'_>, ) -> Option { let (mut left, mut right) = (0, files.len()); while left < right { @@ -537,11 +536,11 @@ fn find_file<'a>( /// some_file_overlaps_range_disjoint returns true if any of the given disjoint files (i.e. level > /// 1) contain keys in the range defined by the user keys [smallest; largest]. -fn some_file_overlaps_range_disjoint<'a, 'b>( +fn some_file_overlaps_range_disjoint( cmp: &InternalKeyCmp, files: &[FileMetaHandle], - smallest: UserKey<'a>, - largest: UserKey<'b>, + smallest: UserKey<'_>, + largest: UserKey<'_>, ) -> bool { let ikey = LookupKey::new(smallest, MAX_SEQUENCE_NUMBER); if let Some(ix) = find_file(cmp, files, ikey.internal_key()) { @@ -553,11 +552,11 @@ fn some_file_overlaps_range_disjoint<'a, 'b>( /// some_file_overlaps_range returns true if any of the given possibly overlapping files contains /// keys in the range [smallest; largest]. -fn some_file_overlaps_range<'a, 'b>( +fn some_file_overlaps_range( cmp: &InternalKeyCmp, files: &[FileMetaHandle], - smallest: UserKey<'a>, - largest: UserKey<'b>, + smallest: UserKey<'_>, + largest: UserKey<'_>, ) -> bool { for f in files { if !(key_is_after_file(cmp, smallest, f) || key_is_before_file(cmp, largest, f)) { @@ -599,7 +598,7 @@ pub mod testutil { /// write_table creates a table with the given number and contents (must be sorted!) in the /// memenv. The sequence numbers given to keys start with startseq. pub fn write_table( - me: &Box, + me: &dyn Env, contents: &[(&[u8], &[u8], ValueType)], startseq: u64, num: FileNum, @@ -650,40 +649,40 @@ pub mod testutil { ("bab".as_bytes(), "val4".as_bytes(), ValueType::TypeValue), ("bba".as_bytes(), "val5".as_bytes(), ValueType::TypeValue), ]; - let t2 = write_table(&env, f2, 26, 2); + let t2 = write_table(env.as_ref().as_ref(), f2, 26, 2); let f1: &[(&[u8], &[u8], ValueType)] = &[ ("aaa".as_bytes(), "val1".as_bytes(), ValueType::TypeValue), ("aab".as_bytes(), "val2".as_bytes(), ValueType::TypeValue), ("aac".as_bytes(), "val3".as_bytes(), ValueType::TypeValue), ("aba".as_bytes(), "val4".as_bytes(), ValueType::TypeValue), ]; - let t1 = write_table(&env, f1, 22, 1); + let t1 = write_table(env.as_ref().as_ref(), f1, 22, 1); // Level 1 let f3: &[(&[u8], &[u8], ValueType)] = &[ ("aaa".as_bytes(), "val0".as_bytes(), ValueType::TypeValue), ("cab".as_bytes(), "val2".as_bytes(), ValueType::TypeValue), ("cba".as_bytes(), "val3".as_bytes(), ValueType::TypeValue), ]; - let t3 = write_table(&env, f3, 19, 3); + let t3 = write_table(env.as_ref().as_ref(), f3, 19, 3); let f4: &[(&[u8], &[u8], ValueType)] = &[ ("daa".as_bytes(), "val1".as_bytes(), ValueType::TypeValue), ("dab".as_bytes(), "val2".as_bytes(), ValueType::TypeValue), ("dba".as_bytes(), "val3".as_bytes(), ValueType::TypeValue), ]; - let t4 = write_table(&env, f4, 16, 4); + let t4 = write_table(env.as_ref().as_ref(), f4, 16, 4); let f5: &[(&[u8], &[u8], ValueType)] = &[ ("eaa".as_bytes(), "val1".as_bytes(), ValueType::TypeValue), ("eab".as_bytes(), "val2".as_bytes(), ValueType::TypeValue), ("fab".as_bytes(), "val3".as_bytes(), ValueType::TypeValue), ]; - let t5 = write_table(&env, f5, 13, 5); + let t5 = write_table(env.as_ref().as_ref(), f5, 13, 5); // Level 2 let f6: &[(&[u8], &[u8], ValueType)] = &[ ("cab".as_bytes(), "val1".as_bytes(), ValueType::TypeValue), ("fab".as_bytes(), "val2".as_bytes(), ValueType::TypeValue), ("fba".as_bytes(), "val3".as_bytes(), ValueType::TypeValue), ]; - let t6 = write_table(&env, f6, 10, 6); + let t6 = write_table(env.as_ref().as_ref(), f6, 10, 6); let f7: &[(&[u8], &[u8], ValueType)] = &[ ("gaa".as_bytes(), "val1".as_bytes(), ValueType::TypeValue), ("gab".as_bytes(), "val2".as_bytes(), ValueType::TypeValue), @@ -691,18 +690,18 @@ pub mod testutil { ("gca".as_bytes(), "val4".as_bytes(), ValueType::TypeDeletion), ("gda".as_bytes(), "val5".as_bytes(), ValueType::TypeValue), ]; - let t7 = write_table(&env, f7, 5, 7); + let t7 = write_table(env.as_ref().as_ref(), f7, 5, 7); // Level 3 (2 * 2 entries, for iterator behavior). let f8: &[(&[u8], &[u8], ValueType)] = &[ ("haa".as_bytes(), "val1".as_bytes(), ValueType::TypeValue), ("hba".as_bytes(), "val2".as_bytes(), ValueType::TypeValue), ]; - let t8 = write_table(&env, f8, 3, 8); + let t8 = write_table(env.as_ref().as_ref(), f8, 3, 8); let f9: &[(&[u8], &[u8], ValueType)] = &[ ("iaa".as_bytes(), "val1".as_bytes(), ValueType::TypeValue), ("iba".as_bytes(), "val2".as_bytes(), ValueType::TypeValue), ]; - let t9 = write_table(&env, f9, 1, 9); + let t9 = write_table(env.as_ref().as_ref(), f9, 1, 9); let cache = TableCache::new("db", opts.clone(), 100); let mut v = Version::new(share(cache), Rc::new(Box::new(DefaultCmp))); @@ -730,11 +729,11 @@ mod tests { let v = make_version().0; let expected_entries = vec![0, 9, 8, 4]; - for l in 1..4 { + (1..4).for_each(|l| { let mut iter = v.new_concat_iter(l); let iter = LdbIteratorIter::wrap(&mut iter); assert_eq!(iter.count(), expected_entries[l]); - } + }); } #[test] @@ -800,7 +799,7 @@ mod tests { ("gbb".as_bytes(), 100, Ok(None)), ]; - for ref c in cases { + for c in cases { match v.get(LookupKey::new(c.0, c.1).internal_key()) { Ok(Some((val, _))) => assert_eq!(c.2.as_ref().unwrap().as_ref().unwrap(), &val), Ok(None) => assert!(c.2.as_ref().unwrap().as_ref().is_none()), @@ -825,9 +824,9 @@ mod tests { assert_eq!(6, ol[2][0].borrow().num); let ol = v.get_overlapping(LookupKey::new(b"x", 50).internal_key()); - for i in 0..NUM_LEVELS { + (0..NUM_LEVELS).for_each(|i| { assert!(ol[i].is_empty()); - } + }); } #[test]