Type Alias CheckedUint32

Source
pub type CheckedUint32 = CheckedInt<u32>;
Expand description

@class CheckedInt @brief Integer wrapper class checking for integer overflow and other errors @param T the integer type to wrap. Can be any type among the following: - any basic integer type such as |int| - any stdint type such as |int8_t|

This class implements guarded integer arithmetic. Do a computation, check that isValid() returns true, you then have a guarantee that no problem, such as integer overflow, happened during this computation, and you can call value() to get the plain integer value.

The arithmetic operators in this class are guaranteed not to raise a signal (e.g. in case of a division by zero).

For example, suppose that you want to implement a function that computes (aX+aY)/aZ, that doesn’t crash if aZ==0, and that reports on error (divide by zero or integer overflow). You could code it as follows: @code bool computeXPlusYOverZ(int aX, int aY, int aZ, int* aResult) { CheckedInt checkedResult = (CheckedInt(aX) + aY) / aZ; if (checkedResult.isValid()) { aResult = checkedResult.value(); return true; } else { return false; } } @endcode

Implicit conversion from plain integers to checked integers is allowed. The plain integer is checked to be in range before being casted to the destination type. This means that the following lines all compile, and the resulting CheckedInts are correctly detected as valid or invalid: @code // 1 is of type int, is found to be in range for uint8_t, x is valid CheckedInt<uint8_t> x(1); // -1 is of type int, is found not to be in range for uint8_t, x is invalid CheckedInt<uint8_t> x(-1); // -1 is of type int, is found to be in range for int8_t, x is valid CheckedInt<int8_t> x(-1); // 1000 is of type int16_t, is found not to be in range for int8_t, // x is invalid CheckedInt<int8_t> x(int16_t(1000)); // 3123456789 is of type uint32_t, is found not to be in range for int32_t, // x is invalid CheckedInt<int32_t> x(uint32_t(3123456789)); @endcode Implicit conversion from checked integers to plain integers is not allowed. As shown in the above example, to get the value of a checked integer as a normal integer, call value().

Arithmetic operations between checked and plain integers is allowed; the result type is the type of the checked integer.

Checked integers of different types cannot be used in the same arithmetic expression.

There are convenience typedefs for all stdint types, of the following form (these are just 2 examples): @code typedef CheckedInt<int32_t> CheckedInt32; typedef CheckedInt<uint16_t> CheckedUint16; @endcode

Aliased Type§

#[repr(C)]
pub struct CheckedUint32 { pub _phantom_0: PhantomData<UnsafeCell<u32>>, pub mValue: u32, pub mIsValid: bool, }

Fields§

§_phantom_0: PhantomData<UnsafeCell<u32>>§mValue: u32§mIsValid: bool