Link to that code? I think I know what's wrong.
Discussion
Well this was throwaway code so I didn't commit it. Here is the current version of that function: https://github.com/vnprc/hashpool/blob/master/protocols/v2/subprotocols/mining/src/cashu.rs#L608
I went with a helper function approach. The code is much cleaner this way. It was a battle to get the u64 out of Amount but even after that I was confused about why I had to interface a u64 with a usize.
Why does core::array:from_fn use usize? I haven't really dealt with this primitive before. Is this related to CPU architecture?
#rust, she is a demanding mistress.
Digging a little deeper to understand this. Apparently, if my LLM is to be trusted, you need to index arrays with usize because they can be stored either on the stack or the heap and need to behave consistently across CPU architectures.
I didn't realize that arrays could go on the heap, but it seems this is what happens when you instantiate an array with Box, Vec, Rc, or Arc.
```
Box::new([1, 2, 3, 4, 5])
vec![1, 2, 3, 4, 5]
Rc::from([1, 2, 3, 4, 5])
Arc::from([1, 2, 3, 4, 5])
```
If only they could make the instantiation code more uniform...😅
Your new amount_to_index() function is a much better idea.
Basically all data types in Rust can go on either the array or the heap. There's some esoteric exceptions. But they're not important at your level of knowledge.
Rust was actually telling you something important with that apparently convoluted conversion: usize on many architectures is 32 bit. So you can't direct convert a u64 to a usize. You have to use a fallible conversion and deal with the potential error.
Also, Amount has a to_sats() method. So you could have used this instead:
usize.try_from(amount.to_sats()).unwrap_or(usize::MAX)
The rust-bitcoin library could also implement TryFrom to convert Amount into usize. But I suspect they won't as that's a really rare thing to do.
Thanks, Peter! I didn't know you were a rust dev. 🦀
I think you are referring to the SignedAmount type in bitcoin-rust: https://github.com/rust-bitcoin/rust-bitcoin/blob/master/units/src/amount/signed.rs#L84
cdk defines it's own amount type: https://github.com/cashubtc/cdk/blob/main/crates/cashu/src/amount.rs#L32
This `Amount` is independent of the `CurrencyUnit` type so you can use it for bitcoin, stablecoins, beefbux or whatever. I'm using it to track difficulty of mining shares.
Actually rust-bitcoin has both Amount and SignedAmount!
But yeah, same logic would apply to cdk's Amount wrapper too.
