optimize increment / increment batch

Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
Jason Volk 2024-07-02 06:24:01 +00:00
parent ee64fb149c
commit 2e2cf08bb2

View file

@ -143,54 +143,34 @@ impl Map {
Box::new(Iter::new(&self.db, &self.cf, read_options, &mode).take_while(move |(k, _)| k.starts_with(&prefix))) Box::new(Iter::new(&self.db, &self.cf, read_options, &mode).take_while(move |(k, _)| k.starts_with(&prefix)))
} }
pub fn increment(&self, key: &[u8]) -> Result<Vec<u8>> { pub fn increment(&self, key: &[u8]) -> Result<[u8; 8]> {
let read_options = &self.read_options; let old = self.get(key)?;
let old = self
.db
.db
.get_cf_opt(&self.cf(), key, read_options)
.or_else(or_else)?;
let new = utils::increment(old.as_deref()); let new = utils::increment(old.as_deref());
self.insert(key, &new)?;
let write_options = &self.write_options;
self.db
.db
.put_cf_opt(&self.cf(), key, new, write_options)
.or_else(or_else)?;
if !self.db.corked() { if !self.db.corked() {
self.db.flush()?; self.db.flush()?;
} }
Ok(new.to_vec()) Ok(new)
} }
pub fn increment_batch(&self, iter: &mut dyn Iterator<Item = Val>) -> Result<()> { pub fn increment_batch(&self, iter: &mut dyn Iterator<Item = Val>) -> Result<()> {
let mut batch = WriteBatchWithTransaction::<false>::default(); let mut batch = WriteBatchWithTransaction::<false>::default();
let read_options = &self.read_options;
for key in iter { for key in iter {
let old = self let old = self.get(&key)?;
.db
.db
.get_cf_opt(&self.cf(), &key, read_options)
.or_else(or_else)?;
let new = utils::increment(old.as_deref()); let new = utils::increment(old.as_deref());
batch.put_cf(&self.cf(), key, new); batch.put_cf(&self.cf(), key, new);
} }
let write_options = &self.write_options; let write_options = &self.write_options;
self.db let res = self.db.db.write_opt(batch, write_options);
.db
.write_opt(batch, write_options)
.or_else(or_else)?;
if !self.db.corked() { if !self.db.corked() {
self.db.flush()?; self.db.flush()?;
} }
Ok(()) result(res)
} }
pub fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> { pub fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {