SmartInt.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 SmartInt(N, IntFlagPolicy _policy, Flag!"bitOps" bitOps = Yes.bitOps)
@property
Select!(isSigned!N, ptrdiff_t, size_t)
idx
const @safe
(
)
if (
isIntegral!N &&
isUnqual!N
)

Examples

1 import checkedint.throws : SmartInt; // use IntFlagPolicy.throws
2 
3 char[3] arr = ['a', 'b', 'c'];
4 SmartInt!long n = 1;
5 
6 // On 32-bit, `long` cannot be used directly for array indexing,
7 static if (size_t.sizeof < long.sizeof)
8     static assert(!__traits(compiles, arr[n]));
9 // but idx can be used to concisely and safely cast to ptrdiff_t:
10 assert(arr[n.idx] == 'b');
11 
12 // The conversion is bounds checked:
13 static if (size_t.sizeof < long.sizeof)
14 {
15     n = long.min;
16     try
17     {
18         arr[n.idx] = '?';
19     }
20     catch (CheckedIntException e)
21     {
22         assert(e.intFlags == IntFlag.negOver);
23     }
24 }

Meta