From 0c7da618b59cb6639ca20a466dfa5618e66cc67b Mon Sep 17 00:00:00 2001 From: Lewin Bormann Date: Sat, 15 Jun 2024 17:48:32 +0200 Subject: [PATCH] More clippy refactoring --- examples/kvserver/src/main.rs | 4 +- examples/leveldb-tool/src/main.rs | 10 +- examples/mcpe/src/main.rs | 2 +- examples/stresstest/src/main.rs | 8 +- examples/word-analyze/src/main.rs | 8 +- examples/write-a-lot/src/main.rs | 6 +- src/benches/maps_bench.rs | 4 +- src/block.rs | 56 +++++----- src/blockhandle.rs | 2 +- src/db_impl.rs | 136 ++++++++++------------- src/filter_block.rs | 16 ++- src/merging_iter.rs | 14 +-- src/version.rs | 133 +++++++++++----------- src/version_edit.rs | 9 +- src/version_set.rs | 178 +++++++++++++++--------------- src/write_batch.rs | 22 ++-- 16 files changed, 308 insertions(+), 300 deletions(-) diff --git a/examples/kvserver/src/main.rs b/examples/kvserver/src/main.rs index f77d6e4..1df686c 100644 --- a/examples/kvserver/src/main.rs +++ b/examples/kvserver/src/main.rs @@ -1,5 +1,3 @@ -use canteen; -use rusty_leveldb; struct KVService { db: rusty_leveldb::DB, @@ -62,7 +60,7 @@ fn put_key_fn(rq: &canteen::Request) -> canteen::Response { fn main() { let db = rusty_leveldb::DB::open("httpdb", rusty_leveldb::Options::default()).unwrap(); - let service = KVService { db: db }; + let service = KVService { db }; unsafe { STORAGE_SERVICE = Some(std::sync::Mutex::new(service)) }; let mut ct = canteen::Canteen::new(); diff --git a/examples/leveldb-tool/src/main.rs b/examples/leveldb-tool/src/main.rs index 8d7dff9..a45ec65 100644 --- a/examples/leveldb-tool/src/main.rs +++ b/examples/leveldb-tool/src/main.rs @@ -56,10 +56,12 @@ fn main() { ); } - let mut opt = Options::default(); - opt.reuse_logs = false; - opt.reuse_manifest = false; - opt.compressor = compressor::SnappyCompressor::ID; + let opt = Options { + reuse_logs: false, + reuse_manifest: false, + compressor: compressor::SnappyCompressor::ID, + ..Default::default() + }; let mut db = DB::open("tooldb", opt).unwrap(); match args[1].as_str() { diff --git a/examples/mcpe/src/main.rs b/examples/mcpe/src/main.rs index e6895a1..56eb917 100644 --- a/examples/mcpe/src/main.rs +++ b/examples/mcpe/src/main.rs @@ -73,7 +73,7 @@ pub fn mcpe_options(compression_level: u8) -> Options { // // 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()); + list.set_with_id(0, NoneCompressor {}); list.set_with_id(2, ZlibCompressor::new(compression_level)); list.set_with_id(4, RawZlibCompressor::new(compression_level)); opt.compressor_list = Rc::new(list); diff --git a/examples/stresstest/src/main.rs b/examples/stresstest/src/main.rs index 18e074c..38a44e6 100644 --- a/examples/stresstest/src/main.rs +++ b/examples/stresstest/src/main.rs @@ -34,7 +34,7 @@ fn read(db: &mut DB, n: usize) -> usize { for _ in 0..n { let k = gen_string(KEY_LEN); - if let Some(_) = db.get(k.as_bytes()) { + if db.get(k.as_bytes()).is_some() { succ += 1; } } @@ -48,8 +48,10 @@ fn main() { let mut entries = 0; for i in 0..m { - let mut opt = Options::default(); - opt.compressor = compressor::SnappyCompressor::ID; + let opt = Options { + compressor: compressor::SnappyCompressor::ID, + ..Default::default() + }; let mut db = DB::open(path, opt).unwrap(); write(&mut db, n); entries += n; diff --git a/examples/word-analyze/src/main.rs b/examples/word-analyze/src/main.rs index 2effed2..4f38612 100644 --- a/examples/word-analyze/src/main.rs +++ b/examples/word-analyze/src/main.rs @@ -9,7 +9,7 @@ fn update_count(w: &str, db: &mut leveldb::DB) -> Option<()> { let mut count: usize = 0; if let Some(v) = db.get(w.as_bytes()) { let s = String::from_utf8(v).unwrap(); - count = usize::from_str_radix(&s, 10).unwrap(); + count = s.parse::().unwrap(); } count += 1; let s = count.to_string(); @@ -35,8 +35,10 @@ fn run(mut db: leveldb::DB) -> io::Result<()> { } fn main() { - let mut opts = leveldb::Options::default(); - opts.compressor = leveldb::compressor::NoneCompressor::ID; + let opts = leveldb::Options { + compressor: leveldb::compressor::NoneCompressor::ID, + ..Default::default() + }; let db = leveldb::DB::open("wordsdb", opts).unwrap(); run(db).unwrap(); diff --git a/examples/write-a-lot/src/main.rs b/examples/write-a-lot/src/main.rs index 965c38c..c8ce763 100644 --- a/examples/write-a-lot/src/main.rs +++ b/examples/write-a-lot/src/main.rs @@ -28,8 +28,10 @@ fn fill_db(db: &mut DB, entries: usize) -> Result<(), Box> { } fn main() { - let mut opt = Options::default(); - opt.compressor = compressor::SnappyCompressor::ID; + let opt = Options { + compressor: compressor::SnappyCompressor::ID, + ..Default::default() + }; let mut db = DB::open("test1", opt).unwrap(); fill_db(&mut db, 32768).unwrap(); diff --git a/src/benches/maps_bench.rs b/src/benches/maps_bench.rs index 97c316d..3a9885b 100644 --- a/src/benches/maps_bench.rs +++ b/src/benches/maps_bench.rs @@ -21,10 +21,10 @@ fn gen_key_val(gen: &mut R, keylen: usize, vallen: usize) -> (Vec, V let mut val = Vec::with_capacity(vallen); for _i in 0..keylen { - key.push(gen.gen_range(b'a', b'z')); + key.push(gen.gen_range(b'a'..=b'z')); } for _i in 0..vallen { - val.push(gen.gen_range(b'a', b'z')); + val.push(gen.gen_range(b'a'..=b'z')); } (key, val) } diff --git a/src/block.rs b/src/block.rs index f5e930c..9f50fab 100644 --- a/src/block.rs +++ b/src/block.rs @@ -319,15 +319,15 @@ mod tests { fn get_data() -> Vec<(&'static [u8], &'static [u8])> { vec![ - ("key1".as_bytes(), "value1".as_bytes()), + (b"key1", b"value1"), ( - "loooooooooooooooooooooooooooooooooongerkey1".as_bytes(), - "shrtvl1".as_bytes(), + b"loooooooooooooooooooooooooooooooooongerkey1", + b"shrtvl1", ), ("medium length key 1".as_bytes(), "some value 2".as_bytes()), - ("prefix_key1".as_bytes(), "value".as_bytes()), - ("prefix_key2".as_bytes(), "value".as_bytes()), - ("prefix_key3".as_bytes(), "value".as_bytes()), + (b"prefix_key1", b"value"), + (b"prefix_key2", b"value"), + (b"prefix_key3", b"value"), ] } @@ -358,9 +358,9 @@ mod tests { let block = Block::new(options::for_test(), blockc); - for _ in LdbIteratorIter::wrap(&mut block.iter()) { + LdbIteratorIter::wrap(&mut block.iter()).for_each(|_| { panic!("expected 0 iterations"); - } + }); } #[test] @@ -403,7 +403,7 @@ mod tests { assert!(!block.valid()); assert_eq!( block.next(), - Some(("key1".as_bytes().to_vec(), "value1".as_bytes().to_vec())) + Some((b"key1".to_vec(), b"value1".to_vec())) ); assert!(block.valid()); block.next(); @@ -412,22 +412,22 @@ mod tests { assert!(block.valid()); assert_eq!( current_key_val(&block), - Some(("key1".as_bytes().to_vec(), "value1".as_bytes().to_vec())) + Some((b"key1".to_vec(), b"value1".to_vec())) ); block.prev(); assert!(!block.valid()); // Verify that prev() from the last entry goes to the prev-to-last entry // (essentially, that next() returning None doesn't advance anything) - while let Some(_) = block.next() {} + while block.next().is_some() {} block.prev(); assert!(block.valid()); assert_eq!( current_key_val(&block), Some(( - "prefix_key2".as_bytes().to_vec(), - "value".as_bytes().to_vec() + b"prefix_key2".to_vec(), + b"value".to_vec() )) ); } @@ -448,44 +448,44 @@ mod tests { let mut block = Block::new(o.clone(), block_contents).iter(); - block.seek(&"prefix_key2".as_bytes()); + block.seek(b"prefix_key2"); assert!(block.valid()); assert_eq!( current_key_val(&block), Some(( - "prefix_key2".as_bytes().to_vec(), - "value".as_bytes().to_vec() + b"prefix_key2".to_vec(), + b"value".to_vec() )) ); - block.seek(&"prefix_key0".as_bytes()); + block.seek(b"prefix_key0"); assert!(block.valid()); assert_eq!( current_key_val(&block), Some(( - "prefix_key1".as_bytes().to_vec(), - "value".as_bytes().to_vec() + b"prefix_key1".to_vec(), + b"value".to_vec() )) ); - block.seek(&"key1".as_bytes()); + block.seek(b"key1"); assert!(block.valid()); assert_eq!( current_key_val(&block), - Some(("key1".as_bytes().to_vec(), "value1".as_bytes().to_vec())) + Some((b"key1".to_vec(), b"value1".to_vec())) ); - block.seek(&"prefix_key3".as_bytes()); + block.seek(b"prefix_key3"); assert!(block.valid()); assert_eq!( current_key_val(&block), Some(( - "prefix_key3".as_bytes().to_vec(), - "value".as_bytes().to_vec() + b"prefix_key3".to_vec(), + b"value".to_vec() )) ); - block.seek(&"prefix_key8".as_bytes()); + block.seek(b"prefix_key8"); assert!(!block.valid()); assert_eq!(current_key_val(&block), None); } @@ -495,7 +495,7 @@ mod tests { let mut o = options::for_test(); // Test with different number of restarts - for block_restart_interval in vec![2, 6, 10] { + for block_restart_interval in [2, 6, 10] { o.block_restart_interval = block_restart_interval; let data = get_data(); @@ -514,8 +514,8 @@ mod tests { assert_eq!( current_key_val(&block), Some(( - "prefix_key3".as_bytes().to_vec(), - "value".as_bytes().to_vec() + b"prefix_key3".to_vec(), + b"value".to_vec() )) ); } diff --git a/src/blockhandle.rs b/src/blockhandle.rs index 5c5514f..eb5a744 100644 --- a/src/blockhandle.rs +++ b/src/blockhandle.rs @@ -54,7 +54,7 @@ mod tests { #[test] fn test_blockhandle() { let bh = BlockHandle::new(890, 777); - let mut dst = [0 as u8; 128]; + let mut dst = [0_u8; 128]; let enc_sz = bh.encode_to(&mut dst[..]); let (bh2, dec_sz) = BlockHandle::decode(&dst).unwrap(); diff --git a/src/db_impl.rs b/src/db_impl.rs index f7b1311..4bf9809 100644 --- a/src/db_impl.rs +++ b/src/db_impl.rs @@ -74,8 +74,8 @@ impl DB { } let path = name.canonicalize().unwrap_or(name.to_owned()); - let cache = share(TableCache::new(&name, opt.clone(), opt.max_open_files - 10)); - let vset = VersionSet::new(&name, opt.clone(), cache.clone()); + let cache = share(TableCache::new(name, opt.clone(), opt.max_open_files - 10)); + let vset = VersionSet::new(name, opt.clone(), cache.clone()); DB { name: name.to_owned(), @@ -151,20 +151,20 @@ impl DB { lw.add_record(&ve.encode())?; lw.flush()?; } - set_current_file(&self.opt.env, &self.path, 1) + set_current_file(self.opt.env.as_ref().as_ref(), &self.path, 1) } /// recover recovers from the existing state on disk. If the wrapped result is `true`, then /// log_and_apply() should be called after recovery has finished. fn recover(&mut self, ve: &mut VersionEdit) -> Result { - if self.opt.error_if_exists && self.opt.env.exists(&self.path.as_ref()).unwrap_or(false) { + if self.opt.error_if_exists && self.opt.env.exists(self.path.as_ref()).unwrap_or(false) { return err(StatusCode::AlreadyExists, "database already exists"); } let _ = self.opt.env.mkdir(Path::new(&self.path)); self.acquire_lock()?; - if let Err(e) = read_current_file(&self.opt.env, &self.path) { + if let Err(e) = read_current_file(self.opt.env.as_ref().as_ref(), &self.path) { if e.code == StatusCode::NotFound && self.opt.create_if_missing { self.initialize_db()?; } else { @@ -186,7 +186,7 @@ impl DB { let mut log_files = vec![]; for file in &filenames { - match parse_file_name(&file) { + match parse_file_name(file) { Ok((num, typ)) => { expected.remove(&num); if typ == FileType::Log @@ -551,7 +551,7 @@ impl DB { } /// Trigger a compaction based on where this key is located in the different levels. - fn record_read_sample<'a>(&mut self, k: InternalKey<'a>) { + fn record_read_sample(&mut self, k: InternalKey<'_>) { let current = self.current(); if current.borrow_mut().record_read_sample(k) { if let Err(e) = self.maybe_do_compaction() { @@ -645,7 +645,7 @@ impl DB { if let Some(c) = c_ { // Update ifrom to the largest key of the last file in this compaction. let ix = c.num_inputs(0) - 1; - ifrom = c.input(0, ix).largest.clone(); + ifrom.clone_from(&c.input(0, ix).largest); self.start_compaction(c)?; } else { break; @@ -696,7 +696,7 @@ impl DB { }; let mut state = CompactionState::new(compaction, smallest); if let Err(e) = self.do_compaction_work(&mut state) { - state.cleanup(&self.opt.env, &self.path); + state.cleanup(self.opt.env.as_ref().as_ref(), &self.path); log!(self.opt.log, "Compaction work failed: {}", e); } self.install_compaction_results(state)?; @@ -763,9 +763,11 @@ impl DB { return Err(e); } - let mut stats = CompactionStats::default(); - stats.micros = self.opt.env.micros() - start_ts; - stats.written = fmd.size; + let stats = CompactionStats { + micros: self.opt.env.micros() - start_ts, + written: fmd.size, + ..Default::default() + }; let mut level = 0; if let Some(b) = base { @@ -853,8 +855,10 @@ impl DB { if cs.builder.is_none() { let fnum = self.vset.borrow_mut().new_file_number(); - let mut fmd = FileMetaData::default(); - fmd.num = fnum; + let fmd = FileMetaData { + num: fnum, + ..Default::default() + }; let fname = table_file_name(&self.path, fnum); let f = self.opt.env.open_writable_file(Path::new(&fname))?; @@ -863,9 +867,9 @@ impl DB { cs.outputs.push(fmd); } if cs.builder.as_ref().unwrap().entries() == 0 { - cs.current_output().smallest = key.clone(); + cs.current_output().smallest.clone_from(&key); } - cs.current_output().largest = key.clone(); + cs.current_output().largest.clone_from(&key); cs.builder.as_mut().unwrap().add(&key, &val)?; // NOTE: Adjust max file size based on level. if cs.builder.as_ref().unwrap().size_estimate() > self.opt.max_file_size { @@ -879,8 +883,10 @@ impl DB { self.finish_compaction_output(cs)?; } - let mut stats = CompactionStats::default(); - stats.micros = self.opt.env.micros() - start_ts; + let mut stats = CompactionStats { + micros: self.opt.env.micros() - start_ts, + ..Default::default() + }; for parent in 0..2 { for inp in 0..cs.compaction.num_inputs(parent) { stats.read += cs.compaction.input(parent, inp).size; @@ -980,7 +986,7 @@ impl CompactionState { } /// cleanup cleans up after an aborted compaction. - fn cleanup>(&mut self, env: &Box, name: P) { + fn cleanup>(&mut self, env: &dyn Env, name: P) { for o in self.outputs.drain(..) { let name = table_file_name(name.as_ref(), o.num); let _ = env.delete(&name); @@ -1112,7 +1118,7 @@ pub mod testutil { let mut lw = LogWriter::new(manifest_file); lw.add_record(&ve.encode()).unwrap(); lw.flush().unwrap(); - set_current_file(&opt.env, name, 10).unwrap(); + set_current_file(opt.env.as_ref().as_ref(), name, 10).unwrap(); (DB::open(name, opt.clone()).unwrap(), opt) } @@ -1182,12 +1188,7 @@ mod tests { let mut mt = MemTable::new(options::for_test().cmp); let mut i = 1; for k in ["abc", "def", "ghi", "jkl", "mno", "aabc", "test123"].iter() { - mt.add( - i, - ValueType::TypeValue, - k.as_bytes(), - "looooongval".as_bytes(), - ); + mt.add(i, ValueType::TypeValue, k.as_bytes(), b"looooongval"); i += 1; } mt @@ -1241,8 +1242,8 @@ mod tests { assert!(env.exists(&Path::new("db").join("LOCK")).unwrap()); assert!(env.exists(&Path::new("db").join("000003.log")).unwrap()); - db.put("abc".as_bytes(), "def".as_bytes()).unwrap(); - db.put("abd".as_bytes(), "def".as_bytes()).unwrap(); + db.put(b"abc", b"def").unwrap(); + db.put(b"abd", b"def").unwrap(); } { @@ -1276,16 +1277,16 @@ mod tests { let current = db.current(); log!(opt.log, "files: {:?}", current.borrow().files); assert_eq!( - "def".as_bytes(), + b"def", current .borrow_mut() - .get(LookupKey::new("abc".as_bytes(), 1).internal_key()) + .get(LookupKey::new(b"abc", 1).internal_key()) .unwrap() .unwrap() .0 .as_slice() ); - db.put("abe".as_bytes(), "def".as_bytes()).unwrap(); + db.put(b"abe", b"def").unwrap(); } { @@ -1318,12 +1319,8 @@ mod tests { // Log is reused, so memtable should contain last written entry from above. assert_eq!(1, db.mem.len()); assert_eq!( - "def".as_bytes(), - db.mem - .get(&LookupKey::new("abe".as_bytes(), 3)) - .0 - .unwrap() - .as_slice() + b"def", + db.mem.get(&LookupKey::new(b"abe", 3)).0.unwrap().as_slice() ); } } @@ -1468,11 +1465,11 @@ mod tests { let path = &Path::new("db").join("000123.ldb"); assert_eq!( - LookupKey::new("aabc".as_bytes(), 6).internal_key(), + LookupKey::new(b"aabc", 6).internal_key(), f.smallest.as_slice() ); assert_eq!( - LookupKey::new("test123".as_bytes(), 7).internal_key(), + LookupKey::new(b"test123", 7).internal_key(), f.largest.as_slice() ); assert_eq!(379, f.size); @@ -1530,49 +1527,34 @@ mod tests { assert_eq!(30, db.vset.borrow().last_seq); // seq = 31 - db.put("xyy".as_bytes(), "123".as_bytes()).unwrap(); + db.put(b"xyy", b"123").unwrap(); let old_ss = db.get_snapshot(); // seq = 32 - db.put("xyz".as_bytes(), "123".as_bytes()).unwrap(); + db.put(b"xyz", b"123").unwrap(); db.flush().unwrap(); - assert!(db.get_at(&old_ss, "xyy".as_bytes()).unwrap().is_some()); - assert!(db.get_at(&old_ss, "xyz".as_bytes()).unwrap().is_none()); + assert!(db.get_at(&old_ss, b"xyy").unwrap().is_some()); + assert!(db.get_at(&old_ss, b"xyz").unwrap().is_none()); // memtable get - assert_eq!( - "123".as_bytes(), - db.get("xyz".as_bytes()).unwrap().as_slice() - ); - assert!(db.get_internal(31, "xyy".as_bytes()).unwrap().is_some()); - assert!(db.get_internal(32, "xyy".as_bytes()).unwrap().is_some()); + assert_eq!(b"123", db.get(b"xyz").unwrap().as_slice()); + assert!(db.get_internal(31, b"xyy").unwrap().is_some()); + assert!(db.get_internal(32, b"xyy").unwrap().is_some()); - assert!(db.get_internal(31, "xyz".as_bytes()).unwrap().is_none()); - assert!(db.get_internal(32, "xyz".as_bytes()).unwrap().is_some()); + assert!(db.get_internal(31, b"xyz").unwrap().is_none()); + assert!(db.get_internal(32, b"xyz").unwrap().is_some()); // table get - assert_eq!( - "val2".as_bytes(), - db.get("eab".as_bytes()).unwrap().as_slice() - ); - assert!(db.get_internal(3, "eab".as_bytes()).unwrap().is_none()); - assert!(db.get_internal(32, "eab".as_bytes()).unwrap().is_some()); + assert_eq!(b"val2", db.get(b"eab").unwrap().as_slice()); + assert!(db.get_internal(3, b"eab").unwrap().is_none()); + assert!(db.get_internal(32, b"eab").unwrap().is_some()); { let ss = db.get_snapshot(); - assert_eq!( - "val2".as_bytes(), - db.get_at(&ss, "eab".as_bytes()) - .unwrap() - .unwrap() - .as_slice() - ); + assert_eq!(b"val2", db.get_at(&ss, b"eab").unwrap().unwrap().as_slice()); } // from table. - assert_eq!( - "val2".as_bytes(), - db.get("cab".as_bytes()).unwrap().as_slice() - ); + assert_eq!(b"val2", db.get(b"cab").unwrap().as_slice()); } #[test] @@ -1612,10 +1594,10 @@ mod tests { fn test_db_impl_compaction_trivial_move() { let mut db = DB::open("db", options::for_test()).unwrap(); - db.put("abc".as_bytes(), "xyz".as_bytes()).unwrap(); - db.put("ab3".as_bytes(), "xyz".as_bytes()).unwrap(); - db.put("ab0".as_bytes(), "xyz".as_bytes()).unwrap(); - db.put("abz".as_bytes(), "xyz".as_bytes()).unwrap(); + db.put(b"abc", b"xyz").unwrap(); + db.put(b"ab3", b"xyz").unwrap(); + db.put(b"ab0", b"xyz").unwrap(); + db.put(b"abz", b"xyz").unwrap(); assert_eq!(4, db.mem.len()); let mut imm = MemTable::new(db.opt.cmp.clone()); mem::swap(&mut imm, &mut db.mem); @@ -1749,17 +1731,19 @@ mod tests { let env: Box = Box::new(MemEnv::new()); let name = "db"; - let stuff = "abcdefghijkl".as_bytes(); + let stuff = b"abcdefghijkl"; env.open_writable_file(&Path::new("db").join("000001.ldb")) .unwrap() .write_all(stuff) .unwrap(); - let mut fmd = FileMetaData::default(); - fmd.num = 1; + let fmd = FileMetaData { + num: 1, + ..Default::default() + }; let mut cs = CompactionState::new(Compaction::new(&options::for_test(), 2, None), 12); cs.outputs = vec![fmd]; - cs.cleanup(&env, name); + cs.cleanup(env.as_ref(), name); assert!(!env.exists(&Path::new("db").join("000001.ldb")).unwrap()); } diff --git a/src/filter_block.rs b/src/filter_block.rs index c78a303..6f7017a 100644 --- a/src/filter_block.rs +++ b/src/filter_block.rs @@ -176,10 +176,10 @@ mod tests { fn get_keys() -> Vec<&'static [u8]> { vec![ - "abcd".as_bytes(), - "efgh".as_bytes(), - "ijkl".as_bytes(), - "mnopqrstuvwxyz".as_bytes(), + b"abcd", + b"efgh", + b"ijkl", + b"mnopqrstuvwxyz", ] } @@ -229,11 +229,9 @@ mod tests { 17 ); // third block in third filter - let unknown_keys = vec![ - "xsb".as_bytes(), - "9sad".as_bytes(), - "assssaaaass".as_bytes(), - ]; + let unknown_keys: [&[u8]; 3] = [b"xsb", + b"9sad", + b"assssaaaass"]; for block_offset in vec![0, 1024, 5000, 6025].into_iter() { for key in get_keys().iter() { diff --git a/src/merging_iter.rs b/src/merging_iter.rs index b5dd9f2..dab76e7 100644 --- a/src/merging_iter.rs +++ b/src/merging_iter.rs @@ -247,7 +247,7 @@ mod tests { #[test] fn test_merging_behavior() { - let val = "def".as_bytes(); + let val = b"def"; let iter = TestLdbIter::new(vec![(b("aba"), val), (b("abc"), val)]); let iter2 = TestLdbIter::new(vec![(b("abb"), val), (b("abd"), val)]); let miter = MergingIter::new( @@ -259,7 +259,7 @@ mod tests { #[test] fn test_merging_forward_backward() { - let val = "def".as_bytes(); + let val = b"def"; let iter = TestLdbIter::new(vec![(b("aba"), val), (b("abc"), val), (b("abe"), val)]); let iter2 = TestLdbIter::new(vec![(b("abb"), val), (b("abd"), val)]); @@ -305,7 +305,7 @@ mod tests { #[test] fn test_merging_real() { - let val = "def".as_bytes(); + let val = b"def"; 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)]); @@ -323,7 +323,7 @@ mod tests { #[test] fn test_merging_seek_reset() { - let val = "def".as_bytes(); + let val = b"def"; 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)]); @@ -338,17 +338,17 @@ mod tests { assert!(iter.valid()); assert!(current_key_val(&iter).is_some()); - iter.seek("abc".as_bytes()); + iter.seek(b"abc"); assert_eq!( current_key_val(&iter), Some((b("abc").to_vec(), val.to_vec())) ); - iter.seek("ab0".as_bytes()); + iter.seek(b"ab0"); assert_eq!( current_key_val(&iter), Some((b("aba").to_vec(), val.to_vec())) ); - iter.seek("abx".as_bytes()); + iter.seek(b"abx"); assert_eq!(current_key_val(&iter), None); iter.reset(); diff --git a/src/version.rs b/src/version.rs index bd80955..4b81612 100644 --- a/src/version.rs +++ b/src/version.rs @@ -31,6 +31,8 @@ pub struct Version { pub compaction_level: Option, } +struct DoSearchResult(Option<(Vec, Vec)>, Vec); + impl Version { pub fn new(cache: Shared, ucmp: Rc>) -> Version { Version { @@ -291,11 +293,11 @@ impl Version { loop { match do_search(self, level, ubegin, uend) { - (Some((newubegin, newuend)), _) => { + DoSearchResult(Some((newubegin, newuend)), _) => { ubegin = newubegin; uend = newuend; } - (None, result) => return result, + DoSearchResult(None, result) => return result, } } @@ -307,7 +309,7 @@ impl Version { level: usize, ubegin: Vec, uend: Vec, - ) -> (Option<(Vec, Vec)>, Vec) { + ) -> DoSearchResult { let mut inputs = vec![]; for f_ in myself.files[level].iter() { let f = f_.borrow(); @@ -316,13 +318,14 @@ impl Version { parse_internal_key(&f.largest).2, ); // Skip files that are not overlapping. - if !ubegin.is_empty() && myself.user_cmp.cmp(flargest, &ubegin) == Ordering::Less { - continue; - } else if !uend.is_empty() - && myself.user_cmp.cmp(fsmallest, &uend) == Ordering::Greater - { - continue; - } else { + let ubegin_nonempty = !ubegin.is_empty(); + let uend_nonempty = !uend.is_empty(); + let block_before_current = + ubegin_nonempty && myself.user_cmp.cmp(flargest, &ubegin) == Ordering::Less; + let block_after_current = + uend_nonempty && myself.user_cmp.cmp(fsmallest, &uend) == Ordering::Greater; + let is_overlapping = !(block_before_current || block_after_current); + if is_overlapping { inputs.push(f_.clone()); // In level 0, files may overlap each other. Check if the new file begins // before ubegin or ends after uend, and expand the range, if so. Then, restart @@ -331,16 +334,18 @@ impl Version { if !ubegin.is_empty() && myself.user_cmp.cmp(fsmallest, &ubegin) == Ordering::Less { - return (Some((fsmallest.to_vec(), uend)), inputs); + return DoSearchResult(Some((fsmallest.to_vec(), uend)), inputs); } else if !uend.is_empty() && myself.user_cmp.cmp(flargest, &uend) == Ordering::Greater { - return (Some((ubegin, flargest.to_vec())), inputs); + return DoSearchResult(Some((ubegin, flargest.to_vec())), inputs); } } + } else { + continue; } } - (None, inputs) + DoSearchResult(None, inputs) } } @@ -643,63 +648,63 @@ pub mod testutil { // Level 0 (overlapping) let f2: &[(&[u8], &[u8], ValueType)] = &[ - ("aac".as_bytes(), "val1".as_bytes(), ValueType::TypeDeletion), - ("aax".as_bytes(), "val2".as_bytes(), ValueType::TypeValue), - ("aba".as_bytes(), "val3".as_bytes(), ValueType::TypeValue), - ("bab".as_bytes(), "val4".as_bytes(), ValueType::TypeValue), - ("bba".as_bytes(), "val5".as_bytes(), ValueType::TypeValue), + (b"aac", b"val1", ValueType::TypeDeletion), + (b"aax", b"val2", ValueType::TypeValue), + (b"aba", b"val3", ValueType::TypeValue), + (b"bab", b"val4", ValueType::TypeValue), + (b"bba", b"val5", ValueType::TypeValue), ]; 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), + (b"aaa", b"val1", ValueType::TypeValue), + (b"aab", b"val2", ValueType::TypeValue), + (b"aac", b"val3", ValueType::TypeValue), + (b"aba", b"val4", ValueType::TypeValue), ]; 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), + (b"aaa", b"val0", ValueType::TypeValue), + (b"cab", b"val2", ValueType::TypeValue), + (b"cba", b"val3", ValueType::TypeValue), ]; 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), + (b"daa", b"val1", ValueType::TypeValue), + (b"dab", b"val2", ValueType::TypeValue), + (b"dba", b"val3", ValueType::TypeValue), ]; 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), + (b"eaa", b"val1", ValueType::TypeValue), + (b"eab", b"val2", ValueType::TypeValue), + (b"fab", b"val3", ValueType::TypeValue), ]; 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), + (b"cab", b"val1", ValueType::TypeValue), + (b"fab", b"val2", ValueType::TypeValue), + (b"fba", b"val3", ValueType::TypeValue), ]; 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), - ("gba".as_bytes(), "val3".as_bytes(), ValueType::TypeValue), - ("gca".as_bytes(), "val4".as_bytes(), ValueType::TypeDeletion), - ("gda".as_bytes(), "val5".as_bytes(), ValueType::TypeValue), + (b"gaa", b"val1", ValueType::TypeValue), + (b"gab", b"val2", ValueType::TypeValue), + (b"gba", b"val3", ValueType::TypeValue), + (b"gca", b"val4", ValueType::TypeDeletion), + (b"gda", b"val5", ValueType::TypeValue), ]; 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), + (b"haa", b"val1", ValueType::TypeValue), + (b"hba", b"val2", ValueType::TypeValue), ]; 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), + (b"iaa", b"val1", ValueType::TypeValue), + (b"iba", b"val2", ValueType::TypeValue), ]; let t9 = write_table(env.as_ref().as_ref(), f9, 1, 9); @@ -728,7 +733,7 @@ mod tests { fn test_version_concat_iter() { let v = make_version().0; - let expected_entries = vec![0, 9, 8, 4]; + let expected_entries = [0, 9, 8, 4]; (1..4).for_each(|l| { let mut iter = v.new_concat_iter(l); let iter = LdbIteratorIter::wrap(&mut iter); @@ -760,7 +765,7 @@ mod tests { assert_eq!(LdbIteratorIter::wrap(&mut miter).count(), 30); // Check that all elements are in order. - let init = LookupKey::new("000".as_bytes(), MAX_SEQUENCE_NUMBER); + let init = LookupKey::new(b"000", MAX_SEQUENCE_NUMBER); let cmp = InternalKeyCmp(Rc::new(Box::new(DefaultCmp))); LdbIteratorIter::wrap(&mut miter).fold(init.internal_key().to_vec(), |b, (k, _)| { assert!(cmp.cmp(&b, &k) == Ordering::Less); @@ -781,31 +786,31 @@ mod tests { fn test_version_get_simple() { let v = make_version().0; let cases: &[(&[u8], u64, Result>>)] = &[ - ("aaa".as_bytes(), 1, Ok(None)), - ("aaa".as_bytes(), 100, Ok(Some("val1".as_bytes().to_vec()))), - ("aaa".as_bytes(), 21, Ok(Some("val0".as_bytes().to_vec()))), - ("aab".as_bytes(), 0, Ok(None)), - ("aab".as_bytes(), 100, Ok(Some("val2".as_bytes().to_vec()))), - ("aac".as_bytes(), 100, Ok(None)), - ("aac".as_bytes(), 25, Ok(Some("val3".as_bytes().to_vec()))), - ("aba".as_bytes(), 100, Ok(Some("val3".as_bytes().to_vec()))), - ("aba".as_bytes(), 25, Ok(Some("val4".as_bytes().to_vec()))), - ("daa".as_bytes(), 100, Ok(Some("val1".as_bytes().to_vec()))), - ("dab".as_bytes(), 1, Ok(None)), - ("dac".as_bytes(), 100, Ok(None)), - ("gba".as_bytes(), 100, Ok(Some("val3".as_bytes().to_vec()))), + (b"aaa", 1, Ok(None)), + (b"aaa", 100, Ok(Some("val1".as_bytes().to_vec()))), + (b"aaa", 21, Ok(Some("val0".as_bytes().to_vec()))), + (b"aab", 0, Ok(None)), + (b"aab", 100, Ok(Some("val2".as_bytes().to_vec()))), + (b"aac", 100, Ok(None)), + (b"aac", 25, Ok(Some("val3".as_bytes().to_vec()))), + (b"aba", 100, Ok(Some("val3".as_bytes().to_vec()))), + (b"aba", 25, Ok(Some("val4".as_bytes().to_vec()))), + (b"daa", 100, Ok(Some("val1".as_bytes().to_vec()))), + (b"dab", 1, Ok(None)), + (b"dac", 100, Ok(None)), + (b"gba", 100, Ok(Some("val3".as_bytes().to_vec()))), // deleted key - ("gca".as_bytes(), 100, Ok(None)), - ("gbb".as_bytes(), 100, Ok(None)), + (b"gca", 100, Ok(None)), + (b"gbb", 100, Ok(None)), ]; - for c in cases { - match v.get(LookupKey::new(c.0, c.1).internal_key()) { + cases + .iter() + .for_each(|c| 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()), Err(_) => assert!(c.2.is_err()), - } - } + }); } #[test] diff --git a/src/version_edit.rs b/src/version_edit.rs index 84e7a80..a86a952 100644 --- a/src/version_edit.rs +++ b/src/version_edit.rs @@ -41,8 +41,7 @@ fn tag_to_enum(t: u32) -> Option { fn read_length_prefixed(reader: &mut R) -> Result> { if let Ok(klen) = reader.read_varint() { - let mut keybuf = Vec::new(); - keybuf.resize(klen, 0); + let mut keybuf = vec![0; klen]; if let Ok(l) = reader.read(&mut keybuf) { if l != klen { @@ -294,6 +293,12 @@ impl VersionEdit { } } +impl Default for VersionEdit { + fn default() -> Self { + Self::new() + } +} + #[cfg(test)] mod tests { use super::CompactionPointer; diff --git a/src/version_set.rs b/src/version_set.rs index 75a63ac..cd59ccc 100644 --- a/src/version_set.rs +++ b/src/version_set.rs @@ -1,6 +1,6 @@ use crate::cmp::{Cmp, InternalKeyCmp}; use crate::env::Env; -use crate::error::{err, Result, Status, StatusCode}; +use crate::error::{err, Result, StatusCode}; use crate::key_types::{parse_internal_key, InternalKey, UserKey}; use crate::log::{LogReader, LogWriter}; use crate::merging_iter::MergingIter; @@ -99,7 +99,7 @@ impl Compaction { /// is_base_level_for checks whether the given key may exist in levels higher than this /// compaction's level plus 2. I.e., whether the levels for this compaction are the last ones /// to contain the key. - pub fn is_base_level_for<'a>(&mut self, k: UserKey<'a>) -> bool { + pub fn is_base_level_for(&mut self, k: UserKey<'_>) -> bool { assert!(self.input_version.is_some()); let inp_version = self.input_version.as_ref().unwrap(); for level in self.level + 2..NUM_LEVELS { @@ -134,7 +134,7 @@ impl Compaction { self.num_inputs(0) == 1 && self.num_inputs(1) == 0 && inputs_size < 10 * self.max_file_size } - pub fn should_stop_before<'a>(&mut self, k: InternalKey<'a>) -> bool { + pub fn should_stop_before(&mut self, k: InternalKey<'_>) -> bool { if self.grandparents.is_none() { self.seen_key = true; return false; @@ -258,7 +258,7 @@ impl VersionSet { v.compaction_score.unwrap_or(0.0) >= 1.0 || v.file_to_compact.is_some() } - fn approximate_offset<'a>(&self, v: &Shared, key: InternalKey<'a>) -> usize { + fn approximate_offset(&self, v: &Shared, key: InternalKey<'_>) -> usize { let mut offset = 0; for level in 0..NUM_LEVELS { for f in &v.borrow().files[level] { @@ -315,7 +315,7 @@ impl VersionSet { } c.level = level; - c.input_version = self.current.clone(); + c.input_version.clone_from(&self.current); if level == 0 { let (smallest, largest) = get_range(&self.cmp, c.inputs[0].iter()); @@ -328,11 +328,11 @@ impl VersionSet { Some(c) } - pub fn compact_range<'a, 'b>( + pub fn compact_range( &mut self, level: usize, - from: InternalKey<'a>, - to: InternalKey<'b>, + from: InternalKey<'_>, + to: InternalKey<'_>, ) -> Option { assert!(self.current.is_some()); let mut inputs = self @@ -514,7 +514,11 @@ impl VersionSet { lw.add_record(&encoded)?; lw.flush()?; } - set_current_file(&self.opt.env, &self.dbname, self.manifest_num)?; + set_current_file( + self.opt.env.as_ref().as_ref(), + &self.dbname, + self.manifest_num, + )?; self.add_version(v); // log_number was set above. @@ -529,16 +533,15 @@ impl VersionSet { let mut best_score = None; for l in 0..NUM_LEVELS - 1 { - let score: f64; - if l == 0 { - score = v.files[l].len() as f64 / 4.0; + let score = if l == 0 { + v.files[l].len() as f64 / 4.0 } else { let mut max_bytes = 10.0 * f64::from(1 << 20); for _ in 0..l - 1 { max_bytes *= 10.0; } - score = total_size(v.files[l].iter()) as f64 / max_bytes; - } + total_size(v.files[l].iter()) as f64 / max_bytes + }; if let Some(ref mut b) = best_score { if *b < score { *b = score; @@ -558,7 +561,7 @@ impl VersionSet { pub fn recover(&mut self) -> Result { assert!(self.current.is_some()); - let mut current = read_current_file(&self.opt.env, &self.dbname)?; + let mut current = read_current_file(self.opt.env.as_ref().as_ref(), &self.dbname)?; let len = current.len(); current.truncate(len - 1); let current = Path::new(¤t); @@ -652,7 +655,7 @@ impl VersionSet { ); // A new manifest needs to be written only if we don't reuse the existing one. - Ok(!self.reuse_manifest(&descfilename, ¤t)) + Ok(!self.reuse_manifest(&descfilename, current)) } /// reuse_manifest checks whether the current manifest can be reused. @@ -755,7 +758,7 @@ impl Builder { /// copied to the supplied compaction_ptrs array. fn apply(&mut self, edit: &VersionEdit, compaction_ptrs: &mut [Vec; NUM_LEVELS]) { for c in edit.compaction_ptrs.iter() { - compaction_ptrs[c.level] = c.key.clone(); + compaction_ptrs[c.level].clone_from(&c.key); } for &(level, num) in edit.deleted.iter() { self.deleted[level].push(num); @@ -856,7 +859,7 @@ fn current_file_name>(dbname: P) -> PathBuf { dbname.as_ref().join("CURRENT").to_owned() } -pub fn read_current_file(env: &Box, dbname: &Path) -> Result { +pub fn read_current_file(env: &dyn Env, dbname: &Path) -> Result { let mut current = String::new(); let mut f = env.open_sequential_file(Path::new(¤t_file_name(dbname)))?; f.read_to_string(&mut current)?; @@ -870,7 +873,7 @@ pub fn read_current_file(env: &Box, dbname: &Path) -> Result { } pub fn set_current_file>( - env: &Box, + env: &dyn Env, dbname: P, manifest_file_num: FileNum, ) -> Result<()> { @@ -886,13 +889,13 @@ pub fn set_current_file>( if let Err(e) = env.rename(Path::new(&tempfile), Path::new(¤tfile)) { // ignore error. let _ = env.delete(Path::new(&tempfile)); - return Err(Status::from(e)); + return Err(e); } Ok(()) } /// sort_files_by_smallest sorts the list of files by the smallest keys of the files. -fn sort_files_by_smallest(cmp: &C, files: &mut Vec) { +fn sort_files_by_smallest(cmp: &C, files: &mut [FileMetaHandle]) { files.sort_by(|a, b| cmp.cmp(&a.borrow().smallest, &b.borrow().smallest)) } @@ -975,26 +978,34 @@ mod tests { use crate::version::testutil::make_version; fn example_files() -> Vec { - let mut f1 = FileMetaData::default(); - f1.num = 1; - f1.size = 10; - f1.smallest = "f".as_bytes().to_vec(); - f1.largest = "g".as_bytes().to_vec(); - let mut f2 = FileMetaData::default(); - f2.num = 2; - f2.size = 20; - f2.smallest = "e".as_bytes().to_vec(); - f2.largest = "f".as_bytes().to_vec(); - let mut f3 = FileMetaData::default(); - f3.num = 3; - f3.size = 30; - f3.smallest = "a".as_bytes().to_vec(); - f3.largest = "b".as_bytes().to_vec(); - let mut f4 = FileMetaData::default(); - f4.num = 4; - f4.size = 40; - f4.smallest = "q".as_bytes().to_vec(); - f4.largest = "z".as_bytes().to_vec(); + let f1 = FileMetaData { + num: 1, + size: 10, + smallest: b"f".to_vec(), + largest: b"g".to_vec(), + ..Default::default() + }; + let f2 = FileMetaData { + num: 2, + size: 20, + smallest: b"e".to_vec(), + largest: b"f".to_vec(), + ..Default::default() + }; + let f3 = FileMetaData { + num: 3, + size: 30, + smallest: b"a".to_vec(), + largest: b"b".to_vec(), + ..Default::default() + }; + let f4 = FileMetaData { + num: 4, + size: 40, + smallest: b"q".to_vec(), + largest: b"z".to_vec(), + ..Default::default() + }; vec![f1, f2, f3, f4].into_iter().map(share).collect() } @@ -1004,7 +1015,7 @@ mod tests { let v2 = vec![1, 3, 5, 7]; assert_eq!( vec![1, 2, 3, 4, 5, 6, 7, 8, 10], - merge_iters(v1.into_iter(), v2.into_iter(), |a, b| a.cmp(&b)) + merge_iters(v1.into_iter(), v2.into_iter(), |a, b| a.cmp(b)) ); } @@ -1017,10 +1028,7 @@ mod tests { fn test_version_set_get_range() { let cmp = DefaultCmp; let fs = example_files(); - assert_eq!( - ("a".as_bytes().to_vec(), "z".as_bytes().to_vec()), - get_range(&cmp, fs.iter()) - ); + assert_eq!((b"a".to_vec(), b"z".to_vec()), get_range(&cmp, fs.iter())); } #[test] @@ -1028,29 +1036,27 @@ mod tests { let (v, opt) = make_version(); let v = share(v); - let mut fmd = FileMetaData::default(); - fmd.num = 21; - fmd.size = 123; - fmd.smallest = LookupKey::new("klm".as_bytes(), 777) - .internal_key() - .to_vec(); - fmd.largest = LookupKey::new("kop".as_bytes(), 700) - .internal_key() - .to_vec(); + let fmd = FileMetaData { + num: 21, + size: 123, + smallest: LookupKey::new(b"klm", 777).internal_key().to_vec(), + largest: LookupKey::new(b"kop", 700).internal_key().to_vec(), + ..Default::default() + }; let mut ve = VersionEdit::new(); ve.add_file(1, fmd); // This deletion should be undone by apply(). ve.delete_file(1, 21); ve.delete_file(0, 2); - ve.set_compact_pointer(2, LookupKey::new("xxx".as_bytes(), 123).internal_key()); + ve.set_compact_pointer(2, LookupKey::new(b"xxx", 123).internal_key()); let mut b = Builder::new(); let mut ptrs: [Vec; NUM_LEVELS] = Default::default(); b.apply(&ve, &mut ptrs); assert_eq!( - &[120 as u8, 120, 120, 1, 123, 0, 0, 0, 0, 0, 0], + &[120_u8, 120, 120, 1, 123, 0, 0, 0, 0, 0, 0], ptrs[2].as_slice() ); assert_eq!(2, b.deleted[0][0]); @@ -1092,7 +1098,7 @@ mod tests { let mut lw = LogWriter::new(mffile); lw.add_record(&ve.encode()).unwrap(); lw.flush().unwrap(); - set_current_file(&opt.env.as_ref(), "db", 19).unwrap(); + set_current_file(opt.env.as_ref().as_ref(), "db", 19).unwrap(); } // Recover from new state. @@ -1110,15 +1116,13 @@ mod tests { { let mut ve = VersionEdit::new(); ve.set_log_num(11); - let mut fmd = FileMetaData::default(); - fmd.num = 21; - fmd.size = 123; - fmd.smallest = LookupKey::new("abc".as_bytes(), 777) - .internal_key() - .to_vec(); - fmd.largest = LookupKey::new("def".as_bytes(), 700) - .internal_key() - .to_vec(); + let fmd = FileMetaData { + num: 21, + size: 123, + smallest: LookupKey::new(b"abc", 777).internal_key().to_vec(), + largest: LookupKey::new(b"def", 700).internal_key().to_vec(), + ..Default::default() + }; ve.add_file(1, fmd); vs.log_and_apply(ve).unwrap(); @@ -1227,15 +1231,15 @@ mod tests { let v = vs.current(); assert_eq!( 0, - vs.approximate_offset(&v, LookupKey::new("aaa".as_bytes(), 9000).internal_key()) + vs.approximate_offset(&v, LookupKey::new(b"aaa", 9000).internal_key()) ); assert_eq!( 232, - vs.approximate_offset(&v, LookupKey::new("bab".as_bytes(), 9000).internal_key()) + vs.approximate_offset(&v, LookupKey::new(b"bab", 9000).internal_key()) ); assert_eq!( 1134, - vs.approximate_offset(&v, LookupKey::new("fab".as_bytes(), 9000).internal_key()) + vs.approximate_offset(&v, LookupKey::new(b"fab", 9000).internal_key()) ); } // The following tests reuse the same version set and verify that various compactions work @@ -1243,8 +1247,8 @@ mod tests { { time_test!("compaction tests"); // compact level 0 with a partial range. - let from = LookupKey::new("000".as_bytes(), 1000); - let to = LookupKey::new("ab".as_bytes(), 1010); + let from = LookupKey::new(b"000", 1000); + let to = LookupKey::new(b"ab", 1010); let c = vs .compact_range(0, from.internal_key(), to.internal_key()) .unwrap(); @@ -1253,8 +1257,8 @@ mod tests { assert_eq!(1, c.grandparents.unwrap().len()); // compact level 0, but entire range of keys in version. - let from = LookupKey::new("000".as_bytes(), 1000); - let to = LookupKey::new("zzz".as_bytes(), 1010); + let from = LookupKey::new(b"000", 1000); + let to = LookupKey::new(b"zzz", 1010); let c = vs .compact_range(0, from.internal_key(), to.internal_key()) .unwrap(); @@ -1268,8 +1272,8 @@ mod tests { ); // Expand input range on higher level. - let from = LookupKey::new("dab".as_bytes(), 1000); - let to = LookupKey::new("eab".as_bytes(), 1010); + let from = LookupKey::new(b"dab", 1000); + let to = LookupKey::new(b"eab", 1010); let c = vs .compact_range(1, from.internal_key(), to.internal_key()) .unwrap(); @@ -1283,8 +1287,8 @@ mod tests { ); // is_trivial_move - let from = LookupKey::new("fab".as_bytes(), 1000); - let to = LookupKey::new("fba".as_bytes(), 1010); + let from = LookupKey::new(b"fab", 1000); + let to = LookupKey::new(b"fba", 1010); let mut c = vs .compact_range(2, from.internal_key(), to.internal_key()) .unwrap(); @@ -1293,9 +1297,9 @@ mod tests { assert!(c.is_trivial_move()); // should_stop_before - let from = LookupKey::new("000".as_bytes(), 1000); - let to = LookupKey::new("zzz".as_bytes(), 1010); - let mid = LookupKey::new("abc".as_bytes(), 1010); + let from = LookupKey::new(b"000", 1000); + let to = LookupKey::new(b"zzz", 1010); + let mid = LookupKey::new(b"abc", 1010); let mut c = vs .compact_range(0, from.internal_key(), to.internal_key()) .unwrap(); @@ -1304,17 +1308,17 @@ mod tests { assert!(!c.should_stop_before(to.internal_key())); // is_base_level_for - let from = LookupKey::new("000".as_bytes(), 1000); - let to = LookupKey::new("zzz".as_bytes(), 1010); + let from = LookupKey::new(b"000", 1000); + let to = LookupKey::new(b"zzz", 1010); let mut c = vs .compact_range(0, from.internal_key(), to.internal_key()) .unwrap(); - assert!(c.is_base_level_for("aaa".as_bytes())); - assert!(!c.is_base_level_for("hac".as_bytes())); + assert!(c.is_base_level_for(b"aaa")); + assert!(!c.is_base_level_for(b"hac")); // input/add_input_deletions - let from = LookupKey::new("000".as_bytes(), 1000); - let to = LookupKey::new("zzz".as_bytes(), 1010); + let from = LookupKey::new(b"000", 1000); + let to = LookupKey::new(b"zzz", 1010); let mut c = vs .compact_range(0, from.internal_key(), to.internal_key()) .unwrap(); diff --git a/src/write_batch.rs b/src/write_batch.rs index c6f31cf..3a6a47d 100644 --- a/src/write_batch.rs +++ b/src/write_batch.rs @@ -19,7 +19,7 @@ pub struct WriteBatch { } impl WriteBatch { - pub fn new() -> WriteBatch { + pub(crate) fn new() -> WriteBatch { let mut v = Vec::with_capacity(128); v.resize(HEADER_SIZE, 0); @@ -51,7 +51,7 @@ impl WriteBatch { #[allow(unused_assignments)] pub fn delete(&mut self, k: &[u8]) { self.entries - .write(&[ValueType::TypeDeletion as u8]) + .write_all(&[ValueType::TypeDeletion as u8]) .unwrap(); self.entries.write_varint(k.len()).unwrap(); self.entries.write_all(k).unwrap(); @@ -109,6 +109,12 @@ impl WriteBatch { } } +impl Default for WriteBatch { + fn default() -> Self { + Self::new() + } +} + pub struct WriteBatchIter<'a> { batch: &'a WriteBatch, ix: usize, @@ -151,12 +157,12 @@ mod tests { #[test] fn test_write_batch() { let mut b = WriteBatch::new(); - let entries = vec![ - ("abc".as_bytes(), "def".as_bytes()), - ("123".as_bytes(), "456".as_bytes()), - ("xxx".as_bytes(), "yyy".as_bytes()), - ("zzz".as_bytes(), "".as_bytes()), - ("010".as_bytes(), "".as_bytes()), + let entries: [(&[u8], &[u8]); 5] = [ + (b"abc", b"def"), + (b"123", b"456"), + (b"xxx", b"yyy"), + (b"zzz", b""), + (b"010", b""), ]; for &(k, v) in entries.iter() {