-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
array.erl
1910 lines (1622 loc) · 62.4 KB
/
array.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% Copyright (C) 2006-2016 Richard Carlsson and Ericsson AB
%%
%% @author Richard Carlsson <carlsson.richard@gmail.com>
%% @author Dan Gudmundsson <dgud@erix.ericsson.se>
%%
%% @doc Functional, extendible arrays. Arrays can have fixed size, or
%% can grow automatically as needed. A default value is used for entries
%% that have not been explicitly set.
%%
%% Arrays uses <b>zero</b> based indexing. This is a deliberate design
%% choice and differs from other erlang datastructures, e.g. tuples.
%%
%% Unless specified by the user when the array is created, the default
%% value is the atom `undefined'. There is no difference between an
%% unset entry and an entry which has been explicitly set to the same
%% value as the default one (cf. {@link reset/2}). If you need to
%% differentiate between unset and set entries, you must make sure that
%% the default value cannot be confused with the values of set entries.
%%
%% The array never shrinks automatically; if an index `I' has been used
%% successfully to set an entry, all indices in the range [0,`I'] will
%% stay accessible unless the array size is explicitly changed by
%% calling {@link resize/2}.
%%
%% Examples:
%% ```
%% %% Create a fixed-size array with entries 0-9 set to 'undefined'
%% A0 = array:new(10).
%% 10 = array:size(A0).
%%
%% %% Create an extendible array and set entry 17 to 'true',
%% %% causing the array to grow automatically
%% A1 = array:set(17, true, array:new()).
%% 18 = array:size(A1).
%%
%% %% Read back a stored value
%% true = array:get(17, A1).
%%
%% %% Accessing an unset entry returns the default value
%% undefined = array:get(3, A1).
%%
%% %% Accessing an entry beyond the last set entry also returns the
%% %% default value, if the array does not have fixed size
%% undefined = array:get(18, A1).
%%
%% %% "sparse" functions ignore default-valued entries
%% A2 = array:set(4, false, A1).
%% [{4, false}, {17, true}] = array:sparse_to_orddict(A2).
%%
%% %% An extendible array can be made fixed-size later
%% A3 = array:fix(A2).
%%
%% %% A fixed-size array does not grow automatically and does not
%% %% allow accesses beyond the last set entry
%% {'EXIT',{badarg,_}} = (catch array:set(18, true, A3)).
%% {'EXIT',{badarg,_}} = (catch array:get(18, A3)).
%% '''
%% @type array(). A functional, extendible array. The representation is
%% not documented and is subject to change without notice. Note that
%% arrays cannot be directly compared for equality.
-module(array).
-export([new/0, new/1, new/2, is_array/1, set/3, get/2, size/1,
sparse_size/1, default/1, reset/2, to_list/1, sparse_to_list/1,
from_list/1, from_list/2, to_orddict/1, sparse_to_orddict/1,
from_orddict/1, from_orddict/2, map/2, sparse_map/2, foldl/3,
foldr/3, sparse_foldl/3, sparse_foldr/3, fix/1, relax/1, is_fix/1,
resize/1, resize/2]).
-export_type([array/0, array/1]).
%%-define(TEST,1).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
%% Developers:
%%
%% For OTP devs: Both tests and documentation is extracted from this
%% file, keep and update this file,
%% test are extracted with array_SUITE:extract_tests().
%% Doc with docb_gen array.erl
%%
%% The key to speed is to minimize the number of tests, on
%% large input. Always make the most probable path as short as possible.
%% In particular, keep in mind that for large trees, the probability of
%% a leaf node is small relative to that of an internal node.
%%
%% If you try to tweak the set_1 and get_1 loops: Measure, look at the
%% generated Beam code, and measure again! The argument order matters!
%% Representation:
%%
%% A tree is either a leaf, with LEAFSIZE elements (the "base"), an
%% internal node with LEAFSIZE+1 elements, or an unexpanded tree,
%% represented by a single integer: the number of elements that may be
%% stored in the tree when it is expanded. The last element of an
%% internal node caches the number of elements that may be stored in
%% each of its subtrees.
%%
%% Note that to update an entry in a tree of height h = log[b] n, the
%% total number of written words is (b+1)+(h-1)*(b+2), since tuples use
%% a header word on the heap. 4 is the optimal base for minimizing the
%% number of words written, but causes higher trees, which takes time.
%% The best compromise between speed and memory usage seems to lie
%% around 8-10. Measurements indicate that the optimum base for speed is
%% 24 - above that, it gets slower again due to the high memory usage.
%% Base 10 is a good choice, giving 2/3 of the possible speedup from
%% base 4, but only using 1/3 more memory. (Base 24 uses 65% more memory
%% per write than base 10, but the speedup is only 21%.)
-define(DEFAULT, undefined).
-define(LEAFSIZE, 10). % the "base"
-define(NODESIZE, ?LEAFSIZE). % (no reason to have a different size)
-define(NODEPATTERN(S), {_,_,_,_,_,_,_,_,_,_,S}). % NODESIZE+1 elements!
-define(NEW_NODE(S), % beware of argument duplication!
setelement((?NODESIZE+1),erlang:make_tuple((?NODESIZE+1),(S)),(S))).
-define(NEW_LEAF(D), erlang:make_tuple(?LEAFSIZE,(D))).
-define(NODELEAFS, ?NODESIZE*?LEAFSIZE).
%% These make the code a little easier to experiment with.
%% It turned out that using shifts (when NODESIZE=2^n) was not faster.
-define(reduce(X), ((X) div (?NODESIZE))).
-define(extend(X), ((X) * (?NODESIZE))).
%%--------------------------------------------------------------------------
-type element_tuple(T) ::
{T, T, T, T, T, T, T, T, T, T}
| {element_tuple(T), element_tuple(T), element_tuple(T),
element_tuple(T), element_tuple(T), element_tuple(T),
element_tuple(T), element_tuple(T), element_tuple(T),
element_tuple(T), non_neg_integer()}.
-type elements(T) :: non_neg_integer()
| element_tuple(T)
| nil(). % kill reference, for GC
-record(array, {size :: non_neg_integer(), %% number of defined entries
max :: non_neg_integer(), %% maximum number of entries
%% in current tree
default, %% the default value (usually 'undefined')
elements :: elements(_) %% the tuple tree
}).
-type array() :: array(term()).
-opaque array(Type) ::
#array{default :: Type, elements :: elements(Type)}.
%%
%% Types
%%
-type array_indx() :: non_neg_integer().
-type array_opt() :: {'fixed', boolean()} | 'fixed'
| {'default', Type :: term()}
| {'size', N :: non_neg_integer()}
| (N :: non_neg_integer()).
-type array_opts() :: array_opt() | [array_opt()].
-type indx_pair(Type) :: {Index :: array_indx(), Type}.
-type indx_pairs(Type) :: [indx_pair(Type)].
%%--------------------------------------------------------------------------
%% @doc Create a new, extendible array with initial size zero.
%% @equiv new([])
%%
%% @see new/1
%% @see new/2
-spec new() -> array().
new() ->
new([]).
%% @doc Create a new array according to the given options. By default,
%% the array is extendible and has initial size zero. Array indices
%% start at 0.
%%
%% `Options' is a single term or a list of terms, selected from the
%% following:
%% <dl>
%% <dt>`N::integer()' or `{size, N::integer()}'</dt>
%% <dd>Specifies the initial size of the array; this also implies
%% `{fixed, true}'. If `N' is not a nonnegative integer, the call
%% fails with reason `badarg'.</dd>
%% <dt>`fixed' or `{fixed, true}'</dt>
%% <dd>Creates a fixed-size array; see also {@link fix/1}.</dd>
%% <dt>`{fixed, false}'</dt>
%% <dd>Creates an extendible (non fixed-size) array.</dd>
%% <dt>`{default, Value}'</dt>
%% <dd>Sets the default value for the array to `Value'.</dd>
%% </dl>
%% Options are processed in the order they occur in the list, i.e.,
%% later options have higher precedence.
%%
%% The default value is used as the value of uninitialized entries, and
%% cannot be changed once the array has been created.
%%
%% Examples:
%% ```array:new(100)''' creates a fixed-size array of size 100.
%% ```array:new({default,0})''' creates an empty, extendible array
%% whose default value is 0.
%% ```array:new([{size,10},{fixed,false},{default,-1}])''' creates an
%% extendible array with initial size 10 whose default value is -1.
%%
%% @see new/0
%% @see new/2
%% @see set/3
%% @see get/2
%% @see from_list/2
%% @see fix/1
-spec new(Options :: array_opts()) -> array().
new(Options) ->
new_0(Options, 0, false).
%% @doc Create a new array according to the given size and options. If
%% `Size' is not a nonnegative integer, the call fails with reason
%% `badarg'. By default, the array has fixed size. Note that any size
%% specifications in `Options' will override the `Size' parameter.
%%
%% If `Options' is a list, this is simply equivalent to `new([{size,
%% Size} | Options]', otherwise it is equivalent to `new([{size, Size} |
%% [Options]]'. However, using this function directly is more efficient.
%%
%% Example:
%% ```array:new(100, {default,0})''' creates a fixed-size array of size
%% 100, whose default value is 0.
%%
%% @see new/1
-spec new(Size :: non_neg_integer(), Options :: array_opts()) -> array().
new(Size, Options) when is_integer(Size), Size >= 0 ->
new_0(Options, Size, true);
new(_, _) ->
erlang:error(badarg).
new_0(Options, Size, Fixed) when is_list(Options) ->
new_1(Options, Size, Fixed, ?DEFAULT);
new_0(Options, Size, Fixed) ->
new_1([Options], Size, Fixed, ?DEFAULT).
new_1([fixed | Options], Size, _, Default) ->
new_1(Options, Size, true, Default);
new_1([{fixed, Fixed} | Options], Size, _, Default)
when is_boolean(Fixed) ->
new_1(Options, Size, Fixed, Default);
new_1([{default, Default} | Options], Size, Fixed, _) ->
new_1(Options, Size, Fixed, Default);
new_1([{size, Size} | Options], _, _, Default)
when is_integer(Size), Size >= 0 ->
new_1(Options, Size, true, Default);
new_1([Size | Options], _, _, Default)
when is_integer(Size), Size >= 0 ->
new_1(Options, Size, true, Default);
new_1([], Size, Fixed, Default) ->
new(Size, Fixed, Default);
new_1(_Options, _Size, _Fixed, _Default) ->
erlang:error(badarg).
new(0, false, undefined) ->
%% Constant empty array
#array{size=0, max=?LEAFSIZE, elements=?LEAFSIZE};
new(Size, Fixed, Default) ->
E = find_max(Size - 1, ?LEAFSIZE),
M = if Fixed -> 0;
true -> E
end,
#array{size = Size, max = M, default = Default, elements = E}.
-spec find_max(integer(), non_neg_integer()) -> non_neg_integer().
find_max(I, M) when I >= M ->
find_max(I, ?extend(M));
find_max(_I, M) ->
M.
%% @doc Returns `true' if `X' appears to be an array, otherwise `false'.
%% Note that the check is only shallow; there is no guarantee that `X'
%% is a well-formed array representation even if this function returns
%% `true'.
-spec is_array(X :: term()) -> boolean().
is_array(#array{size = Size, max = Max})
when is_integer(Size), is_integer(Max) ->
true;
is_array(_) ->
false.
%% @doc Get the number of entries in the array. Entries are numbered
%% from 0 to `size(Array)-1'; hence, this is also the index of the first
%% entry that is guaranteed to not have been previously set.
%% @see set/3
%% @see sparse_size/1
-spec size(Array :: array()) -> non_neg_integer().
size(#array{size = N}) -> N;
size(_) -> erlang:error(badarg).
%% @doc Get the value used for uninitialized entries.
%%
%% @see new/2
-spec default(Array :: array(Type)) -> Value :: Type.
default(#array{default = D}) -> D;
default(_) -> erlang:error(badarg).
-ifdef(EUNIT).
new_test_() ->
N0 = ?LEAFSIZE,
N01 = N0+1,
N1 = ?NODESIZE*N0,
N11 = N1+1,
N2 = ?NODESIZE*N1,
[?_test(new()),
?_test(new([])),
?_test(new(10)),
?_test(new({size,10})),
?_test(new(fixed)),
?_test(new({fixed,true})),
?_test(new({fixed,false})),
?_test(new({default,undefined})),
?_test(new([{size,100},{fixed,false},{default,undefined}])),
?_test(new([100,fixed,{default,0}])),
?_assert(new() =:= new([])),
?_assert(new() =:= new([{size,0},{default,undefined},{fixed,false}])),
?_assert(new() =:= new(0, {fixed,false})),
?_assert(new(fixed) =:= new(0)),
?_assert(new(fixed) =:= new(0, [])),
?_assert(new(10) =:= new([{size,0},{size,5},{size,10}])),
?_assert(new(10) =:= new(0, {size,10})),
?_assert(new(10, []) =:= new(10, [{default,undefined},{fixed,true}])),
?_assertError(badarg, new(-1)),
?_assertError(badarg, new(10.0)),
?_assertError(badarg, new(undefined)),
?_assertError(badarg, new([undefined])),
?_assertError(badarg, new([{default,0} | fixed])),
?_assertError(badarg, new(-1, [])),
?_assertError(badarg, new(10.0, [])),
?_assertError(badarg, new(undefined, [])),
?_assertMatch(#array{size=0,max=N0,default=undefined,elements=N0},
new()),
?_assertMatch(#array{size=0,max=0,default=undefined,elements=N0},
new(fixed)),
?_assertMatch(#array{size=N0,max=N0,elements=N0},
new(N0, {fixed,false})),
?_assertMatch(#array{size=N01,max=N1,elements=N1},
new(N01, {fixed,false})),
?_assertMatch(#array{size=N1,max=N1,elements=N1},
new(N1, {fixed,false})),
?_assertMatch(#array{size=N11,max=N2,elements=N2},
new(N11, {fixed,false})),
?_assertMatch(#array{size=N2, max=N2, default=42,elements=N2},
new(N2, [{fixed,false},{default,42}])),
?_assert(0 =:= array:size(new())),
?_assert(17 =:= array:size(new(17))),
?_assert(100 =:= array:size(array:set(99,0,new()))),
?_assertError(badarg, array:size({bad_data,gives_error})),
?_assert(undefined =:= default(new())),
?_assert(4711 =:= default(new({default,4711}))),
?_assert(0 =:= default(new(10, {default,0}))),
?_assertError(badarg, default({bad_data,gives_error})),
?_assert(is_array(new())),
?_assert(false =:= is_array({foobar, 23, 23})),
?_assert(false =:= is_array(#array{size=bad})),
?_assert(false =:= is_array(#array{max=bad})),
?_assert(is_array(new(10))),
?_assert(is_array(new(10, {fixed,false})))
].
-endif.
%% @doc Fix the size of the array. This prevents it from growing
%% automatically upon insertion; see also {@link set/3}.
%% @see relax/1
-spec fix(Array :: array(Type)) -> array(Type).
fix(#array{}=A) ->
A#array{max = 0}.
%% @doc Check if the array has fixed size.
%% Returns `true' if the array is fixed, otherwise `false'.
%% @see fix/1
-spec is_fix(Array :: array()) -> boolean().
is_fix(#array{max = 0}) -> true;
is_fix(#array{}) -> false.
-ifdef(EUNIT).
fix_test_() ->
[?_assert(is_array(fix(new()))),
?_assert(fix(new()) =:= new(fixed)),
?_assertNot(is_fix(new())),
?_assertNot(is_fix(new([]))),
?_assertNot(is_fix(new({fixed,false}))),
?_assertNot(is_fix(new(10, {fixed,false}))),
?_assert(is_fix(new({fixed,true}))),
?_assert(is_fix(new(fixed))),
?_assert(is_fix(new(10))),
?_assert(is_fix(new(10, []))),
?_assert(is_fix(new(10, {fixed,true}))),
?_assert(is_fix(fix(new()))),
?_assert(is_fix(fix(new({fixed,false})))),
?_test(set(0, 17, new())),
?_assertError(badarg, set(0, 17, new(fixed))),
?_assertError(badarg, set(1, 42, fix(set(0, 17, new())))),
?_test(set(9, 17, new(10))),
?_assertError(badarg, set(10, 17, new(10))),
?_assertError(badarg, set(10, 17, fix(new(10, {fixed,false}))))
].
-endif.
%% @doc Make the array resizable. (Reverses the effects of {@link
%% fix/1}.)
%% @see fix/1
-spec relax(Array :: array(Type)) -> array(Type).
relax(#array{size = N}=A) ->
A#array{max = find_max(N-1, ?LEAFSIZE)}.
-ifdef(EUNIT).
relax_test_() ->
[?_assert(is_array(relax(new(fixed)))),
?_assertNot(is_fix(relax(fix(new())))),
?_assertNot(is_fix(relax(new(fixed)))),
?_assert(new() =:= relax(new(fixed))),
?_assert(new() =:= relax(new(0))),
?_assert(new(17, {fixed,false}) =:= relax(new(17))),
?_assert(new(100, {fixed,false})
=:= relax(fix(new(100, {fixed,false}))))
].
-endif.
%% @doc Change the size of the array. If `Size' is not a nonnegative
%% integer, the call fails with reason `badarg'. If the given array has
%% fixed size, the resulting array will also have fixed size.
-spec resize(Size :: non_neg_integer(), Array :: array(Type)) ->
array(Type).
resize(Size, #array{size = N, max = M, elements = E}=A)
when is_integer(Size), Size >= 0 ->
if Size > N ->
{E1, M1} = grow(Size-1, E,
if M > 0 -> M;
true -> find_max(N-1, ?LEAFSIZE)
end),
A#array{size = Size,
max = if M > 0 -> M1;
true -> M
end,
elements = E1};
Size < N ->
%% TODO: shrink physical representation when shrinking the array
A#array{size = Size};
true ->
A
end;
resize(_Size, _) ->
erlang:error(badarg).
%% @doc Change the size of the array to that reported by {@link
%% sparse_size/1}. If the given array has fixed size, the resulting
%% array will also have fixed size.
%% @equiv resize(sparse_size(Array), Array)
%% @see resize/2
%% @see sparse_size/1
-spec resize(Array :: array(Type)) -> array(Type).
resize(Array) ->
resize(sparse_size(Array), Array).
-ifdef(EUNIT).
resize_test_() ->
[?_assert(resize(0, new()) =:= new()),
?_assert(resize(99, new(99)) =:= new(99)),
?_assert(resize(99, relax(new(99))) =:= relax(new(99))),
?_assert(is_fix(resize(100, new(10)))),
?_assertNot(is_fix(resize(100, relax(new(10))))),
?_assert(array:size(resize(100, new())) =:= 100),
?_assert(array:size(resize(0, new(100))) =:= 0),
?_assert(array:size(resize(99, new(10))) =:= 99),
?_assert(array:size(resize(99, new(1000))) =:= 99),
?_assertError(badarg, set(99, 17, new(10))),
?_test(set(99, 17, resize(100, new(10)))),
?_assertError(badarg, set(100, 17, resize(100, new(10)))),
?_assert(array:size(resize(new())) =:= 0),
?_assert(array:size(resize(new(8))) =:= 0),
?_assert(array:size(resize(array:set(7, 0, new()))) =:= 8),
?_assert(array:size(resize(array:set(7, 0, new(10)))) =:= 8),
?_assert(array:size(resize(array:set(99, 0, new(10,{fixed,false}))))
=:= 100),
?_assert(array:size(resize(array:set(7, undefined, new()))) =:= 0),
?_assert(array:size(resize(array:from_list([1,2,3,undefined])))
=:= 3),
?_assert(array:size(
resize(array:from_orddict([{3,0},{17,0},{99,undefined}])))
=:= 18),
?_assertError(badarg, resize(foo, bad_argument))
].
-endif.
%% @doc Set entry `I' of the array to `Value'. If `I' is not a
%% nonnegative integer, or if the array has fixed size and `I' is larger
%% than the maximum index, the call fails with reason `badarg'.
%%
%% If the array does not have fixed size, and `I' is greater than
%% `size(Array)-1', the array will grow to size `I+1'.
%%
%% @see get/2
%% @see reset/2
-spec set(I :: array_indx(), Value :: Type, Array :: array(Type)) -> array(Type).
set(I, Value, #array{size = N, max = M, default = D, elements = E}=A)
when is_integer(I), I >= 0 ->
if I < N ->
A#array{elements = set_1(I, E, Value, D)};
I < M ->
%% (note that this cannot happen if M == 0, since N >= 0)
A#array{size = I+1, elements = set_1(I, E, Value, D)};
M > 0 ->
{E1, M1} = grow(I, E, M),
A#array{size = I+1, max = M1,
elements = set_1(I, E1, Value, D)};
true ->
erlang:error(badarg)
end;
set(_I, _V, _A) ->
erlang:error(badarg).
%% See get_1/3 for details about switching and the NODEPATTERN macro.
set_1(I, E=?NODEPATTERN(S), X, D) ->
I1 = I div S + 1,
setelement(I1, E, set_1(I rem S, element(I1, E), X, D));
set_1(I, E, X, D) when is_integer(E) ->
expand(I, E, X, D);
set_1(I, E, X, _D) ->
setelement(I+1, E, X).
%% Enlarging the array upwards to accommodate an index `I'
grow(I, E, _M) when is_integer(E) ->
M1 = find_max(I, E),
{M1, M1};
grow(I, E, M) ->
grow_1(I, E, M).
grow_1(I, E, M) when I >= M ->
grow(I, setelement(1, ?NEW_NODE(M), E), ?extend(M));
grow_1(_I, E, M) ->
{E, M}.
%% Insert an element in an unexpanded node, expanding it as necessary.
expand(I, S, X, D) when S > ?LEAFSIZE ->
S1 = ?reduce(S),
setelement(I div S1 + 1, ?NEW_NODE(S1),
expand(I rem S1, S1, X, D));
expand(I, _S, X, D) ->
setelement(I+1, ?NEW_LEAF(D), X).
%% @doc Get the value of entry `I'. If `I' is not a nonnegative
%% integer, or if the array has fixed size and `I' is larger than the
%% maximum index, the call fails with reason `badarg'.
%%
%% If the array does not have fixed size, this function will return the
%% default value for any index `I' greater than `size(Array)-1'.
%% @see set/3
-spec get(I :: array_indx(), Array :: array(Type)) -> Value :: Type.
get(I, #array{size = N, max = M, elements = E, default = D})
when is_integer(I), I >= 0 ->
if I < N ->
get_1(I, E, D);
M > 0 ->
D;
true ->
erlang:error(badarg)
end;
get(_I, _A) ->
erlang:error(badarg).
%% The use of NODEPATTERN(S) to select the right clause is just a hack,
%% but it is the only way to get the maximum speed out of this loop
%% (using the Beam compiler in OTP 11).
get_1(I, E=?NODEPATTERN(S), D) ->
get_1(I rem S, element(I div S + 1, E), D);
get_1(_I, E, D) when is_integer(E) ->
D;
get_1(I, E, _D) ->
element(I+1, E).
%% @doc Reset entry `I' to the default value for the array.
%% If the value of entry `I' is the default value the array will be
%% returned unchanged. Reset will never change size of the array.
%% Shrinking can be done explicitly by calling {@link resize/2}.
%%
%% If `I' is not a nonnegative integer, or if the array has fixed size
%% and `I' is larger than the maximum index, the call fails with reason
%% `badarg'; cf. {@link set/3}
%%
%% @see new/2
%% @see set/3
%% TODO: a reset_range function
-spec reset(I :: array_indx(), Array :: array(Type)) -> array(Type).
reset(I, #array{size = N, max = M, default = D, elements = E}=A)
when is_integer(I), I >= 0 ->
if I < N ->
try A#array{elements = reset_1(I, E, D)}
catch throw:default -> A
end;
M > 0 ->
A;
true ->
erlang:error(badarg)
end;
reset(_I, _A) ->
erlang:error(badarg).
reset_1(I, E=?NODEPATTERN(S), D) ->
I1 = I div S + 1,
setelement(I1, E, reset_1(I rem S, element(I1, E), D));
reset_1(_I, E, _D) when is_integer(E) ->
throw(default);
reset_1(I, E, D) ->
Indx = I+1,
case element(Indx, E) of
D -> throw(default);
_ -> setelement(I+1, E, D)
end.
-ifdef(EUNIT).
set_get_test_() ->
N0 = ?LEAFSIZE,
N1 = ?NODESIZE*N0,
[?_assert(array:get(0, new()) =:= undefined),
?_assert(array:get(1, new()) =:= undefined),
?_assert(array:get(99999, new()) =:= undefined),
?_assert(array:get(0, new(1)) =:= undefined),
?_assert(array:get(0, new(1,{default,0})) =:= 0),
?_assert(array:get(9, new(10)) =:= undefined),
?_assertError(badarg, array:get(0, new(fixed))),
?_assertError(badarg, array:get(1, new(1))),
?_assertError(badarg, array:get(-1, new(1))),
?_assertError(badarg, array:get(10, new(10))),
?_assertError(badarg, array:set(-1, foo, new(10))),
?_assertError(badarg, array:set(10, foo, no_array)),
?_assert(array:size(set(0, 17, new())) =:= 1),
?_assert(array:size(set(N1-1, 17, new())) =:= N1),
?_assert(array:size(set(0, 42, set(0, 17, new()))) =:= 1),
?_assert(array:size(set(9, 42, set(0, 17, new()))) =:= 10),
?_assert(array:get(0, set(0, 17, new())) =:= 17),
?_assert(array:get(0, set(1, 17, new())) =:= undefined),
?_assert(array:get(1, set(1, 17, new())) =:= 17),
?_assert(array:get(0, fix(set(0, 17, new()))) =:= 17),
?_assertError(badarg, array:get(1, fix(set(0, 17, new())))),
?_assert(array:get(N1-2, set(N1-1, 17, new())) =:= undefined),
?_assert(array:get(N1-1, set(N1-1, 17, new())) =:= 17),
?_assertError(badarg, array:get(N1, fix(set(N1-1, 17, new())))),
?_assert(array:get(0, set(0, 42, set(0, 17, new()))) =:= 42),
?_assertError(badarg, array:get(0, reset(11, new([{size,10}])))),
?_assertError(badarg, array:get(0, reset(-1, new([{size,10}])))),
?_assert(array:get(0, reset(0, new())) =:= undefined),
?_assert(array:get(0, reset(0, set(0, 17, new()))) =:= undefined),
?_assert(array:get(0, reset(9, set(9, 17, new()))) =:= undefined),
?_assert(array:get(0, reset(11, set(11, 17, new()))) =:= undefined),
?_assert(array:get(0, reset(11, set(12, 17, new()))) =:= undefined),
?_assert(array:get(0, reset(1, set(12, 17, new()))) =:= undefined),
?_assert(array:get(0, reset(11, new())) =:= undefined),
?_assert(array:get(0, reset(0, set(0, 17, new({default,42})))) =:= 42),
?_assert(array:get(0, reset(0, new({default,42}))) =:= 42)
].
-endif.
%% @doc Converts the array to a list.
%%
%% @see from_list/2
%% @see sparse_to_list/1
-spec to_list(Array :: array(Type)) -> list(Value :: Type).
to_list(#array{size = 0}) ->
[];
to_list(#array{size = N, elements = E, default = D}) ->
to_list_1(E, D, N - 1);
to_list(_) ->
erlang:error(badarg).
%% this part handles the rightmost subtrees
to_list_1(E=?NODEPATTERN(S), D, I) ->
N = I div S,
to_list_3(N, D, to_list_1(element(N+1, E), D, I rem S), E);
to_list_1(E, D, I) when is_integer(E) ->
push(I+1, D, []);
to_list_1(E, _D, I) ->
push_tuple(I+1, E, []).
%% this part handles full trees only
to_list_2(E=?NODEPATTERN(_S), D, L) ->
to_list_3(?NODESIZE, D, L, E);
to_list_2(E, D, L) when is_integer(E) ->
push(E, D, L);
to_list_2(E, _D, L) ->
push_tuple(?LEAFSIZE, E, L).
to_list_3(0, _D, L, _E) ->
L;
to_list_3(N, D, L, E) ->
to_list_3(N-1, D, to_list_2(element(N, E), D, L), E).
push(0, _E, L) ->
L;
push(N, E, L) ->
push(N - 1, E, [E | L]).
push_tuple(0, _T, L) ->
L;
push_tuple(N, T, L) ->
push_tuple(N - 1, T, [element(N, T) | L]).
-ifdef(EUNIT).
to_list_test_() ->
N0 = ?LEAFSIZE,
[?_assert([] =:= to_list(new())),
?_assert([undefined] =:= to_list(new(1))),
?_assert([undefined,undefined] =:= to_list(new(2))),
?_assert(lists:duplicate(N0,0) =:= to_list(new(N0,{default,0}))),
?_assert(lists:duplicate(N0+1,1) =:= to_list(new(N0+1,{default,1}))),
?_assert(lists:duplicate(N0+2,2) =:= to_list(new(N0+2,{default,2}))),
?_assert(lists:duplicate(666,6) =:= to_list(new(666,{default,6}))),
?_assert([1,2,3] =:= to_list(set(2,3,set(1,2,set(0,1,new()))))),
?_assert([3,2,1] =:= to_list(set(0,3,set(1,2,set(2,1,new()))))),
?_assert([1|lists:duplicate(N0-2,0)++[1]] =:=
to_list(set(N0-1,1,set(0,1,new({default,0}))))),
?_assert([1|lists:duplicate(N0-1,0)++[1]] =:=
to_list(set(N0,1,set(0,1,new({default,0}))))),
?_assert([1|lists:duplicate(N0,0)++[1]] =:=
to_list(set(N0+1,1,set(0,1,new({default,0}))))),
?_assert([1|lists:duplicate(N0*3,0)++[1]] =:=
to_list(set((N0*3)+1,1,set(0,1,new({default,0}))))),
?_assertError(badarg, to_list(no_array))
].
-endif.
%% @doc Converts the array to a list, skipping default-valued entries.
%%
%% @see to_list/1
-spec sparse_to_list(Array :: array(Type)) -> list(Value :: Type).
sparse_to_list(#array{size = 0}) ->
[];
sparse_to_list(#array{size = N, elements = E, default = D}) ->
sparse_to_list_1(E, D, N - 1);
sparse_to_list(_) ->
erlang:error(badarg).
%% see to_list/1 for details
sparse_to_list_1(E=?NODEPATTERN(S), D, I) ->
N = I div S,
sparse_to_list_3(N, D,
sparse_to_list_1(element(N+1, E), D, I rem S),
E);
sparse_to_list_1(E, _D, _I) when is_integer(E) ->
[];
sparse_to_list_1(E, D, I) ->
sparse_push_tuple(I+1, D, E, []).
sparse_to_list_2(E=?NODEPATTERN(_S), D, L) ->
sparse_to_list_3(?NODESIZE, D, L, E);
sparse_to_list_2(E, _D, L) when is_integer(E) ->
L;
sparse_to_list_2(E, D, L) ->
sparse_push_tuple(?LEAFSIZE, D, E, L).
sparse_to_list_3(0, _D, L, _E) ->
L;
sparse_to_list_3(N, D, L, E) ->
sparse_to_list_3(N-1, D, sparse_to_list_2(element(N, E), D, L), E).
sparse_push_tuple(0, _D, _T, L) ->
L;
sparse_push_tuple(N, D, T, L) ->
case element(N, T) of
D -> sparse_push_tuple(N - 1, D, T, L);
E -> sparse_push_tuple(N - 1, D, T, [E | L])
end.
-ifdef(EUNIT).
sparse_to_list_test_() ->
N0 = ?LEAFSIZE,
[?_assert([] =:= sparse_to_list(new())),
?_assert([] =:= sparse_to_list(new(1))),
?_assert([] =:= sparse_to_list(new(1,{default,0}))),
?_assert([] =:= sparse_to_list(new(2))),
?_assert([] =:= sparse_to_list(new(2,{default,0}))),
?_assert([] =:= sparse_to_list(new(N0,{default,0}))),
?_assert([] =:= sparse_to_list(new(N0+1,{default,1}))),
?_assert([] =:= sparse_to_list(new(N0+2,{default,2}))),
?_assert([] =:= sparse_to_list(new(666,{default,6}))),
?_assert([1,2,3] =:= sparse_to_list(set(2,3,set(1,2,set(0,1,new()))))),
?_assert([3,2,1] =:= sparse_to_list(set(0,3,set(1,2,set(2,1,new()))))),
?_assert([0,1] =:= sparse_to_list(set(N0-1,1,set(0,0,new())))),
?_assert([0,1] =:= sparse_to_list(set(N0,1,set(0,0,new())))),
?_assert([0,1] =:= sparse_to_list(set(N0+1,1,set(0,0,new())))),
?_assert([0,1,2] =:= sparse_to_list(set(N0*10+1,2,set(N0*2+1,1,set(0,0,new()))))),
?_assertError(badarg, sparse_to_list(no_array))
].
-endif.
%% @equiv from_list(List, undefined)
-spec from_list(List :: list(Value :: Type)) -> array(Type).
from_list(List) ->
from_list(List, undefined).
%% @doc Convert a list to an extendible array. `Default' is used as the value
%% for uninitialized entries of the array. If `List' is not a proper list,
%% the call fails with reason `badarg'.
%%
%% @see new/2
%% @see to_list/1
-spec from_list(List :: list(Value :: Type), Default :: term()) -> array(Type).
from_list([], Default) ->
new({default,Default});
from_list(List, Default) when is_list(List) ->
{E, N, M} = from_list_1(?LEAFSIZE, List, Default, 0, [], []),
#array{size = N, max = M, default = Default, elements = E};
from_list(_, _) ->
erlang:error(badarg).
%% Note: A cleaner but slower algorithm is to first take the length of
%% the list and compute the max size of the final tree, and then
%% decompose the list. The below algorithm is almost twice as fast,
%% however.
%% Building the leaf nodes (padding the last one as necessary) and
%% counting the total number of elements.
from_list_1(0, Xs, D, N, As, Es) ->
E = list_to_tuple(lists:reverse(As)),
case Xs of
[] ->
case Es of
[] ->
{E, N, ?LEAFSIZE};
_ ->
from_list_2_0(N, [E | Es], ?LEAFSIZE)
end;
[_|_] ->
from_list_1(?LEAFSIZE, Xs, D, N, [], [E | Es]);
_ ->
erlang:error(badarg)
end;
from_list_1(I, Xs, D, N, As, Es) ->
case Xs of
[X | Xs1] ->
from_list_1(I-1, Xs1, D, N+1, [X | As], Es);
_ ->
from_list_1(I-1, Xs, D, N, [D | As], Es)
end.
%% Building the internal nodes (note that the input is reversed).
from_list_2_0(N, Es, S) ->
from_list_2(?NODESIZE, pad((N-1) div S + 1, ?NODESIZE, S, Es),
S, N, [S], []).
from_list_2(0, Xs, S, N, As, Es) ->
E = list_to_tuple(As),
case Xs of
[] ->
case Es of
[] ->
{E, N, ?extend(S)};
_ ->
from_list_2_0(N, lists:reverse([E | Es]),
?extend(S))
end;
_ ->
from_list_2(?NODESIZE, Xs, S, N, [S], [E | Es])
end;
from_list_2(I, [X | Xs], S, N, As, Es) ->
from_list_2(I-1, Xs, S, N, [X | As], Es).
%% left-padding a list Es with elements P to the nearest multiple of K
%% elements from N (adding 0 to K-1 elements).
pad(N, K, P, Es) ->
push((K - (N rem K)) rem K, P, Es).
-ifdef(EUNIT).
from_list_test_() ->
N0 = ?LEAFSIZE,
N1 = ?NODESIZE*N0,
N2 = ?NODESIZE*N1,
N3 = ?NODESIZE*N2,
N4 = ?NODESIZE*N3,
[?_assert(array:size(from_list([])) =:= 0),
?_assert(array:is_fix(from_list([])) =:= false),
?_assert(array:size(from_list([undefined])) =:= 1),
?_assert(array:is_fix(from_list([undefined])) =:= false),
?_assert(array:size(from_list(lists:seq(1,N1))) =:= N1),
?_assert(to_list(from_list(lists:seq(1,N0))) =:= lists:seq(1,N0)),
?_assert(to_list(from_list(lists:seq(1,N0+1))) =:= lists:seq(1,N0+1)),
?_assert(to_list(from_list(lists:seq(1,N0+2))) =:= lists:seq(1,N0+2)),
?_assert(to_list(from_list(lists:seq(1,N2))) =:= lists:seq(1,N2)),
?_assert(to_list(from_list(lists:seq(1,N2+1))) =:= lists:seq(1,N2+1)),
?_assert(to_list(from_list(lists:seq(0,N3))) =:= lists:seq(0,N3)),
?_assert(to_list(from_list(lists:seq(0,N4))) =:= lists:seq(0,N4)),
?_assertError(badarg, from_list([a,b,a,c|d])),
?_assertError(badarg, from_list(no_array))
].