SafeInt.idx

Convert this value to a type suitable for indexing an array:

  • If N is signed, a ptrdiff_t is returned.
  • If N is unsigned, a size_t is returned.

checkedint.to() is used for bounds checking.

struct SafeInt(N, IntFlagPolicy _policy, Flag!"bitOps" bitOps = Yes.bitOps)
@property const @safe
Select!(isSigned!N, ptrdiff_t, size_t)
idx
()
if (
isIntegral!N &&
)

Examples

import checkedint.throws : SafeInt; // use IntFlagPolicy.throws

char[3] arr = ['a', 'b', 'c'];
SafeInt!long n = 1;

// On 32-bit, `long` cannot be used directly for array indexing,
static if (size_t.sizeof < long.sizeof)
    static assert(!__traits(compiles, arr[n]));
// but idx can be used to concisely and safely cast to ptrdiff_t:
assert(arr[n.idx] == 'b');

// The conversion is bounds checked:
static if (size_t.sizeof < long.sizeof)
{
    n = long.min;
    try
    {
        arr[n.idx] = '?';
    }
    catch (CheckedIntException e)
    {
        assert(e.intFlags == IntFlag.negOver);
    }
}

Meta