From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on polar.synack.me X-Spam-Level: X-Spam-Status: No, score=-1.3 required=5.0 tests=BAYES_00,INVALID_MSGID autolearn=no autolearn_force=no version=3.4.4 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 103376,45a9122ddf5fcf5 X-Google-Attributes: gid103376,public From: ka@socrates.hr.att.com (Kenneth Almquist) Subject: Re: Valid Attribute and Unchecked Conversion Date: 1996/10/07 Message-ID: <539un2$mha@nntpa.cb.lucent.com>#1/1 X-Deja-AN: 187236530 references: <1996Oct1.100608.1@eisner> organization: Lucent Technologies, Columbus, Ohio newsgroups: comp.lang.ada Date: 1996-10-07T00:00:00+00:00 List-Id: kst@thomsoft.com (Keith Thompson) writes: > RM95-13.9.1(12) says: > > A call to an imported function or an instance of > Unchecked_Conversion is erroneous if the result > is scalar, and the result object has an invalid > representation. [snip] > So, suppose I have a sparse enumeration type: > > type Enum is (Ten, Twenty, Thirty); > for Enum use (10, 20, 30); > for Enum'Size use 8; > > and a corresponding integer type: > > type Int_Type is range 0 .. 31; > for Int_Type'Size use 8; > > Given an arbitrary value of type Int_Type, is there any non-erroneous > way to get the corresponding Enum value if there is one, or raise > an exception if there isn't? By "corresponding", I mean 10 => Ten, > 20 => Twenty, 30 => Thirty. Do an unchecked conversion to a nonscalar type. -- Convert Int_Type to Enum, raising constraint error if the result is -- invalid. function To_Enum(I : Int_Type) return Enum is type Wrapped_Enum is record Value : Enum; end record; for Wrapped_Enum'size use Enum'size; function To_Wrapped_Enum is new Ada.Unchecked_Conversion(Int_Type, Wrapped_Enum); W : Wrapped_Enum; begin W := To_Wrapped_Enum(I); if W.Value'valid then return W.Value; else raise Constraint_Error; end if; end To_Enum;