|
| 1 | +% |
| 2 | +% This file is part of AtomVM. |
| 3 | +% |
| 4 | +% Copyright 2024 Tomasz Sobkiewicz <tomasz.sobkiewt> |
| 5 | +% |
| 6 | +% Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +% you may not use this file except in compliance with the License. |
| 8 | +% You may obtain a copy of the License at |
| 9 | +% |
| 10 | +% http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +% |
| 12 | +% Unless required by applicable law or agreed to in writing, software |
| 13 | +% distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +% See the License for the specific language governing permissions and |
| 16 | +% limitations under the License. |
| 17 | +% |
| 18 | +% SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later |
| 19 | +% |
| 20 | + |
| 21 | +-module(is_record). |
| 22 | + |
| 23 | +-record(person, {id, name, age}). |
| 24 | + |
| 25 | +-export([start/0, id/1, is_person/1, fail_with_badarg/1]). |
| 26 | + |
| 27 | +-define(ID(Arg), ?MODULE:id(Arg)). |
| 28 | + |
| 29 | +start() -> |
| 30 | + Mike = #person{ |
| 31 | + id = 1, |
| 32 | + name = "Mike", |
| 33 | + age = 32 |
| 34 | + }, |
| 35 | + IsRecord = ?ID(fun erlang:is_record/2), |
| 36 | + true = IsRecord(?ID({person, 1, 2, 3}), ?ID(person)), |
| 37 | + true = erlang:is_record(?ID({person, 1, 2, 3}), ?ID(person)), |
| 38 | + true = erlang:is_record(?ID({person}), ?ID(person)), |
| 39 | + true = erlang:is_record(?ID(Mike), ?ID(person)), |
| 40 | + true = ?MODULE:is_person(?ID(Mike)), |
| 41 | + |
| 42 | + false = ?MODULE:is_person(?ID({tuple, 1, 2})), |
| 43 | + false = erlang:is_record(?ID(Mike), ?ID(foo)), |
| 44 | + false = erlang:is_record(?ID({person, 1, 2, 3}), ?ID(foo)), |
| 45 | + false = erlang:is_record(?ID({}), ?ID(person)), |
| 46 | + false = erlang:is_record(?ID([]), ?ID(person)), |
| 47 | + ok = fail_with_badarg(fun() -> erlang:is_record(?ID(Mike), ?ID(1)) end), |
| 48 | + ok = fail_with_badarg(fun() -> erlang:is_record(?ID({}), ?ID(1)) end), |
| 49 | + 0. |
| 50 | + |
| 51 | +id(T) -> |
| 52 | + T. |
| 53 | + |
| 54 | +is_person(T) when is_record(T, person) -> true; |
| 55 | +is_person(_X) -> false. |
| 56 | + |
| 57 | +fail_with_badarg(Fun) -> |
| 58 | + try Fun() of |
| 59 | + Ret -> {unexpected, Ret} |
| 60 | + catch |
| 61 | + error:badarg -> ok; |
| 62 | + C:E -> {unexpected, C, E} |
| 63 | + end. |
0 commit comments