Skip to content

Commit

Permalink
feat(chain)!: add take convenience method to Append trait
Browse files Browse the repository at this point in the history
This is useful if the caller wishes to use the type as a staging area.

This is breaking as `Append` has a `Default` bound now.
  • Loading branch information
evanlinjin committed Jun 14, 2024
1 parent 1eca568 commit feb27df
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 12 deletions.
11 changes: 10 additions & 1 deletion crates/chain/src/tx_data_traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,21 @@ pub trait AnchorFromBlockPosition: Anchor {
}

/// Trait that makes an object appendable.
pub trait Append {
pub trait Append: Default {
/// Append another object of the same type onto `self`.
fn append(&mut self, other: Self);

/// Returns whether the structure is considered empty.
fn is_empty(&self) -> bool;

/// Take the value, replacing it with the default value.
fn take(&mut self) -> Option<Self> {
if self.is_empty() {
None
} else {
Some(core::mem::take(self))
}
}
}

impl<K: Ord, V> Append for BTreeMap<K, V> {
Expand Down
6 changes: 1 addition & 5 deletions crates/wallet/src/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2291,11 +2291,7 @@ impl Wallet {

/// Take the staged [`ChangeSet`] to be persisted now (if any).
pub fn take_staged(&mut self) -> Option<ChangeSet> {
if self.stage.is_empty() {
None
} else {
Some(core::mem::take(&mut self.stage))
}
self.stage.take()
}

/// Get a reference to the inner [`TxGraph`].
Expand Down
12 changes: 6 additions & 6 deletions example-crates/example_bitcoind_rpc_polling/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,8 @@ fn main() -> anyhow::Result<()> {
if last_db_commit.elapsed() >= DB_COMMIT_DELAY {
let db = &mut *db.lock().unwrap();
last_db_commit = Instant::now();
if !db_stage.is_empty() {
db.append_changeset(&core::mem::take(&mut db_stage))?;
if let Some(changeset) = db_stage.take() {
db.append_changeset(&changeset)?;
}
println!(
"[{:>10}s] committed to db (took {}s)",
Expand Down Expand Up @@ -235,8 +235,8 @@ fn main() -> anyhow::Result<()> {
{
let db = &mut *db.lock().unwrap();
db_stage.append((local_chain::ChangeSet::default(), graph_changeset));
if !db_stage.is_empty() {
db.append_changeset(&core::mem::take(&mut db_stage))?;
if let Some(changeset) = db_stage.take() {
db.append_changeset(&changeset)?;
}
}
}
Expand Down Expand Up @@ -325,8 +325,8 @@ fn main() -> anyhow::Result<()> {
if last_db_commit.elapsed() >= DB_COMMIT_DELAY {
let db = &mut *db.lock().unwrap();
last_db_commit = Instant::now();
if !db_stage.is_empty() {
db.append_changeset(&core::mem::take(&mut db_stage))?;
if let Some(changeset) = db_stage.take() {
db.append_changeset(&changeset)?;
}
println!(
"[{:>10}s] committed to db (took {}s)",
Expand Down

0 comments on commit feb27df

Please sign in to comment.