ynn
ynn

Reputation: 4815

How to get the number of bits of usize in older version of Rust?

In 2022, I sometimes have to use Rust 1.42.0 (released in 2020) in remote environment.

How to get the number of bits of usize in that old version of Rust?

I once encountered a similar problem where I wanted to access the max value of usize but found usize::MAX doesn't exist in Rust 1.42.0. At that time, I found std::usize::MAX had already existed in 1.42.0. However, inconsistently, std::usize::BITS doesn't exist.

Newer Rust Rust 1.42.0
max value usize::MAX (Rust 1.43.0 or newer) std::usize::MAX or usize::max_value()
min value usize::MIN (Rust 1.43.0 or newer) std::usize::MIN or usize::min_value()
# of bits usize::BITS (Rust 1.53.0 or newer) None of std::usize::BITS or usize::bits_value() exists.

Upvotes: 1

Views: 968

Answers (1)

ynn
ynn

Reputation: 4815

As far as I know, there is no built-in simple method like usize::BITS or usize::bits_value().

You have to use a relatively low-level operation to directly calculate the number of bits:

let bits = std::mem::size_of::<usize>() * 8;

(However, note usize::BITS is of type u32 while size_of() returns usize.)

According to the related pull request (Add associated constant BITS to all integer types #76492), it seems this inconvenience is why usize::BITS is added in Rust 1.53.0 in the first place.

Upvotes: 2

Related Questions