From 96b10751325dc1bced09f9e864438216400e4ba3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BF=97=E5=AE=87?= Date: Thu, 11 May 2023 11:49:33 +0800 Subject: [PATCH] Fix and improve `Persist::commit` method Previously, regardless of whether writing to persistence backend is successful or not, the logic always cleared `self.staged`. This is changed to only clear `self.staged` after successful write. Additionally, the written changeset (if any) is returned, and `PersistBackend::write_changes` will not be called if `self.staged` is empty. --- crates/chain/src/persist.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/chain/src/persist.rs b/crates/chain/src/persist.rs index 188f88f26..07ff67957 100644 --- a/crates/chain/src/persist.rs +++ b/crates/chain/src/persist.rs @@ -41,11 +41,19 @@ where /// Commit the staged changes to the underlying persistance backend. /// + /// Changes that are committed (if any) are returned. + /// + /// # Error + /// /// Returns a backend-defined error if this fails. - pub fn commit(&mut self) -> Result<(), B::WriteError> { - let mut temp = C::default(); - core::mem::swap(&mut temp, &mut self.stage); - self.backend.write_changes(&temp) + pub fn commit(&mut self) -> Result, B::WriteError> { + if self.stage.is_empty() { + return Ok(None); + } + self.backend + .write_changes(&self.stage) + // if written successfully, take and return `self.stage` + .map(|_| Some(core::mem::take(&mut self.stage))) } }