]> Untitled Git - bdk/commitdiff
Fix and improve `Persist::commit` method
author志宇 <hello@evanlinjin.me>
Thu, 11 May 2023 03:49:33 +0000 (11:49 +0800)
committer志宇 <hello@evanlinjin.me>
Thu, 11 May 2023 03:49:33 +0000 (11:49 +0800)
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

index 188f88f26f4a1ad450a5d8e30fefda2008130b1e..07ff679573ba66798c0aa010ff9569a592586851 100644 (file)
@@ -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<Option<C>, 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)))
     }
 }