bitcoindevkit / bitcoindevkit/bitcoin-ffi

Understanding the Arc optimizations

Open
#16 13 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
13
Forks
11
PR merge metrics
No merged PRs in 30d

Description

We are currently using this optimization when using Arcs (example using `TxOut`):

```rust
impl From for BitcoinTxOut {
fn from(tx_out: TxOut) -> Self {
let value = match Arc::try_unwrap(tx_out.value) {
Ok(val) => val.0,
Err(arc) => arc.0,
};

let script_pubkey = match Arc::try_unwrap(tx_out.script_pubkey) {
Ok(val) => val.0,
Err(arc) => arc.0.clone(),
};

BitcoinTxOut {
value,
script_pubkey,
}
}
}
```

I'm trying to wrap my head around how this _really_ works. Here is my rough understanding:

In the case where we have a `TxOut` type on the Kotlin side and there is only one reference to it, when we feed this type to a method that takes `TxOut`, it will de-Arc it and consume the inner value of the `Amount` type and provide it to the method that requires it.

What I'm still unclear on:

The issue I am unclear on is:
- When the Rust method that consumes the `TxOut` type returns, isn't the memory de-allocated, therefore the value inside Amount cleared?
- If that's the case but I still attempt to use the txOut variable created in Kotlin, will we have a problem? Am I miscounting the references here and the Arc will account for this somehow?

Kotlin example to show what I'm wondering about:
```kotlin
val txOut = wallet.giveMeATxOut() // some method that returns a TxOut object
importantInformation = wallet.analyzeTxOut(txOut) // the variable goes through the From pipeline and gets "de-Arc'ed"
println(txOut.value) // will this be a dangling pointer??
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.