`{u,i}size_half`

This primitive integer type is half the bit-width of a usize or isize. Its purpose is to have a narrower range of values, appropriate for defining multi-dimensional collections of values.

The classic example is a rectangular matrix (2D list), which can be implemented as a Vec<Vec<T>> or as a Vec<T> with "arithmetic addressing". The maximum width or height of a "2D Vec" must be usize::MAX.isqrt() which could be losslessly casted as usize_half

While it's not perfectly typesafe, you can get a 90% solution with #[cfg(target_ptr_width = "32")] type Idx = u16; #[cfg(target_ptr_width = "64")] type Idx = u32; and as such there's no need for std to provide what's ultimately a very niche usage datatype. std/core is for broadly used vocabulary types with roughly one obvious choice of implementation tradeoffs.

8 Likes

Only if the matrix is square. Otherwise the max for either width or height (but not both at the same time) is isize::MAX. (A "clever" solution would thus be packing both extents into a single integer, plus a few bits to store the width of one extent.)

2 Likes

What about using const generics (array) rather than conditional compilation?

pub struct usize_half([u8; size_of::<usize>() / 2]);

I expect this would be more cross-platform. The only problems I see are: