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 }
Convert this value to a type suitable for indexing an array:
checkedint.to() is used for bounds checking.