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

Ondrej Pokorny lazarus at kluug.net
Fri Jul 5 16:48:32 CEST 2019


On 05.07.2019 14:58, Martok wrote:
> Am 05.07.2019 um 12:20 schrieb Ondrej Pokorny:
>>> Anything that even looks like a subrange cannot be used for these interfaces.
>> You may use enumerations for these interfaces - you may just not fill
>> them directly but through an integer variable in between when reading
>> from outside.
> Then you're not using them *in* the interface ;-)

For records you could use such a workaround:

program Project1;
{$mode objfpc}
{$modeswitch advancedrecords}
type
   TMyEnum = (one, two, three);
   TMyRecord = record
   public
     function IsValid: Boolean;
   public
     case Boolean of
       False: ( // real values
         Enum: TMyEnum;
       );
       True: ( // used for interface
         EnumIntf: Integer;
         {$IF SizeOf(Integer)<>SizeOf(TMyEnum)}
           {$ERROR Size mismatch}
         {$ENDIF}
       );
   end;
{ TMyRecord }
function TMyRecord.IsValid: Boolean;
begin
   Result := EnumIntf is TMyEnum;
end;

var
   R: TMyRecord;
begin
   // fill R with data ...
   Randomize;
   FillChar(R, SizeOf(R), Random(High(Byte)));
   // check validity
   if R.IsValid then
     Writeln('R is valid')
   else
     Writeln('R is not valid');
   Writeln(R.EnumIntf);
   ReadLn;
end.

Best
Ondrej



More information about the fpc-devel mailing list