Code Correctness - [ranges]

(Text mostly by Claude Opus 5.5)

Win32, Win64 and ranges


A Delphi set can hold at most 256 values, the ordinals 0 to 255. So [A..B] can only describe values in that range.

  • Constant bounds are checked by the compiler. A bound past 255 is W1012, or E1012 under {$R+}.
  • Constant bounds also keep 'in' correct. Testing an element against them, like CnPack’s Ident in [1..22], gives the right answer on both platforms, even for Ident = 257 ([experiment 38]).
  • Variable bounds are where it goes wrong.
    A bound computed at run time can be past 255, and then each bound is cut down to a byte, so it wraps mod 256:
    • 299 becomes 43,
    • 300 becomes 44,
    • 1000 becomes 232.
  • In a loop the two platforms behave the same. for var I in [A..B] with B = 1000 runs 233 times on both ([experiment 24]).
  • In a test they differ. For X in [A..B]:
    • Win32 wraps the bounds, so 100 in [0..300] asks about [0..44] and answers FALSE.
    • Win64 compares X against A and B at full width, so it answers TRUE, which is correct.
      (How each compiler does it internally is speculation)

So JVCL’s Tmp in [0..FImageList.Count - 1] is a bug when two things hold:

  • the code runs as a Win32 program;
  • the list holds more than 256 images.

The same source can give different answers on the two platforms.
$R+ turns each case into an ERangeError.
Rewriting to InRange(X, A, B) compares at full width & answers correctly on every platform.


File Earlier commits
JvListComb 2021 (a performance change), 2018–19 (uses-clause tidying)
JvFormMagnet 2015 (code style, encoding), 2011 (XE2)
JvId3v2 2010–2011

The wrapping code has passed through ten-plus years of maintenance.
JvFormMagnet’s logic dates from at least 2003, under its old name.
In practice, few image lists pass 256 entries, and FArea (a snap distance in pixels) rarely passes 255.