[fpc-devel] [Suggestion] Enumeration range-check intrinsic

Martok listbox at martoks-place.de
Sat Jul 6 14:56:21 CEST 2019


Am 06.07.2019 um 09:01 schrieb Ondrej Pokorny:
> Ord(aEnum) for invalid enumeration values is undefined ;)

If there was any logic here, it should be, but it's not ;-)

The documentation page specifically mentions Ord as the older syntax to hard
casts. Whatever it contains, any enum is always smaller or equal to the largest
possible bitsize, which is Longint.


Alternatively, which should be completely equivalent but is not because Ord is
Delphi-compatible and subranges are not:

generic function TStreamHelper.ReadEnum<T>(out aEnum: T): Boolean;
var
  tmp: Ord(Low(T))..Ord(High(T)) absolute aEnum;
begin
   if Read(aEnum, SizeOf(aEnum)) <> SizeOf(aEnum) then
     Exit(False)
   else begin
     Result := (tmp >= Ord(Low(T))) and (tmp <= Ord(High(T)));
   end;
end;

This *could* be optimized out by FPC, but not by a Borland compiler.


-- 
Regards,
Martok

Ceterum censeo b32079 esse sanandam.



More information about the fpc-devel mailing list