Skip to content

Commit

Permalink
bitcoin: Compile time assert on index size
Browse files Browse the repository at this point in the history
Currently we enforce that our code only runs on machines with a certain
pointer width (32 or 64). One of the underlying reasons is because of
requirements in consensus code in Bitcoin Core which requires containers
with more than 2^16 (65536) items [0].

We can better express our requirements by asserting on Rust's index
size (the `usize` type).

As a side benefit, there is active work [1] to make Rust support
architectures where pointer width != idex size. With this patch applied
`rust-bitcoin` will function correctly even if that work progresses.

- [0] rust-bitcoin#2929 (comment)
- [1] rust-lang/rust#65473
  • Loading branch information
tcharding committed Jul 6, 2024
1 parent 1d62f04 commit 63578d9
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions bitcoin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,19 @@
#![allow(clippy::manual_range_contains)] // More readable than clippy's format.
#![allow(clippy::needless_borrows_for_generic_args)] // https://github.com/rust-lang/rust-clippy/issues/12454

// Disable 16-bit support at least for now as we can't guarantee it yet.
#[cfg(target_pointer_width = "16")]
compile_error!(
"rust-bitcoin currently only supports architectures with pointers wider than 16 bits, let us
know if you want 16-bit support. Note that we do NOT guarantee that we will implement it!"
);
use core::mem;

// We only support machines with index size of 4 or 8 bytes.
//
// Bitcoin consensus code relies on being able to have containers with more than 65536 (2^16)
// entries in them so we cannot support consensus logic on machines that only have 16-bit memory
// addresses.
//
// We specifically do not use `target_pointer_width` because of the possibility that pointer width
// does not equal index size.
//
// ref: https://github.com/rust-bitcoin/rust-bitcoin/pull/2929#discussion_r1661848565
internals::const_assert!(mem::size_of::<usize>() == 4 || mem::size_of::<usize>() == 8);

#[cfg(bench)]
extern crate test;
Expand Down

0 comments on commit 63578d9

Please sign in to comment.