1%%
2%% %CopyrightBegin%
3%%
4%% Copyright Ericsson AB 1999-2018. All Rights Reserved.
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%% %CopyrightEnd%
19%%
20
21-module(ref_SUITE).
22
23-export([all/0, suite/0]).
24-export([wrap_1/1]).
25-export([compare_list/1, compare_ets/1]).
26
27-export([loop_ref/1]).
28
29-include_lib("common_test/include/ct.hrl").
30
31suite() ->
32    [{ct_hooks,[ts_install_cth]},
33     {timetrap, {minutes, 2}}].
34
35all() ->
36    [wrap_1, compare_list, compare_ets].
37
38%% Check that refs don't wrap around easily.
39wrap_1(Config) when is_list(Config) ->
40    spawn_link(?MODULE, loop_ref, [self()]),
41    receive
42        done ->
43            ct:fail(wrapfast)
44    after 30000 ->
45              ok
46    end,
47    ok.
48
49loop_ref(Parent) ->
50    Ref0 = make_ref(),
51    loop_ref(Ref0, first, 0),
52    Parent ! done.
53
54loop_ref(R, R, _) -> ok;
55loop_ref(R0, _, N) ->
56    loop_ref(R0, make_ref(), N+1).
57
58%% Check that ref ordering works
59compare_list(Config) when is_list(Config) ->
60    %% Although this test uses external refs, it would apply the same to plain refs
61    ExtRef1 = <<131,114,0,3,100,0,3,110,64,98,3, 0,0,173,156, 0,216,0,4, 0,0,0,0>>,
62    ExtRef2 = <<131,114,0,3,100,0,3,110,64,98,3, 0,1,31,27,   129,4,0,1, 0,0,0,0>>,
63
64    Ref1 = binary_to_term(ExtRef1), %% #Ref<n@b.0.14155780.44444>
65    Ref2 = binary_to_term(ExtRef2), %% #Ref<n@b.0.2164523009.73499>
66    OrderedList = [Ref1, Ref2],
67    OrderedList = lists:sort(OrderedList),
68    ok.
69
70%% This is the scarier case since it makes terms "invisible" in ets or Mnesia
71%% (the underlying fault cause is the same as compare_list/1)
72compare_ets(Config) when is_list(Config) ->
73    W2s = [610350147,899574699,2994196869,686384822,2397690439, 923302211],
74    ExtRefBase = <<131,114,0,3,100,0,3,110,64,98,3>>,
75    ExtRefs = [<<ExtRefBase/binary, 1:32, W2:32, 0:32>> || W2 <- W2s],
76    Refs = [binary_to_term(Bin) || Bin <- ExtRefs],
77
78    Ets = ets:new(refbug, [ordered_set]),
79    ets:insert(Ets, [{Ref,Ref} || Ref <- Refs]),
80    0 = length([R || R <- ets:tab2list(Ets), ets:lookup(Ets, element(1,R)) == []]),
81    ok.
82