forked from erlang-unicode/ux
/
ux_col.erl
1734 lines (1534 loc) · 61.9 KB
/
ux_col.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
% vim: set filetype=erlang shiftwidth=4 tabstop=4 expandtab tw=80:
%%% =====================================================================
%%% This library is free software; you can redistribute it and/or modify
%%% it under the terms of the GNU Lesser General Public License as
%%% published by the Free Software Foundation; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This library is distributed in the hope that it will be useful, but
%%% WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% Lesser General Public License for more details.
%%%
%%% You should have received a copy of the GNU Lesser General Public
%%% License along with this library; if not, write to the Free Software
%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
%%% USA
%%%
%%% $Id$
%%%
%%% @copyright 2010-2011 Michael Uvarov
%%% @author Michael Uvarov <freeakk@gmail.com>
%%% @see ux
%%% @end
%%% =====================================================================
%%% @doc UCA.
%%%
%%% == Additional information (and links) ==
%%%
%%% 1. [http://www.open-std.org/jtc1/sc22/wg20/docs/n1037-Hangul%20Collation%20Requirements.htm
%%% Hangul Collation Requirements]
%%% PS: There is the main source of information.
%%%
%%% 2. [http://code.activestate.com/lists/perl-unicode/2163/
%%% Terminator weight for Hangul]
%%%
%%% 3. [http://blogs.msdn.com/b/michkap/archive/2005/02/25/380266.aspx
%%% Theory vs. practice for Korean text collation]
%%% PS: there is no any practice. They do not the UCA :/
%%%
%%% 4. [http://en.wikipedia.org/wiki/Unicode_collation_algorithm Wiki]
%%%
%%% 6. [http://useless-factor.blogspot.com/2007/08/unicode-implementers-guide-part-3.html
%%% Unicode implementer's guide part 3: Conjoining jamo behavior]
%%%
%%% 7. [http://useless-factor.blogspot.com/2007/10/unicode-implementers-guide-part-5.html
%%% Unicode implementer's guide part 5: Collation]
%%%
%%% 8. [http://useless-factor.blogspot.com/2008/05/unicode-collation-works-now.html
%%% Unicode collation works now]
%%% PS: I found it so late. :(
%%%
%%% 9. [http://userguide.icu-project.org/collation/concepts ICU]
%%%
%%% 10. [http://trapexit.org/String_Sorting_%28Natural%29
%%% String Sorting (Natural) in Erlang Cookbook]
%%% ```
%%% FIXED: Combining character contractions. Apparently, two combining marks can
%%% form a contraction. A straight reading of the UCA wouldn't predict
%%% this, but not all of the UCA tests pass unless you check for
%%% non-adjacent combining marks being in a contraction together, without
%%% a noncombining mark to start it off.
%%% '''
%%% @end
-module(ux_col).
-author('Uvarov Michael <freeakk@gmail.com>').
-export([non_ignorable/2,
blanked/2,
shifted/2,
shift_trimmed/2,
compare/2, compare/3,
sort_array/1, sort_array/2,
sort_array_non_ignorable/1,
sort_array_blanked/1,
sort_array_shifted/1,
sort_array_shift_trimmed/1,
sort_key/1, sort_key/2,
sort/1, sort/2,
ducet/1,
get_options/0, get_options/1, get_options/2
]).
-include("ux.hrl").
-include("ux_string.hrl").
-include("ux_unidata.hrl").
-include("ux_char.hrl").
-include("ux_col.hrl").
% ducet_r(reversed_in) -> non_reversed_key;
ducet_r(V) -> ?UNIDATA:ducet_r(V).
ccc(V) -> ?UNIDATA:ccc(V).
%% @doc In: not reversed string.
%% Out: not reversed weight list.
%% @end
ducet(A) -> ducet_r(lists:reverse(A)).
get_options() -> #uca_options{
ducet_r_fn = fun ducet_r/1
}.
get_options(non_ignorable) ->
#uca_options {
ducet_r_fn = fun ducet_r/1,
natural_sort = false,
strength = 3,
alternate = non_ignorable
};
get_options(blanked) ->
#uca_options {
ducet_r_fn = fun ducet_r/1,
natural_sort = false,
strength = 3,
alternate = blanked
};
get_options(shifted) ->
#uca_options {
ducet_r_fn = fun ducet_r/1,
natural_sort = false,
strength = 4,
alternate = shifted
};
get_options(shift_trimmed) ->
#uca_options {
ducet_r_fn = fun ducet_r/1,
natural_sort = false,
strength = 4,
alternate = shift_trimmed
};
get_options([_|_] = Params) ->
get_options(Params, get_options()).
%% @doc If you want use this library without import *.hrl, you can create
%% a #uca_options {} record with this function.
%% @end
get_options([{hangul_terminator, Val}|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ hangul_terminator=Val });
get_options([{natural_sort, Val}|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ natural_sort=Val });
get_options([{case_sensitive, Val}|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ case_sensitive=Val });
get_options([{case_first, Val}|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ case_first=Val });
get_options([{strength, Val}|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ strength=Val });
get_options([{alternate, Val}|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ alternate=Val });
get_options([{sort_key_format, Val}|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ sort_key_format=Val });
get_options([{ducet_r_fn, Val}|T], Opt = #uca_options{ })
when is_function(Val) ->
get_options(T, Opt#uca_options{ ducet_r_fn=Val });
% I don't like enter {sort_key_format, list}. So, get atom:
% alternate
get_options([shifted|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ alternate=shifted });
get_options([shift_trimmed|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ alternate=shift_trimmed });
get_options([non_ignorable|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ alternate=non_ignorable });
get_options([blanked|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ alternate=blanked });
% sort_key_format
get_options([binary|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ sort_key_format=binary });
get_options([list|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ sort_key_format=list });
get_options([uncompressed|T], Opt = #uca_options{ }) ->
get_options(T, Opt#uca_options{ sort_key_format=uncompressed });
get_options([{ducet_r, Val}|T], Opt = #uca_options{ })
when is_function(Val) ->
get_options(T, Opt#uca_options{
ducet_r_fn=fun(A) ->
Val(lists:reverse(A))
end });
get_options([], Opt = #uca_options{ }) ->
Opt.
% % %%%%% %
% % % % % %
% % % % %
% % % % %
% % % %%%%%%%
% % % % % %
%%%%% %%%%% % %
%% ----------------------------------------------------------------------------
%% UNICODE COLLATION ALGORITHM
%% see Unicode Technical Standard #10
% For hangul:
% http://www.open-std.org/Jtc1/sc22/wg20/docs/n1037-Hangul%20Collation%20Requirements.htm
% http://www.unicode.org/reports/tr10/#Hangul_Collation
% http://en.wikipedia.org/wiki/KSX1001
-spec non_ignorable(string(), string()) -> less | greater | equal.
% Levels: http://unicode.org/reports/tr10/#Multi_Level_Comparison
% L1 Base characters
% L2 Accents
% L3 Case
% L4 Punctuation
%% @doc Variable collation elements are not reset to be ignorable, but
%% get the weights explicitly mentioned in the file.
%% ```
%% * SPACE would have the value [.0209.0020.0002]
%% * Capital A would be unchanged, with the value [.06D9.0020.0008]
%% * Ignorables are unchanged.'''
%% @end
non_ignorable(S1, S2) ->
compare(S1, S2,
get_options(non_ignorable),
fun ducet_r/1, % ducet_r(reversed_in) -> non_reversed_key;
fun non_ignorable_bin_to_list/1).
%% @doc Variable collation elements and any subsequent ignorables
%% are reset so that their weights at levels one through three are zero.
%% For example,
%% ```
%% * SPACE would have the value [.0000.0000.0000]
%% * A combining grave accent after a space would have the value [.0000.0000.0000]
%% * Capital A would be unchanged, with the value [.06D9.0020.0008]
%% * A combining grave accent after a Capital A would be unchanged'''
%% @end
blanked(S1, S2) ->
compare(S1, S2,
get_options(blanked),
fun ducet_r/1, % ducet_r(reversed_in) -> non_reversed_key;
fun blanked_bin_to_list/1).
%% @doc Variable collation elements are reset to zero at levels one through
%% three. In addition, a new fourth-level weight is appended, whose value
%% depends on the type, as shown in Table 12.
%% Any subsequent primary or secondary ignorables following a variable are reset
%% so that their weights at levels one through four are zero.
%% ```
%% * A combining grave accent after a space would have the value
%% [.0000.0000.0000.0000].
%% * A combining grave accent after a Capital A would be unchanged.'''
%% @end
shifted(S1, S2) ->
compare(S1, S2,
get_options(shifted),
fun ducet_r/1, % ducet_r(reversed_in) -> non_reversed_key;
fun shifted_bin_to_list/1).
%% @doc This option is the same as Shifted, except that all trailing
%% FFFFs are trimmed from the sort key.
%% This could be used to emulate POSIX behavior.
%% @end
shift_trimmed(S1, S2) ->
compare(S1, S2,
get_options(shift_trimmed),
fun ducet_r/1, % ducet_r(reversed_in) -> non_reversed_key;
fun shift_trimmed_bin_to_list/1).
non_ignorable_bin_to_list(Value) ->
{fun non_ignorable_bin_to_list/1, bin_to_list(Value)}.
%% @doc Convert binary from DUCET to list [L1, L2, L3, L4].
%% A variable CE is "*" in ducet (1).
%% A non-varialbe CE is "." in ducet (0).
%% @end
%% @private
bin_to_list(<<_Variable:8, L1:16, L2:16, L3:16, L4:16>>) ->
[L1, L2, L3, L4];
bin_to_list(<<_Variable:8, L1:16, L2:16, L3:16, L4:24>>) ->
[L1, L2, L3, L4];
% For hangul
bin_to_list(L1) when is_integer(L1) ->
[L1, 0, 0, 0].
%% @private
% If it is a tertiary ignorable, then L4 = 0.
shifted_bin_to_list(<<_:8, 0:48, _/binary>>) ->
{fun shifted_bin_to_list/1, [0, 0, 0, 0]};
% If it is a variable, then L4 = Old L1.
shifted_bin_to_list(<<1:8, L1:16, _/binary>>) ->
{fun shifted_bin_to_list2/1, [0, 0, 0, L1]};
shifted_bin_to_list(Value) ->
{fun shifted_bin_to_list/1, set_l4_to_value(Value, 16#FFFF)}.
%% @doc This function is a version of shifted_bin_to_list/1, but its value is
%% after variable.
%% @end
%% @private
% If it is a ignorable, then L4 = 0.
shifted_bin_to_list2(<<_:8, 0:16, _/binary>>) ->
{fun shifted_bin_to_list2/1, [0, 0, 0, 0]};
% If it is a variable, then L4 = Old L1.
shifted_bin_to_list2(<<1:8, L1:16, _/binary>>) ->
{fun shifted_bin_to_list2/1, [0, 0, 0, L1]};
shifted_bin_to_list2(Value) ->
{fun shifted_bin_to_list/1, set_l4_to_value(Value, 16#FFFF)}.
%% @private
%% Alternate=Shifted, Strength=L3
blanked_bin_to_list(<<1:8, _/binary>>) ->
{fun blanked_bin_to_list2/1, [0, 0, 0]};
blanked_bin_to_list(Value) ->
{fun blanked_bin_to_list/1, bin_to_list(Value)}.
%% @private
blanked_bin_to_list2(<<_:8, 0:16, _/binary>>) ->
{fun blanked_bin_to_list2/1, [0, 0, 0]};
blanked_bin_to_list2(<<1:8, _/binary>>) ->
{fun blanked_bin_to_list2/1, [0, 0, 0]};
blanked_bin_to_list2(Value) ->
{fun blanked_bin_to_list/1, bin_to_list(Value)}.
%% @private
% If it is a tertiary ignorable, then L4 = 0.
shift_trimmed_bin_to_list(<<_:8, 0:48, _/binary>>) ->
{fun shift_trimmed_bin_to_list/1, [0, 0, 0, 0]};
% If it is a variable, then L4 = Old L1.
shift_trimmed_bin_to_list(<<1:8, L1:16, _/binary>>) ->
{fun shift_trimmed_bin_to_list2/1, [0, 0, 0, L1]};
shift_trimmed_bin_to_list(Value) ->
{fun shift_trimmed_bin_to_list/1, set_l4_to_value(Value, 0)}.
%% @doc This function is a version of shifted_bin_to_list/1, but its value is
%% after variable.
%% @end
%% @private
% If it is a ignorable, then L4 = 0.
shift_trimmed_bin_to_list2(<<_:8, 0:16, _/binary>>) ->
{fun shift_trimmed_bin_to_list2/1, [0, 0, 0, 0]};
% If it is a variable, then L4 = Old L1.
shift_trimmed_bin_to_list2(<<1:8, L1:16, _/binary>>) ->
{fun shift_trimmed_bin_to_list2/1, [0, 0, 0, L1]};
shift_trimmed_bin_to_list2(Value) ->
{fun shift_trimmed_bin_to_list/1, set_l4_to_value(Value, 0)}.
%% @private
%% Return: [_, _, _, _]
set_l4_to_value(<<_Variable:8, L1:16, L2:16, L3:16, _:16>>, Val) ->
[L1, L2, L3, Val];
set_l4_to_value(<<_Variable:8, L1:16, L2:16, L3:16, _:24>>, Val) ->
[L1, L2, L3, Val];
% For hangul
set_l4_to_value(L1, Val) when is_integer(L1) ->
[L1, 0, 0, Val].
%% @private
%% Returns: <<Bin>>
set_l1_to_value_bin(<<Variable:8, _L1:16, T/binary>>, Val) ->
<<Variable, Val:16, T/binary>>.
sort(Lists) ->
sort(Lists, #uca_options{}).
%% @doc Sort a string list.
%% Example:
%% ```f().
%% RawData = ["death", "de luge", "de-luge", "deluge", "de-luge", "de Luge", "de-Luge", "deLuge", "de-Luge", "demark"].
%% Data = lists:map(fun lists:flatten/1, RawData).
%% ux_string:sort(Data, non_ignorable).
%% ux_string:sort(Data, blanked).
%% ux_string:sort(Data, shifted).
%% ux_string:sort(Data, shift_trimmed).'''
%% @end
sort(Lists, Alt) when is_atom(Alt) ->
Params = get_options(Alt),
Fn = get_comp_fn(Alt),
lists:map(fun({_SortKey, Str}) -> Str end,
lists:keysort(1,
sort_map(Lists, Params, Fn, [])));
sort(Lists, #uca_options{alternate=Alt} = Params) ->
Fn = get_comp_fn(Alt),
lists:map(fun({_SortKey, Str}) -> Str end,
lists:keysort(1,
sort_map(Lists, Params, Fn, []))).
%% @doc Lists: an array of strings;
%% Fn: an map function.
%%
%% This function does:
%% `lists:map(fun(X) -> sort_key(X, Fn) end, Lists).'
%% H is string.
%% Fn is col_function.
%% Params is #uca_options{}
%% @end
%% @private
sort_map([H|T], Params = #uca_options{ducet_r_fn=DucetRFn}, Fn, Res) ->
sort_map(T, Params, Fn, [
{sort_array_to_key(
sort_array(H, Params, DucetRFn, Fn)), H}|Res]);
sort_map([], _Params, _Fn, Res) ->
lists:reverse(Res).
%% @private
-spec get_sort_fn(atom()) -> function().
get_sort_fn(non_ignorable) ->
fun sort_array_non_ignorable/1;
get_sort_fn(blanked) ->
fun sort_array_blanked/1;
get_sort_fn(shifted) ->
fun sort_array_shifted/1;
get_sort_fn(shift_trimmed) ->
fun sort_array_shift_trimmed/1.
-spec get_comp_fn(atom()) -> function().
get_comp_fn(non_ignorable) ->
fun non_ignorable_bin_to_list/1;
get_comp_fn(blanked) ->
fun blanked_bin_to_list/1;
get_comp_fn(shifted) ->
fun shifted_bin_to_list/1;
get_comp_fn(shift_trimmed) ->
fun shift_trimmed_bin_to_list/1.
sort_key(Str) ->
sort_key(Str, #uca_options{ducet_r_fn=fun ducet_r/1}).
% Return key as binary
sort_key(Str, #uca_options{
sort_key_format=binary,
alternate=Alt,
ducet_r_fn=DucetRFn} = Params) ->
Fn = get_comp_fn(Alt),
convert_key_to_bin(
sort_array_to_key(
sort_array(Str, Params, DucetRFn, Fn)));
% Return key as a list
sort_key(Str, #uca_options{
sort_key_format=list,
alternate=Alt,
ducet_r_fn=DucetRFn} = Params) ->
Fn = get_comp_fn(Alt),
sort_array_to_key(
sort_array(Str, Params, DucetRFn, Fn));
% Return key as an uncompressed list
sort_key(Str, #uca_options{
sort_key_format=uncompressed,
alternate=Alt,
ducet_r_fn=DucetRFn} = Params) ->
Fn = get_comp_fn(Alt),
sort_array_to_uncompressed_key(
sort_array(Str, Params, DucetRFn, Fn));
% For testing. Second parameter is a comp_fun.
sort_key(Str, Fn) when is_function(Fn) ->
Array = apply(Fn, [Str]),
{_Level, Res} = sort_key1(Array, 1, [], []),
lists:reverse(Res);
% Pass only comp_fn id.
sort_key(Str, FnName) when is_atom(FnName) ->
Fn = get_sort_fn(FnName),
sort_key(Str, Fn).
%% Convert a sort array to a sort key.
sort_array_to_key(Array) ->
{Level, Res} = sort_key1(Array, 1, [], []),
compress_sort_key_r(Res, Level, []).
sort_array_to_uncompressed_key(Array) ->
{_Level, Res} = sort_key1(Array, 1, [], []),
lists:reverse(Res).
%% @private
%% @param AT is Array Tail.
%% @param Level is max level of key (default 1).
%% @return {MaxLevel, ReversedSortKey}
-spec sort_key1(list(), integer(), list(), list()) -> tuple().
sort_key1([[0]|AT], Level, Acc, Res) ->
sort_key1(AT, Level, Acc, Res);
sort_key1([[H]|AT], Level, Acc, Res) ->
sort_key1(AT, Level, Acc, [H|Res]);
sort_key1([[0|T]|AT], Level, Acc, Res) ->
sort_key1(AT, Level, [T|Acc], Res);
sort_key1([[H|T]|AT], Level, Acc, Res) ->
sort_key1(AT, Level, [T|Acc], [H|Res]);
sort_key1([[]|AT], Level, Acc, Res) ->
sort_key1(AT, Level, Acc, Res);
sort_key1([] = _InArray, Level, [_|_] = Acc, Res) ->
sort_key1(lists:reverse(Acc), Level + 1, [], [0|Res]);
sort_key1([] = _InArray, Level, [] = _Acc, Res) -> {Level, Res}.
% CAPACITY is a max value after compression.
% MIN is a min value before compression.
% MAX is a max value before compression.
% Before:
% MIN < COMMON < MAX
% After:
% MIN < MAXBOTTOM < GAP_FOR_COMMON_VALUE < MINTOP < CAPACITY
-define(COL_LEVEL2_CAPACITY, 500).
-define(COL_LEVEL2_MIN, 1).
-define(COL_LEVEL2_MAX, 450).
-define(COL_LEVEL2_COMMON, 32).
-define(COL_LEVEL2_BOUND, 50).
-define(COL_LEVEL2_MINTOP, 31).
-define(COL_LEVEL3_CAPACITY, 16#FF).
-define(COL_LEVEL3_MIN, 2).
-define(COL_LEVEL3_MAX, 16#1F).
-define(COL_LEVEL3_COMMON, 2).
-define(COL_LEVEL3_BOUND, 60).
-define(COL_LEVEL3_MINTOP, 1).
-define(COL_LEVEL4_CAPACITY, 16#FFFFFF).
-define(COL_LEVEL4_MIN, 1).
-define(COL_LEVEL4_MAX, 16#1FFFFF).
-define(COL_LEVEL4_COMMON, 16#FFFF).
-define(COL_LEVEL4_BOUND, 16#100F0).
-define(COL_LEVEL4_MINTOP, 16#FFFE).
% Reassign the weights in the collation element table at level n to create
% a gap of size GAP above COMMON. Typically for secondaries or tertiaries
% this is done after the values have been reduced to a byte range by the
% above methods. Here is a mapping that moves weights up or down to create
% a gap in a byte range.
% w -> w + 01 - MIN, for MIN <= w < COMMON
% w -> w + FF - MAX, for COMMON < w <= MAX
-define(REASSIGN_WEIGHT(W, Min, Max, Common, Capacity),
(if
((W) >= (Min)) and ((W) < (Common)) ->
(W) + 1 - (Min);
(W > Common) and ((W) =< (Max)) ->
(W) + Capacity - (Max);
true -> Common
end)).
-define(REASSIGN_WEIGHT2(W),
?REASSIGN_WEIGHT(W, ?COL_LEVEL2_MIN, ?COL_LEVEL2_MAX, ?COL_LEVEL2_COMMON,
?COL_LEVEL2_CAPACITY)).
-define(REASSIGN_WEIGHT3(W),
?REASSIGN_WEIGHT(W, ?COL_LEVEL3_MIN, ?COL_LEVEL3_MAX, ?COL_LEVEL3_COMMON,
?COL_LEVEL3_CAPACITY)).
-define(REASSIGN_WEIGHT4(W),
?REASSIGN_WEIGHT(W, ?COL_LEVEL4_MIN, ?COL_LEVEL4_MAX, ?COL_LEVEL4_COMMON,
?COL_LEVEL4_CAPACITY)).
-define(COL_LEVEL2_MAXBOTTOM, (?COL_LEVEL2_CAPACITY - ?COL_LEVEL2_MIN
- (?COL_LEVEL2_MAX - ?COL_LEVEL2_COMMON + 1))).
-define(COL_LEVEL2_GAP_SIZE, (?COL_LEVEL2_CAPACITY - ?COL_LEVEL2_MAX
- ?COL_LEVEL2_MIN)).
-define(COL_LEVEL3_MAXBOTTOM, (?COL_LEVEL3_CAPACITY - ?COL_LEVEL3_MIN
- (?COL_LEVEL3_MAX - ?COL_LEVEL3_COMMON + 1))).
-define(COL_LEVEL3_GAP_SIZE, (?COL_LEVEL3_CAPACITY - ?COL_LEVEL3_MAX
- ?COL_LEVEL3_MIN)).
-define(COL_LEVEL4_MAXBOTTOM, (?COL_LEVEL4_CAPACITY - ?COL_LEVEL4_MIN
- (?COL_LEVEL4_MAX - ?COL_LEVEL4_COMMON + 1))).
-define(COL_LEVEL4_GAP_SIZE, (?COL_LEVEL4_CAPACITY - ?COL_LEVEL4_MAX
- ?COL_LEVEL4_MIN)).
%% @doc Get reversed sort key and compress it.
%% @param Key
%% @param Level (1-4). For example: 3 then 2 then 1 (because Key is reversed!)
%% @param Res Compressed key
-spec compress_sort_key_r(list(), integer(), list()) -> list().
compress_sort_key_r([0|T], Level, Res) ->
compress_sort_key_r(T, Level - 1, [0|Res]);
% Replace H=2 on Level=3
compress_sort_key_r([?COL_LEVEL3_COMMON|T], _Level = 3, Res) ->
compress_sort_key_l3(T, 1, Res);
compress_sort_key_r([H|T], Level = 3, Res) ->
compress_sort_key_r(T, Level, [?REASSIGN_WEIGHT3(H)|Res]);
% Replace on Level=2
compress_sort_key_r([?COL_LEVEL2_COMMON|T], _Level = 2, Res) ->
compress_sort_key_l2(T, 1, Res);
compress_sort_key_r([H|T], Level = 2, Res) ->
compress_sort_key_r(T, Level, [?REASSIGN_WEIGHT2(H)|Res]);
% Replace on Level=4
compress_sort_key_r([?COL_LEVEL4_COMMON|T], _Level = 4, Res) ->
compress_sort_key_l4(T, 1, Res);
compress_sort_key_r([H|T], Level = 4, Res) ->
compress_sort_key_r(T, Level, [?REASSIGN_WEIGHT4(H)|Res]);
compress_sort_key_r([H|T], Level, Res) ->
compress_sort_key_r(T, Level, [H|Res]);
compress_sort_key_r([], _Level, Res) -> Res.
%% @doc Read all W from Key.
%% ```If W < COMMON (or there is no W), replace the sequence by a synthetic low
%% weight equal to (MINTOP + m).
%% If W > COMMON, replace the sequence by a synthetic high weight equal to
%% (MAXBOTTOM - m).'''
%%
%% An input key must be reversed!
%% @end
%% @private
-spec compress_sort_key_l3(list(), integer(), list()) -> list().
compress_sort_key_l3([?COL_LEVEL3_COMMON|T], M, Res) ->
compress_sort_key_l3(T, M + 1, Res);
compress_sort_key_l3(T, M, [W|_] = Res)
when (W > ?COL_LEVEL3_MAXBOTTOM) ->
SynHighWeight = ?COL_LEVEL3_MAXBOTTOM - M,
if
% If a synthetic high weight would be less than BOUND, use a
% sequence of high weights of the form (BOUND)..(BOUND)(MAXBOTTOM -
% remainder).
SynHighWeight < ?COL_LEVEL3_BOUND ->
HighGapSize = ?COL_LEVEL3_MAXBOTTOM - ?COL_LEVEL3_BOUND - 1,
SeqCnt = M div HighGapSize,
Remainder = M rem HighGapSize,
compress_sort_key_r(T, 3,
compress_seq(SeqCnt, ?COL_LEVEL3_BOUND,
[(?COL_LEVEL3_MAXBOTTOM - Remainder)|Res]));
true -> compress_sort_key_r(T, 3, [SynHighWeight|Res])
end;
compress_sort_key_l3(T, M, Res) ->
SynLowWeight = ?COL_LEVEL3_MINTOP + M,
if
SynLowWeight < ?COL_LEVEL3_BOUND ->
compress_sort_key_r(T, 3, [SynLowWeight|Res]);
% If a synthetic low weight would not be less than BOUND, use a sequence
% of low weights of the form (BOUND-1)..(BOUND-1)(MINTOP + remainder) to
% express the length of the sequence.
true ->
LowGapSize = ?COL_LEVEL3_BOUND - ?COL_LEVEL3_MINTOP - 2,
SeqCnt = M div LowGapSize,
Remainder = M rem LowGapSize,
compress_sort_key_r(T, 3,
compress_seq(SeqCnt, ?COL_LEVEL3_BOUND - 1,
[(?COL_LEVEL3_MINTOP + Remainder)|Res]))
end.
%% Read all W from Key.
%% If W < COMMON (or there is no W), replace the sequence by a synthetic low
%% weight equal to (MINTOP + m).
%% If W > COMMON, replace the sequence by a synthetic high weight equal to
%% (MAXBOTTOM - m).
-spec compress_sort_key_l2(list(), integer(), list()) -> list().
compress_sort_key_l2([?COL_LEVEL2_COMMON|T], M, Res) ->
compress_sort_key_l2(T, M + 1, Res);
compress_sort_key_l2(T, M, [W|_] = Res)
when (W > ?COL_LEVEL2_MAXBOTTOM) ->
SynHighWeight = ?COL_LEVEL2_MAXBOTTOM - M,
if
% If a synthetic high weight would be less than BOUND, use a
% sequence of high weights of the form (BOUND)..(BOUND)(MAXBOTTOM -
% remainder).
SynHighWeight < ?COL_LEVEL2_BOUND ->
HighGapSize = ?COL_LEVEL2_MAXBOTTOM - ?COL_LEVEL2_BOUND - 1,
SeqCnt = M div HighGapSize,
Remainder = M rem HighGapSize,
compress_sort_key_r(T, 2,
compress_seq(SeqCnt, ?COL_LEVEL2_BOUND,
[(?COL_LEVEL2_MAXBOTTOM - Remainder)|Res]));
true -> compress_sort_key_r(T, 2, [SynHighWeight|Res])
end;
compress_sort_key_l2(T, M, Res) ->
SynLowWeight = ?COL_LEVEL2_MINTOP + M,
if
SynLowWeight < ?COL_LEVEL2_BOUND ->
compress_sort_key_r(T, 2, [SynLowWeight|Res]);
% If a synthetic low weight would not be less than BOUND, use a sequence
% of low weights of the form (BOUND-1)..(BOUND-1)(MINTOP + remainder) to
% express the length of the sequence.
true ->
LowGapSize = ?COL_LEVEL2_BOUND - ?COL_LEVEL2_MINTOP - 2,
SeqCnt = M div LowGapSize,
Remainder = M rem LowGapSize,
compress_sort_key_r(T, 2,
compress_seq(SeqCnt, ?COL_LEVEL2_BOUND - 1,
[(?COL_LEVEL2_MINTOP + Remainder)|Res]))
end.
%% Read all W from Key.
%% If W < COMMON (or there is no W), replace the sequence by a synthetic low
%% weight equal to (MINTOP + m).
%% If W > COMMON, replace the sequence by a synthetic high weight equal to
%% (MAXBOTTOM - m).
-spec compress_sort_key_l4(list(), integer(), list()) -> list().
compress_sort_key_l4([?COL_LEVEL4_COMMON|T], M, Res) ->
compress_sort_key_l4(T, M + 1, Res);
compress_sort_key_l4(T, M, [W|_] = Res)
when (W > ?COL_LEVEL4_MAXBOTTOM) ->
SynHighWeight = ?COL_LEVEL4_MAXBOTTOM - M,
if
% If a synthetic high weight would be less than BOUND, use a
% sequence of high weights of the form (BOUND)..(BOUND)(MAXBOTTOM -
% remainder).
SynHighWeight < ?COL_LEVEL4_BOUND ->
HighGapSize = ?COL_LEVEL4_MAXBOTTOM - ?COL_LEVEL4_BOUND - 1,
SeqCnt = M div HighGapSize,
Remainder = M rem HighGapSize,
compress_sort_key_r(T, 4,
compress_seq(SeqCnt, ?COL_LEVEL4_BOUND,
[(?COL_LEVEL4_MAXBOTTOM - Remainder)|Res]));
true -> compress_sort_key_r(T, 4, [SynHighWeight|Res])
end;
compress_sort_key_l4(T, M, Res) ->
SynLowWeight = ?COL_LEVEL4_MINTOP + M,
if
SynLowWeight < ?COL_LEVEL4_BOUND ->
compress_sort_key_r(T, 4, [SynLowWeight|Res]);
% If a synthetic low weight would not be less than BOUND, use a sequence
% of low weights of the form (BOUND-1)..(BOUND-1)(MINTOP + remainder) to
% express the length of the sequence.
true ->
LowGapSize = ?COL_LEVEL4_BOUND - ?COL_LEVEL4_MINTOP - 2,
SeqCnt = M div LowGapSize,
Remainder = M rem LowGapSize,
compress_sort_key_r(T, 4,
compress_seq(SeqCnt, ?COL_LEVEL4_BOUND - 1,
[(?COL_LEVEL4_MINTOP + Remainder)|Res]))
end.
%% @see compress_sort_key_l3/3
%% @see compress_sort_key_l2/3
%% @doc Add Val to the beginning Cnt times.
%% @private
-spec compress_seq(integer(), integer(), list()) -> list().
compress_seq(1, Val, Res) ->
[Val|Res];
compress_seq(SeqCnt, Val, Res) when SeqCnt > 1 ->
compress_seq(SeqCnt - 1, Val, [Val|Res]).
convert_key_to_bin(Key) when is_list(Key) ->
convert_key_to_bin(Key, 1, []).
%% @doc Key is a list.
%% Level (default 1).
%% @end
-spec convert_key_to_bin(list(), integer(), list()) -> binary().
convert_key_to_bin([0|T], Level, Res) when Level < 4 ->
convert_key_to_bin(T, Level + 1, [0|[0|Res]]);
convert_key_to_bin([H|T], 2, Res) when H < 255 ->
convert_key_to_bin(T, 2, [H|Res]);
convert_key_to_bin([H|T], 3, Res) when H < 255 ->
convert_key_to_bin(T, 3, [H|Res]);
convert_key_to_bin([H|T], 2, Res) when H > 254 ->
convert_key_to_bin([(H - 255)|T], 2, [255|Res]);
convert_key_to_bin([H|T], 3, Res) when H > 254 ->
convert_key_to_bin([(H - 255)|T], 3, [255|Res]);
convert_key_to_bin([H|T], 1, Res) when H =< 16#FFFF ->
convert_key_to_bin(T, 1, [(H rem 256) |[(H bsr 8) |Res]]);
convert_key_to_bin([H|T], 4, Res) when H =< 16#FFFFFF ->
convert_key_to_bin(T, 4,
[(H rem 256)
|[((H bsr 8) rem 256)
|[(H bsr 16)|Res]]]);
convert_key_to_bin([], _Level, Res) ->
erlang:list_to_binary(lists:reverse(Res)).
% http://unicode.org/reports/tr10/#Variable_Weighting
sort_array(Str) when is_list(Str) ->
sort_array(Str, #uca_options {ducet_r_fn = fun ducet_r/1},
fun ducet_r/1, fun bin_to_bin/1).
sort_array(Str, Params = #uca_options{alternate=Alt, ducet_r_fn=DucetRFn})
when is_list(Str) ->
sort_array(Str, Params, DucetRFn, get_comp_fn(Alt)).
sort_array_non_ignorable(Str) when is_list(Str) ->
sort_array(Str, get_options(non_ignorable),
fun ducet_r/1, fun non_ignorable_bin_to_list/1).
sort_array_blanked(Str) when is_list(Str) ->
sort_array(Str, get_options(blanked),
fun ducet_r/1, fun blanked_bin_to_list/1).
sort_array_shifted(Str) when is_list(Str) ->
sort_array(Str, get_options(shifted),
fun ducet_r/1, fun shifted_bin_to_list/1).
sort_array_shift_trimmed(Str) when is_list(Str) ->
sort_array(Str, get_options(shift_trimmed),
fun ducet_r/1, fun shift_trimmed_bin_to_list/1).
%% @doc This function does nothing. :)
%% @private
bin_to_bin(Val) ->
{ fun bin_to_bin/1, Val }.
-spec compare(list(), list()) -> lower | upper | equal.
compare(String1, String2) when is_list(String1), is_list(String2) ->
Params = #uca_options{ducet_r_fn=fun ducet_r/1},
#uca_options{ alternate=Alt } = Params,
compare(String1, String2, Params, fun ducet_r/1, get_comp_fn(Alt)).
compare(String1, String2, #uca_options{
alternate=Alt, ducet_r_fn=DucetRFn} = Params) ->
compare(String1, String2, Params, DucetRFn, get_comp_fn(Alt)).
%% @doc Compare 2 strings.
%% TableFun returns value from DUCET table.
%% ComparatorFun http://unicode.org/reports/tr10/#Variable%20Weighting
%% @end
-spec compare(list(), list(), record(), function(), function())
-> lower | upper | equal.
compare(String1, String2, #uca_options{} = Params, TableFun, ComparatorFun)
when is_function(TableFun), is_function(ComparatorFun),
is_list(String1), is_list(String2) ->
compare1(ux_string:to_nfd(String1),
ux_string:to_nfd(String2),
Params,
[], % Buf 1, contains ducet(Char)
[], % Buf 2
false, % CompValue 1
[], % Accumulator for String 1
% saves values for next levels comparation
[], % Accumulator for String 2
TableFun, % fun ux_string:ducet/1, in chars are REVERSED.
ComparatorFun, ComparatorFun).
%% @doc MANUAL:
%% S2.1 Find the longest initial substring S at each point
%% that has a match in the table.
%% S2.1.1 If there are any non-starters following S, process each non-starter C.
%% S2.1.2 If C is not blocked from S, find if S + C has a match in the table.
%% S2.1.3 If there is a match, replace S by S + C, and remove C.
%%
%% Returns: {Not reversed list of weight elements, Tail of the string}.
%% @end
%% @private
-spec extract(string(), #uca_options{}, fun())
-> {[[integer(), ...], ...], Tail :: string()}.
extract(Str, #uca_options {
hangul_terminator=Term,
natural_sort=DecFlag,
case_sensitive=CaseSenFlag,
case_first=CaseFirst
} = _Params, TableFun) ->
Res = extract0(Str, TableFun),
{Weights, StrTail} = Res,
{Weights2, StrTail2} =
case mod_weights_proxy(Weights, DecFlag, Term, [],
StrTail, TableFun) of
false -> Res;
Res1 -> Res1
end,
Weights3 = case CaseFirst of
off -> Weights2;
lower -> Weights2;
upper -> case_first_hack(Weights2)
end,
Weights4 = case CaseSenFlag of
false -> Weights3;
true -> case_sensitive_hack(Weights3)
end,
{Weights4, StrTail2}.
%% @doc Uppercase to sort before lowercase. Remap L3.
%% @private
case_first_hack(Res) ->
case_first_hack1(Res, []).
%% @private
case_first_hack1([<<Var:8, L1L2:32, L3:16, L4/binary>> | In], Out) ->
NewL3 = case_invert(L3),
case_first_hack1(In, [<<Var:8, L1L2:32, NewL3:16, L4/binary>> | Out]);
case_first_hack1([] = _In, Out) -> lists:reverse(Out);
case_first_hack1([Int | In], Out) when is_integer(Int) ->
case_first_hack1(In, [Int | Out]).
%% @private
case_invert(L3) when L3 >= 2 andalso L3 =< 6 ->
L3 + 6;
case_invert(L3) when L3 >= 8 andalso L3 =< 12 ->
L3 - 6;
case_invert(L3) ->
L3.
%% @doc Copy L3 before L1.
%% @private
case_sensitive_hack(Res) ->
case_sensitive_hack1(Res, []).
%% @private
% Skip primary ignorable element.
% L1 ~ (L1 ++ L3)
case_sensitive_hack1([<<Var:8, L1:16, L2:16, L3:16, L4/binary>> | In], Out) ->
case_sensitive_hack1(In, [<<Var:8, L1:16, L2:16, 0:16, L4/binary>> |
[<<Var:8, L3:16, 0:48>> | Out]]);
case_sensitive_hack1([] = _In, Out) -> lists:reverse(Out);
case_sensitive_hack1([Int | In], Out) when is_integer(Int) ->
case_first_hack1(In, [Int | Out]).
%% @private
mod_weights_proxy(Weights, DecFlag, Term, Acc, StrTail, TableFun) ->
case mod_weights(Weights, DecFlag, Term, Acc, StrTail, TableFun) of
% There is no any hangul jamo L chars in this string
% (or other char with a weight of jamo L char)
{next, {Weights2, Acc2, StrTail2}} ->
mod_weights_proxy(Weights2, DecFlag, Term, Acc2, StrTail2, TableFun);
Res2 -> Res2
end.
% 7.1.5 Hangul Collation
% Interleaving Method
% MANUAL:
% Generate a modified weight table:
% 1. Assign a weight to each precomposed Hangul syllable character,
% with a 1-weight gap between each one.
% (See Section 6.2, Large Weight Values)
% 2. Give each jamo a 1-byte internal weight.
% Also add an internal terminator 1-byte weight (W).
% These are assigned so that al W < T < V < L.
% These weights are separate from the default weights, and are just used
% internally.
% When any string of jamo and/or Hangul syllables is encountered,
% break it into syllables according to the rules of Section 3.12,
% Conjoining Jamo Behavior of [Unicode].
% Process each syllable separately:
% If a syllable is canonically equivalent to one of the precomposed Hangul
% syllables, then just assign the weight as above
% If not, then find the greatest syllable that it is greater than;
% call that the base syllable. Generate a weight sequence corresponding to
% the following gap weight, followed by all the jamo weight bytes,
% followed by the terminator byte.
%
% L1 as an argument is first hangul jamo L.
% L1 as an part of ?IS_L1_OF_HANGUL_L is first level.
%% @private
% Hack for Hangul.
mod_weights([<<_:8, L1:16, _/binary>> = H | T],
_DecFlag, Term, Acc, StrTail, TableFun)
when ?IS_L1_OF_HANGUL_L(L1) ->
hangul2(l, T, [H|Acc], StrTail, TableFun, Term);
% Hack for numbers.
mod_weights([<<_:8, L1:16, _/binary>> = H | T],
true = _DecFlag, _Term, Acc, StrTail, TableFun)
when ?IS_L1_OF_DECIMAL(L1) ->
decimal2(?COL_WEIGHT_TO_DECIMAL(L1), T,
[set_l1_to_value_bin(H, 1)|Acc], StrTail, TableFun);
mod_weights([H|T], DecFlag, Term, Acc, StrTail, TableFun) ->
mod_weights(T, DecFlag, Term, [H|Acc], StrTail, TableFun);
mod_weights([], _DecFlag, _Term, _Acc, _StrTail, _TableFun) ->
false. % L1 is not found. There is no hangul jamo in this string.
decimal2(Dec, [<<_:8, 00:16, _/binary>> = H | T], Acc, StrTail, TableFun) ->
decimal2(Dec, T, [H|Acc], StrTail, TableFun); % skip an ignorable element.
decimal2(Dec, [<<_:8, L1:16, _/binary>> = H | T], Acc, StrTail, TableFun)
when ?IS_L1_OF_DECIMAL(L1) -> % L2 is found. LL*
decimal2((Dec * 10) + ?COL_WEIGHT_TO_DECIMAL(L1), T,
[set_l1_to_value_bin(H, 0)|Acc], StrTail, TableFun);
decimal2(Dec, [], Acc, [_|_] = StrTail, TableFun) ->
{Weights, StrTail2} = extract0(StrTail, TableFun), % We need more gold.
decimal2(Dec, Weights, Acc, StrTail2, TableFun);
decimal2(Dec, T, Acc, StrTail, _TableFun) -> % L
{lists:reverse(lists:reverse(T, decimal_result(Dec, Acc))), StrTail}.
decimal_result(Dec, Res) ->
case Dec div 16#FFFF of
0 -> [1|[Dec|Res]];
Div -> decimal_result(Div, [Dec rem 16#FFFF|[16#FFFF|Res]])
end.
%% L1 was found.
%% Mod: l
%% @private
hangul2(Mod, [<<_:8, 0:16, _/binary>> = H|T], Acc, StrTail, TableFun, Term) ->
% skip an ignorable element.
hangul2(Mod, T, [H|Acc], StrTail, TableFun, Term);
hangul2(l, [<<_:8, L1:16, _/binary>> = H|T], Acc, StrTail, TableFun, Term)
when ?IS_L1_OF_HANGUL_L(L1) -> % L2 is found. LL*
hangul2(ll, T, [H|Acc], StrTail, TableFun, Term);