[PATCH v5 04/23] rust: add new `num` module with `PowerOfTwo` type

Boqun Feng boqun.feng at gmail.com
Sat Jun 14 17:31:50 UTC 2025


On Thu, Jun 12, 2025 at 11:01:32PM +0900, Alexandre Courbot wrote:
[...]
> +/// An unsigned integer which is guaranteed to be a power of 2.
> +#[derive(Debug, Clone, Copy)]
> +#[repr(transparent)]
> +pub struct PowerOfTwo<T>(T);
> +
[...]
> +impl<T> Deref for PowerOfTwo<T> {

Why do we need `impl Deref` (and the `impl Borrow` below)? A similar
concept `NonZero` in std doesn't impl them as well.

> +    type Target = T;
> +
> +    fn deref(&self) -> &Self::Target {
> +        &self.0
> +    }
> +}
> +
> +impl<T> PartialEq for PowerOfTwo<T>

Any reason you want to impl these manually instead of deriving? For
`NonZero`, the std wants to impl these traits only for
`ZeroablePrimitive` types, but we don't have a similar trait here.


Explaining the above in the comments is much appreciated.

Regards,
Boqun

> +where
> +    T: PartialEq,
> +{
> +    fn eq(&self, other: &Self) -> bool {
> +        self.0 == other.0
> +    }
> +}
> +
> +impl<T> Eq for PowerOfTwo<T> where T: Eq {}
> +
> +impl<T> PartialOrd for PowerOfTwo<T>
> +where
> +    T: PartialOrd,
> +{
> +    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
> +        self.0.partial_cmp(&other.0)
> +    }
> +}
> +
> +impl<T> Ord for PowerOfTwo<T>
> +where
> +    T: Ord,
> +{
> +    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
> +        self.0.cmp(&other.0)
> +    }
> +}
> +
> +impl<T> Hash for PowerOfTwo<T>
> +where
> +    T: Hash,
> +{
> +    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
> +        self.0.hash(state);
> +    }
> +}
> +
> +impl<T> Borrow<T> for PowerOfTwo<T> {
> +    fn borrow(&self) -> &T {
> +        &self.0
> +    }
> +}
> 
> -- 
> 2.49.0
> 


More information about the dri-devel mailing list