Why the return type of `int.leading_zeros` is `u32` of `u8`?

Now that its value won't exceed 128?

(I guess the question might have been discussed somewhere, but I cannot search that out.)

I'm not entirely sure, but I think the underlying instruction returns it in that type. I suppose that u32 is a rather nice default size for integers.

@alice Thanks for your reply.

I'm not entirely sure, but I think the underlying instruction returns it in that type.

But it seems that it is converted to u32 manually.

I suppose that u32 is a rather nice default size for integers.

In my view, the integer type with the most number of bits is u128/i128. And u8 can hold 0-255 which is sufficient?

It's also a type that wastes at least 75% of the space used for the return value with a probability of 100%.

So it would seem like a good idea to deprecate this function and replace it with an identical one that has a u8 return type.

What if they decide to add a u256/i256?

We will need a way to represent 256 for the function applied to number 0, which clearly needs 9 bits at least.

2 Likes

No offense but what does this even mean?

(0u256).leading_zeroes() == 256

Ah now I see. Well the thing about that is that we can stretch it up arbitrarily far: how about when we consider a hypothetical 0u1024? The line has to be drawn somewhere, or (and maybe this is even preferable) an entirely different scheme is needed where .leading_zeroes() becomes a trait method with a trait signature like

pub trait LeadingZeroes {
  type Output = Self; // type defaults aren't stable yet, but this would make sense

  fn leading_zeroes(&self) -> Self::Output;
} 

I think the answer by @brunoczim is reasonable.

@jjpe See https://en.wikipedia.org/wiki/Orders_of_magnitude_(numbers) . Even for 0u1024, the u32 is sufficient in such cases because log[2, 1024] = 10 < 32. And (2^32)^2 seems to be large enough in the foreseeable future.

1 Like

Yes, this is a mistake I see made again and again in the IT industry as a whole. IP addresses. Time representations in eg kernels (y2k anyone?). All manifestations of the same mistake.

A trait would solve the problem in a forwards compatible way for now and forever. An int with a specified width does not.

What, are you building computers for gods? This is a thing of completely different kind from stating that 32 bits is enough to hold all IP addresses. 2^(2^32) is an egregiously large number.