Merge rust-bitcoin/rust-bitcoin#1735: Add kilo weight unit conversion

dbd2ea07b5 Add kilo weight unit conversion (yancy)

Pull request description:

  The FeeRate module defaults to sats per `kwu` so when doing fee calculations, it would be convenient to easily convert weight to the same units.

ACKs for top commit:
  Kixunil:
    ACK dbd2ea07b5
  tcharding:
    ACK dbd2ea07b5
  apoelstra:
    ACK dbd2ea07b5

Tree-SHA512: fe26b631cf474f1dca627a4d21e9052c80f8ada9a0eb635c46b7f8f42095671b9b161fb5012b723699008372faf7668507d5e92bde7d1808d389f85dba33529b
This commit is contained in:
Andrew Poelstra 2023-03-22 23:39:00 +00:00
commit 3ca9de82a6
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 22 additions and 0 deletions

View File

@ -32,6 +32,9 @@ impl Weight {
/// Directly constructs `Weight` from weight units. /// Directly constructs `Weight` from weight units.
pub const fn from_wu(wu: u64) -> Self { Weight(wu) } pub const fn from_wu(wu: u64) -> Self { Weight(wu) }
/// Constructs `Weight` from kilo weight units returning `None` if overflow occurred.
pub fn from_kwu(wu: u64) -> Option<Self> { wu.checked_mul(1000).map(Weight) }
/// Constructs `Weight` from virtual bytes. /// Constructs `Weight` from virtual bytes.
/// ///
/// # Errors /// # Errors
@ -55,6 +58,9 @@ impl Weight {
/// Can be used instead of `into()` to avoid inference issues. /// Can be used instead of `into()` to avoid inference issues.
pub const fn to_wu(self) -> u64 { self.0 } pub const fn to_wu(self) -> u64 { self.0 }
/// Converts to kilo weight units rounding down.
pub const fn to_kwu_floor(self) -> u64 { self.0 / 1000 }
/// Converts to vB rounding down. /// Converts to vB rounding down.
pub const fn to_vbytes_floor(self) -> u64 { self.0 / 4 } pub const fn to_vbytes_floor(self) -> u64 { self.0 / 4 }
@ -102,6 +108,17 @@ mod tests {
assert_eq!(Weight::ZERO, Weight::from_wu(0)); assert_eq!(Weight::ZERO, Weight::from_wu(0));
} }
#[test]
fn kilo_weight_constructor_test() {
assert_eq!(Weight(1_000), Weight::from_kwu(1).expect("expected weight unit"));
}
#[test]
#[should_panic]
fn kilo_weight_constructor_panic_test() {
Weight::from_kwu(u64::max_value()).expect("expected weight unit");
}
#[test] #[test]
fn from_vb_test() { fn from_vb_test() {
let vb = Weight::from_vb(1).expect("expected weight unit"); let vb = Weight::from_vb(1).expect("expected weight unit");
@ -132,6 +149,11 @@ mod tests {
assert_eq!(Weight(4), Weight::from_non_witness_data_size(1)); assert_eq!(Weight(4), Weight::from_non_witness_data_size(1));
} }
#[test]
fn to_kwu_floor_test() {
assert_eq!(1, Weight(1_000).to_kwu_floor());
}
#[test] #[test]
fn to_vb_floor_test() { fn to_vb_floor_test() {
assert_eq!(1, Weight(4).to_vbytes_floor()); assert_eq!(1, Weight(4).to_vbytes_floor());