Hi, I've been writting a little hash program before I come across Wrapping type. However, I found no way to convert an wrapped value back to primitive one. For e.g.:
u32::wrapping_add(1,Wrapping(2).into());
just generates an error:
the trait `std::convert::From<std::num::Wrapping<u32>>` is not implemented for `u32`
= help: the following implementations were found:
<u32 as std::convert::From<bool>>
<u32 as std::convert::From<char>>
<u32 as std::convert::From<std::net::Ipv4Addr>>
<u32 as std::convert::From<std::num::NonZeroU32>>
and 2 others
= note: required because of the requirements on the impl of `std::convert::Into<u32>` for `std::num::Wrapping<u32>`
I'm not very familiar with the From and Into trait. AFAIK without std::convert::From<std::num::Wrapping<u32>> I can never do the conversion I want. I've checked Wrapping type's methods, but none of them seems to do the job.
u32::wrapping_add is another way of saying Wrapping::<u32>::add, because u32::add is by default non-wrapping and panics on overflow, while Wrapping is a wrapper which wraps on overflow.
Therefore Wrapping(254_u8) + Wrapping(2_u8) is equivalent to u8::wrapping_add(254_u8, 2_u8).
To get the value out of a Wrapping use my_wrapping.0.
.0 is the way to access stuff from a tuple struct. Wrapping is a really simple type that is defined like this
pub struct Wrapping<T>(pub T);
And has specific impls for the arithmetic operators to do wrap on overflow instead of panic on overflow by deferring to the appropriate wrapping_* method on the integers.
@TomP@RustyYato
Thank you for your reply, Actually I'm searching for any documentation on the implemention of Wrapping type. If it's documented as just a Tuple, it would be (at least feels like to) safer to use the .0 way.
I know I can check the source code directly. But I kind don't want to rely on inner details.
Anyway the problem is solved. Hope the implementation of Wrapping remains unchanged in future releases.