[fpc-devel] [Suggestion] Enumeration range-check intrinsic
J. Gareth Moreton
gareth at moreton-family.com
Fri Jul 5 06:53:55 CEST 2019
Okay, I've done some preliminary testing, and "if Value < Low(TMyEnum)
then" and "if Value > High(TMyEnum) then" work as expected and aren't
optimised out, even when using -O4 -Cr. So admittedly there is still a
way to check to see if the enumeration is within the valid range, at
least for now. I'm not sure if the compiler will be changed so this
would be optimised out (in which case, an intrinsic or "is" would be
necessary).
I do think one needs to put in a clear warning in the documentation for
'case' so developers who do fall foul of the slightly counterintuitive
behaviour have a means to work around it.
This was my test, written in a way so I couldn't be told off for using
'absolute', pointers or assembly language and is comparable to a
real-world example of reading an enumeration from a data stream:
----
program EnumTest;
uses
Classes;
type
TMyEnum = (meOff = 1, meLowered, meStowed);
const
ByteSequence: array[0..5] of Byte = (0, 2, 4, 127, 128, 255);
var
Stream: TMemoryStream;
EnumVal: TMyEnum;
X: Integer;
begin
Stream := TMemoryStream.Create;
try
{ Fill the memory stream }
Stream.SetSize(Length(ByteSequence));
Stream.Write(ByteSequence, Length(ByteSequence));
Stream.Seek(0, soBeginning);
{ Okay, now read back the values }
while Stream.Read(EnumVal, 1) > 0 do
begin
if EnumVal < Low(TMyEnum) then
WriteLn('Below valid range')
else if EnumVal > High(TMyEnum) then
WriteLn('Above valid range')
else
WriteLn(EnumVal);
end;
finally
Stream.Free;
end;
end.
----
If I make the enumeration non-contiguous and try to call
WriteLn(EnumVal) with an invalid value that is otherwise still within
the lower and upper bounds, then I do get an exception, which is to be
expected - "EInOutError: Unknown Run-Time error : 107" - the only real
fault with it is that it's listed as an unknown error. If an intrinsic
or "is" is accepted as a convenient shortcut for the bounds check, it
should probably catch values that fall within these gaps.
Gareth aka. Kit
---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus
More information about the fpc-devel
mailing list