Repository navigation
Expand file tree
/
Copy pathalpha.c
More file actions
7092 lines (6292 loc) · 223 KB
/
Copy pathalpha.c
File metadata and controls
7092 lines (6292 loc) · 223 KB
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
/*
+----------------------------------------------------------------------+
| Copyright © The PHP Group and Contributors. |
+----------------------------------------------------------------------+
| This source file is subject to the Modified BSD License that is |
| bundled with this package in the file LICENSE, and is available at |
| through the World Wide Web at <https://www.php.net/license/>. |
| |
| SPDX-License-Identifier: BSD-3-Clause |
+----------------------------------------------------------------------+
*/
/* alpha: a standalone extension providing the _alpha parallel-
* implementations of the standard array/search/sort functions. The function
* bodies and helpers below are vendored verbatim from ext/standard/array.c
* and ext/standard/type.c (PHP 8.6); the only changes are:
* - ARRAYG(...) -> ALPHAG(...) (this extension's own module globals,
* so it never touches ext/standard's array module globals);
* - php_multisort_compare -> php_multisort_compare_alpha (a local static
* copy reading ALPHAG(multisort_func), since the PHPAPI original reads
* ARRAYG(multisort_func));
* - the two PHPAPI _alpha recursive merge/replace helpers are made
* `static` (they exist only in this experimental tree, not in stock PHP,
* so a pie-installed shared extension cannot link them).
* The originals in ext/standard are removed (moved here); the baseline
* in_array/array_search/sort/... functions stay untouched in ext/standard. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include <stdarg.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#include "zend_globals.h"
#include "zend_interfaces.h"
#include "zend_smart_str.h"
#include "zend_bitset.h"
#include "zend_exceptions.h"
#include "zend_sort.h"
#include "ext/standard/info.h"
#include "ext/standard/php_string.h"
#include "ext/standard/php_array.h"
#include "ext/standard/php_math.h"
#include "php_alpha.h"
#include "alpha_arginfo.h"
/* Compatibility shims: zend_symtable_add() and zend_dval_to_lval_silent() only
* exist in PHP >= 8.6 (API 20250926). Reproduce their semantics on older API
* versions so the source builds against both header sets. */
#if !defined(ZEND_MODULE_API_NO) || ZEND_MODULE_API_NO < 20250926
static zend_always_inline zval *zend_symtable_add(HashTable *ht, zend_string *key, zval *pData)
{
zend_ulong idx;
if (ZEND_HANDLE_NUMERIC(key, idx)) {
return zend_hash_index_add(ht, idx, pData);
}
return zend_hash_add(ht, key, pData);
}
static zend_always_inline zend_long zend_dval_to_lval_silent(double d)
{
return zend_dval_to_lval(d);
}
/* zend_array_sort_ex() (and its zend_array_sort() inline) is not exported by
* PHP < 8.6 binaries; its exported twin zend_hash_sort() is, and these
* comparators never run user code, so the GC guard difference is moot. */
#define zend_array_sort(ht, compare_func, renumber) \
zend_hash_sort(ht, compare_func, renumber)
#endif
ZEND_DECLARE_MODULE_GLOBALS(alpha)
static void php_alpha_init_globals(zend_alpha_globals *alpha_globals)
{
memset(alpha_globals, 0, sizeof(zend_alpha_globals));
}
PHP_MINIT_FUNCTION(alpha)
{
ZEND_INIT_MODULE_GLOBALS(alpha, php_alpha_init_globals, NULL);
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(alpha)
{
#ifdef ZTS
ts_free_id(alpha_globals_id);
#endif
return SUCCESS;
}
PHP_MINFO_FUNCTION(alpha)
{
php_info_print_table_start();
php_info_print_table_header(2, "alpha", "enabled");
php_info_print_table_row(2, "_alpha functions", "39 parallel reimplementations of standard array/search/sort");
php_info_print_table_end();
}
zend_module_entry alpha_module_entry = {
STANDARD_MODULE_HEADER,
"alpha",
ext_functions,
PHP_MINIT(alpha),
PHP_MSHUTDOWN(alpha),
NULL, /* RINIT */
NULL, /* RSHUTDOWN */
PHP_MINFO(alpha),
PHP_ALPHA_VERSION,
STANDARD_MODULE_PROPERTIES
};
#ifdef COMPILE_DL_ALPHA
ZEND_GET_MODULE(alpha)
# if defined(ZTS)
ZEND_TSRMLS_CACHE_DEFINE()
# endif
#endif
/* ===================================================================== *
* Vendored comparator/sort/natural-sort machinery and _alpha function
* bodies follow. Order preserves the original ext/standard/array.c layout
* so static definitions precede their uses.
* ===================================================================== */
/* ===== blockA_comparators (array.c 100-1070) ===== */
static zend_never_inline ZEND_COLD int stable_sort_fallback(Bucket *a, Bucket *b) {
if (Z_EXTRA(a->val) > Z_EXTRA(b->val)) {
return 1;
} else if (Z_EXTRA(a->val) < Z_EXTRA(b->val)) {
return -1;
} else {
return 0;
}
}
#define RETURN_STABLE_SORT(a, b, result) do { \
int _result = (result); \
if (EXPECTED(_result)) { \
return _result; \
} \
return stable_sort_fallback((a), (b)); \
} while (0)
/* Generate inlined unstable and stable variants, and non-inlined reversed variants. */
#define DEFINE_SORT_VARIANTS(name) \
static zend_never_inline int php_array_##name##_unstable(Bucket *a, Bucket *b) { \
return php_array_##name##_unstable_i(a, b); \
} \
static zend_never_inline int php_array_##name(Bucket *a, Bucket *b) { \
RETURN_STABLE_SORT(a, b, php_array_##name##_unstable_i(a, b)); \
} \
static zend_never_inline int php_array_reverse_##name##_unstable(Bucket *a, Bucket *b) { \
return php_array_##name##_unstable(a, b) * -1; \
} \
static zend_never_inline int php_array_reverse_##name(Bucket *a, Bucket *b) { \
RETURN_STABLE_SORT(a, b, php_array_reverse_##name##_unstable(a, b)); \
} \
static zend_always_inline int php_array_key_compare_unstable_i(Bucket *f, Bucket *s) /* {{{ */
{
zval first;
zval second;
if (f->key == NULL && s->key == NULL) {
return (zend_long)f->h > (zend_long)s->h ? 1 : -1;
} else if (f->key && s->key) {
return zendi_smart_strcmp(f->key, s->key);
}
if (f->key) {
ZVAL_STR(&first, f->key);
} else {
ZVAL_LONG(&first, f->h);
}
if (s->key) {
ZVAL_STR(&second, s->key);
} else {
ZVAL_LONG(&second, s->h);
}
return zend_compare(&first, &second);
}
/* }}} */
static zend_always_inline int php_array_key_compare_numeric_unstable_i(Bucket *f, Bucket *s) /* {{{ */
{
if (f->key == NULL && s->key == NULL) {
return (zend_long)f->h > (zend_long)s->h ? 1 : -1;
} else {
double d1, d2;
if (f->key) {
d1 = zend_strtod(f->key->val, NULL);
} else {
d1 = (double)(zend_long)f->h;
}
if (s->key) {
d2 = zend_strtod(s->key->val, NULL);
} else {
d2 = (double)(zend_long)s->h;
}
return ZEND_THREEWAY_COMPARE(d1, d2);
}
}
/* }}} */
static zend_always_inline int php_array_key_compare_string_case_unstable_i(Bucket *f, Bucket *s) /* {{{ */
{
const char *s1, *s2;
size_t l1, l2;
char buf1[MAX_LENGTH_OF_LONG + 1];
char buf2[MAX_LENGTH_OF_LONG + 1];
if (f->key) {
s1 = f->key->val;
l1 = f->key->len;
} else {
s1 = zend_print_long_to_buf(buf1 + sizeof(buf1) - 1, f->h);
l1 = buf1 + sizeof(buf1) - 1 - s1;
}
if (s->key) {
s2 = s->key->val;
l2 = s->key->len;
} else {
s2 = zend_print_long_to_buf(buf2 + sizeof(buf2) - 1, s->h);
l2 = buf2 + sizeof(buf2) - 1 - s2;
}
return zend_binary_strcasecmp_l(s1, l1, s2, l2);
}
/* }}} */
static zend_always_inline int php_array_key_compare_string_unstable_i(Bucket *f, Bucket *s) /* {{{ */
{
const char *s1, *s2;
size_t l1, l2;
char buf1[MAX_LENGTH_OF_LONG + 1];
char buf2[MAX_LENGTH_OF_LONG + 1];
if (f->key) {
s1 = f->key->val;
l1 = f->key->len;
} else {
s1 = zend_print_long_to_buf(buf1 + sizeof(buf1) - 1, f->h);
l1 = buf1 + sizeof(buf1) - 1 - s1;
}
if (s->key) {
s2 = s->key->val;
l2 = s->key->len;
} else {
s2 = zend_print_long_to_buf(buf2 + sizeof(buf2) - 1, s->h);
l2 = buf2 + sizeof(buf2) - 1 - s2;
}
return zend_binary_strcmp(s1, l1, s2, l2);
}
/* }}} */
static int php_array_key_compare_string_natural_general(Bucket *f, Bucket *s, bool fold_case) /* {{{ */
{
const char *s1, *s2;
size_t l1, l2;
char buf1[MAX_LENGTH_OF_LONG + 1];
char buf2[MAX_LENGTH_OF_LONG + 1];
if (f->key) {
s1 = f->key->val;
l1 = f->key->len;
} else {
s1 = zend_print_long_to_buf(buf1 + sizeof(buf1) - 1, f->h);
l1 = buf1 + sizeof(buf1) - 1 - s1;
}
if (s->key) {
s2 = s->key->val;
l2 = s->key->len;
} else {
s2 = zend_print_long_to_buf(buf2 + sizeof(buf2) - 1, s->h);
l2 = buf2 + sizeof(buf2) - 1 - s2;
}
return strnatcmp_ex(s1, l1, s2, l2, fold_case);
}
/* }}} */
static int php_array_key_compare_string_natural_case(Bucket *a, Bucket *b) /* {{{ */
{
RETURN_STABLE_SORT(a, b, php_array_key_compare_string_natural_general(a, b, true));
}
/* }}} */
static int php_array_reverse_key_compare_string_natural_case(Bucket *a, Bucket *b) /* {{{ */
{
RETURN_STABLE_SORT(a, b, php_array_key_compare_string_natural_general(b, a, true));
}
/* }}} */
static int php_array_key_compare_string_natural(Bucket *a, Bucket *b) /* {{{ */
{
RETURN_STABLE_SORT(a, b, php_array_key_compare_string_natural_general(a, b, false));
}
/* }}} */
static int php_array_reverse_key_compare_string_natural(Bucket *a, Bucket *b) /* {{{ */
{
RETURN_STABLE_SORT(a, b, php_array_key_compare_string_natural_general(b, a, false));
}
/* }}} */
static zend_always_inline int php_array_key_compare_string_locale_unstable_i(Bucket *f, Bucket *s) /* {{{ */
{
const char *s1, *s2;
char buf1[MAX_LENGTH_OF_LONG + 1];
char buf2[MAX_LENGTH_OF_LONG + 1];
if (f->key) {
s1 = f->key->val;
} else {
s1 = zend_print_long_to_buf(buf1 + sizeof(buf1) - 1, f->h);
}
if (s->key) {
s2 = s->key->val;
} else {
s2 = zend_print_long_to_buf(buf2 + sizeof(buf2) - 1, s->h);
}
return strcoll(s1, s2);
}
/* }}} */
static zend_always_inline int php_array_data_compare_unstable_i(Bucket *f, Bucket *s) /* {{{ */
{
int result = zend_compare(&f->val, &s->val);
/* Special enums handling for array_unique. We don't want to add this logic to zend_compare as
* that would be observable via comparison operators. */
zval *rhs = &s->val;
ZVAL_DEREF(rhs);
if (UNEXPECTED(Z_TYPE_P(rhs) == IS_OBJECT)
&& result == ZEND_UNCOMPARABLE
&& (Z_OBJCE_P(rhs)->ce_flags & ZEND_ACC_ENUM)) {
zval *lhs = &f->val;
ZVAL_DEREF(lhs);
if (Z_TYPE_P(lhs) == IS_OBJECT && (Z_OBJCE_P(lhs)->ce_flags & ZEND_ACC_ENUM)) {
// Order doesn't matter, we just need to group the same enum values
uintptr_t lhs_uintptr = (uintptr_t)Z_OBJ_P(lhs);
uintptr_t rhs_uintptr = (uintptr_t)Z_OBJ_P(rhs);
return lhs_uintptr == rhs_uintptr ? 0 : (lhs_uintptr < rhs_uintptr ? -1 : 1);
} else {
// Shift enums to the end of the array
return -1;
}
}
return result;
}
/* }}} */
static zend_always_inline int php_array_data_compare_long_unstable_i(Bucket *f, Bucket *s) /* {{{ */
{
/* Exact integer three-way compare, mirroring zend_compare()'s IS_LONG/IS_LONG
* arm. Unlike numeric_compare_function() (which promotes to double via
* zval_get_double), this stays exact for longs beyond 2^53. Safe only when
* the caller has verified every element is IS_LONG and free of references. */
zend_long a = Z_LVAL_P(&f->val);
zend_long b = Z_LVAL_P(&s->val);
return a > b ? 1 : (a < b ? -1 : 0);
}
/* }}} */
static zend_always_inline int php_array_data_compare_numeric_unstable_i(Bucket *f, Bucket *s) /* {{{ */
{
return numeric_compare_function(&f->val, &s->val);
}
/* }}} */
static zend_always_inline int php_array_data_compare_string_case_unstable_i(Bucket *f, Bucket *s) /* {{{ */
{
return string_case_compare_function(&f->val, &s->val);
}
/* }}} */
static zend_always_inline int php_array_data_compare_string_unstable_i(Bucket *f, Bucket *s) /* {{{ */
{
return string_compare_function(&f->val, &s->val);
}
/* }}} */
static int php_array_natural_general_compare(Bucket *f, Bucket *s, bool fold_case) /* {{{ */
{
zend_string *tmp_str1, *tmp_str2;
zend_string *str1 = zval_get_tmp_string(&f->val, &tmp_str1);
zend_string *str2 = zval_get_tmp_string(&s->val, &tmp_str2);
int result = strnatcmp_ex(ZSTR_VAL(str1), ZSTR_LEN(str1), ZSTR_VAL(str2), ZSTR_LEN(str2), fold_case);
zend_tmp_string_release(tmp_str1);
zend_tmp_string_release(tmp_str2);
return result;
}
/* }}} */
static zend_always_inline int php_array_natural_compare_unstable_i(Bucket *a, Bucket *b) /* {{{ */
{
return php_array_natural_general_compare(a, b, false);
}
/* }}} */
static zend_always_inline int php_array_natural_case_compare_unstable_i(Bucket *a, Bucket *b) /* {{{ */
{
return php_array_natural_general_compare(a, b, true);
}
/* }}} */
/* _alpha pre-classified Schwartzian transform for the natural comparators.
*
* The baseline php_array_natural_general_compare calls strnatcmp_ex on every
* O(n log n) comparison, and strnatcmp_ex re-parses both strings each call --
* per byte it pays an isdigit()/isspace() libc table lookup (a __ctype_b_loc()
* TLS fetch + index + mask) and, for the case-insensitive variant, a toupper().
* Each element's string is therefore classified ~log2(n) times.
*
* This path classifies each string ONCE, up front, into a decoration:
*
* - buf: the byte stream the comparator walks. For natcasesort_alpha every
* byte is toupper() applied at decoration time, so the comparator never
* touppers; for natsort_alpha buf is the original bytes. The first
* digit run's leading zeros are stripped (strnatcmp_ex's
* start-of-string strip, lines 105-112), which is deterministic per
* string and so can be baked in. buf is NUL-terminated at blen.
* - cls: a parallel per-byte class byte (OTHER / DIGIT / SPACE), with
* cls[blen] = OTHER so the NUL sentinel terminates whitespace skips the
* same way strnatcmp_ex's NUL terminator does.
* - orig_len: the original byte length, to replicate strnatcmp_ex's empty-string
* fast path `if (a_len==0 || b_len==0) return sign(a_len-b_len)`.
* toupper() never changes digit/space membership, so a class map
* computed on the folded byte equals the class strnatcmp_ex computes on
* the original; non-C ctype locales are preserved because the same
* isdigit()/isspace() calls are used, just hoisted out of the comparison.
*
* The comparator (php_natcmp_cls) is a faithful line-for-line port of strnatcmp_ex
* operating on (buf, cls): isdigit(c) -> cls[i]==DIGIT, isspace(c) ->
* cls[i]==SPACE, toupper() removed (folded into buf). It preserves strnatcmp_ex's
* RELATIONAL digit-run rule -- a run is compared numerically only when BOTH sides
* are digits at the aligned position; a digit vs a non-digit falls through to raw
* byte comparison -- which is exactly why a flat memcmp-able sort key is
* impossible (any per-string key must commit to "numeric" or "raw" without knowing
* its partner) and why we decorate with buffers + a relational comparator instead.
* The trailing-whitespace end checks and the fall-through (not continue) after a
* digit-run tie are preserved verbatim.
*
* The decoration recs[] is indexed by the SAME original bucket position that
* zend_hash_sort_internal stores in Z_EXTRA (it sets Z_EXTRA(arData[i].val)=i
* before sorting), so the bucket comparator recovers its decoration via
* Z_EXTRA(a->val) and reuses Z_EXTRA as the stable tie-break key. The recs base is
* stashed per-thread in ALPHAG(nat_sort_recs) for the comparator (the
* bucket_compare_func_t signature carries no context); natsort never recurses
* across the comparator. Only natsort_alpha / natcasesort_alpha reach this path;
* the baseline natsort / natcasesort and strnatcmp_ex stay untouched. */
#define NAT_CLASS_OTHER 0
#define NAT_CLASS_DIGIT 1
#define NAT_CLASS_SPACE 2
typedef struct {
uint32_t orig_len; /* original byte length, for the empty fast path */
uint32_t blen; /* logical length of buf (after leading-zero strip) */
const unsigned char *buf; /* blen+1 bytes, NUL-terminated, folded/stripped */
const unsigned char *cls; /* blen+1 bytes, per-position class; cls[blen]=OTHER */
} php_nat_rec;
/* Port of compare_left (strnatcmp.c:64): left-aligned numeric comparison -- the
* first differing digit wins; if one run ends first, it is smaller. ap/ac and
* bp/bc advance in lockstep; on return they point at the first post-run byte. */
static zend_always_inline int php_natcmp_compare_left_cls(
const unsigned char **ap, const unsigned char **ac,
const unsigned char **bp, const unsigned char **bc) /* {{{ */
{
for (;;) {
bool adig = (**ac == NAT_CLASS_DIGIT);
bool bdig = (**bc == NAT_CLASS_DIGIT);
if (!adig && !bdig) {
return 0;
} else if (!adig) {
return -1;
} else if (!bdig) {
return 1;
} else if (**ap < **bp) {
return -1;
} else if (**ap > **bp) {
return 1;
}
++*ap; ++*ac; ++*bp; ++*bc;
}
}
/* }}} */
/* Port of compare_right (strnatcmp.c:33): the longest run of digits wins; aside
* from that, the greater value wins, remembered in bias. ap/ac and bp/bc advance
* in lockstep; on return they point at the first post-run byte. */
static zend_always_inline int php_natcmp_compare_right_cls(
const unsigned char **ap, const unsigned char **ac,
const unsigned char **bp, const unsigned char **bc) /* {{{ */
{
int bias = 0;
for (;;) {
bool adig = (**ac == NAT_CLASS_DIGIT);
bool bdig = (**bc == NAT_CLASS_DIGIT);
if (!adig && !bdig) {
return bias;
} else if (!adig) {
return -1;
} else if (!bdig) {
return 1;
} else if (**ap < **bp) {
if (!bias) {
bias = -1;
}
} else if (**ap > **bp) {
if (!bias) {
bias = 1;
}
}
++*ap; ++*ac; ++*bp; ++*bc;
}
}
/* }}} */
/* Faithful port of strnatcmp_ex (strnatcmp.c:88) on pre-classified buffers. The
* leading-zero strip and case folding are already baked into buf, so this body is
* the case-sensitive shape; natcasesort_alpha folds at decoration time and so
* reuses this same comparator. Returns -1/0/+1, ==0 iff strnatcmp_ex would. */
static zend_never_inline int php_natcmp_cls(const php_nat_rec *ra, const php_nat_rec *rb) /* {{{ */
{
if (ra->orig_len == 0 || rb->orig_len == 0) {
return ZEND_THREEWAY_COMPARE(ra->orig_len, rb->orig_len);
}
const unsigned char *ap = ra->buf, *ac = ra->cls;
const unsigned char *bp = rb->buf, *bc = rb->cls;
const unsigned char *aend = ra->buf + ra->blen;
const unsigned char *bend = rb->buf + rb->blen;
unsigned char ca = *ap, cb = *bp;
for (;;) {
/* Skip consecutive whitespace on each side independently. */
while (*ac == NAT_CLASS_SPACE) {
++ap; ++ac; ca = *ap;
}
while (*bc == NAT_CLASS_SPACE) {
++bp; ++bc; cb = *bp;
}
/* Process run of digits, but only when BOTH sides are digits here --
* the relational rule that makes a flat sort key impossible. */
if (*ac == NAT_CLASS_DIGIT && *bc == NAT_CLASS_DIGIT) {
int result;
bool fractional = (ca == '0' || cb == '0');
if (fractional) {
result = php_natcmp_compare_left_cls(&ap, &ac, &bp, &bc);
} else {
result = php_natcmp_compare_right_cls(&ap, &ac, &bp, &bc);
}
if (result != 0) {
return result;
} else if (ap == aend && bp == bend) {
return 0;
} else if (ap == aend) {
return -1;
} else if (bp == bend) {
return 1;
} else {
/* Keep on comparing from the current point. */
ca = *ap; cb = *bp;
}
}
/* (No toupper: buf is pre-folded for natcasesort_alpha.) */
if (ca < cb) {
return -1;
} else if (ca > cb) {
return 1;
}
++ap; ++ac; ++bp; ++bc;
if (ap >= aend && bp >= bend) {
return 0;
} else if (ap >= aend) {
return -1;
} else if (bp >= bend) {
return 1;
}
ca = *ap; cb = *bp;
}
}
/* }}} */
/* Bucket comparator for zend_array_sort: recover each bucket's decoration via the
* original position stored in Z_EXTRA (set by zend_hash_sort_internal), and reuse
* that same Z_EXTRA as the stable tie-break key -- exactly what the baseline's
* RETURN_STABLE_SORT/stable_sort_fallback does. Equivalent to the baseline stable
* comparator iff php_natcmp_cls matches strnatcmp_ex sign-for-sign. */
static int php_array_natural_compare_cls(Bucket *a, Bucket *b) /* {{{ */
{
const php_nat_rec *recs = (const php_nat_rec *) ALPHAG(nat_sort_recs);
uint32_t ia = Z_EXTRA(a->val);
uint32_t ib = Z_EXTRA(b->val);
int result = php_natcmp_cls(&recs[ia], &recs[ib]);
if (result) {
return result;
}
return ZEND_THREEWAY_COMPARE(ia, ib);
}
/* }}} */
/* Build the decoration for an all-string, no-reference, hole-free array. Returns
* the recs array and, via data_out, the single contiguous buffer holding every
* element's (buf, cls). Returns NULL (with *data_out = NULL) if any value is not a
* plain IS_STRING or is a reference, so the caller falls back to the baseline.
* recs[i] corresponds to the i-th element in iteration order; zend_hash_sort_internal
* converts a packed array to a hash (preserving order) before setting
* Z_EXTRA(arData[i].val)=i, so recs[i] stays aligned with the Z_EXTRA index the
* comparator reads. */
static zend_always_inline zval *php_nat_zval_at(HashTable *ht, uint32_t i) /* {{{ */
{
return HT_IS_PACKED(ht) ? &ht->arPacked[i] : &ht->arData[i].val;
}
/* }}} */
static php_nat_rec *php_nat_build_recs(HashTable *ht, bool fold_case, unsigned char **data_out) /* {{{ */
{
uint32_t n = ht->nNumUsed;
php_nat_rec *recs = emalloc(n * sizeof(php_nat_rec));
size_t total = 0;
uint32_t i;
for (i = 0; i < n; i++) {
zval *zv = php_nat_zval_at(ht, i);
if (UNEXPECTED(Z_TYPE_P(zv) == IS_REFERENCE) || UNEXPECTED(Z_TYPE_P(zv) != IS_STRING)) {
efree(recs);
*data_out = NULL;
return NULL;
}
zend_string *s = Z_STR_P(zv);
const unsigned char *src = (const unsigned char *) ZSTR_VAL(s);
size_t len = ZSTR_LEN(s);
size_t start = 0;
while (start + 1 < len && src[start] == '0' && isdigit(src[start + 1])) {
start++;
}
recs[i].orig_len = (uint32_t) len;
recs[i].blen = (uint32_t) (len - start);
total += (size_t) (recs[i].blen + 1) * 2;
}
unsigned char *data = emalloc(total);
unsigned char *p = data;
for (i = 0; i < n; i++) {
zend_string *s = Z_STR_P(php_nat_zval_at(ht, i));
const unsigned char *src = (const unsigned char *) ZSTR_VAL(s);
size_t len = recs[i].orig_len;
size_t start = 0;
while (start + 1 < len && src[start] == '0' && isdigit(src[start + 1])) {
start++;
}
uint32_t blen = recs[i].blen;
unsigned char *buf = p;
unsigned char *cls = p + blen + 1;
for (uint32_t k = 0; k < blen; k++) {
unsigned char c = src[start + k];
if (fold_case) {
c = toupper(c);
}
buf[k] = c;
cls[k] = isdigit(c) ? NAT_CLASS_DIGIT : (isspace(c) ? NAT_CLASS_SPACE : NAT_CLASS_OTHER);
}
buf[blen] = 0;
cls[blen] = NAT_CLASS_OTHER;
recs[i].buf = buf;
recs[i].cls = cls;
p += (size_t) (blen + 1) * 2;
}
*data_out = data;
return recs;
}
/* }}} */
static void php_nat_free_recs(php_nat_rec *recs, unsigned char *data) /* {{{ */
{
if (data) {
efree(data);
}
if (recs) {
efree(recs);
}
}
/* }}} */
static int php_array_data_compare_string_locale_unstable_i(Bucket *f, Bucket *s) /* {{{ */
{
return string_locale_compare_function(&f->val, &s->val);
}
/* }}} */
/* _alpha key-compare specialization: all-integer keys (Bucket.key == NULL for
* every element to be sorted). Mirrors php_array_data_compare_long_unstable_i:
* exact integer three-way compare, no double promotion (correct beyond 2^53).
*
* These are hand-written single-frame comparators rather than produced by
* DEFINE_SORT_VARIANTS, so the REVERSE variant collapses the two extra
* zend_never_inline intermediates the macro-generated reverse path adds
* (php_array_reverse_key_compare -> ..._reverse_unstable -> ..._unstable)
* into a single frame. Each comparison is then one indirect call -> one
* never_inline body -> the inlined leaf. Keys are unique in a HashTable, so
* the result is never 0 and stable_sort_fallback never fires here; the
* RETURN_STABLE_SORT shape is kept for consistency with the other comparators.
* Only ksort_alpha / krsort_alpha reach these; the baseline key comparators
* and their callers stay untouched. */
static zend_always_inline int php_array_key_compare_long_i(Bucket *f, Bucket *s) /* {{{ */
{
zend_long a = (zend_long)f->h;
zend_long b = (zend_long)s->h;
return a > b ? 1 : (a < b ? -1 : 0);
}
/* }}} */
static zend_never_inline int php_array_key_compare_long(Bucket *a, Bucket *b) /* {{{ */
{
RETURN_STABLE_SORT(a, b, php_array_key_compare_long_i(a, b));
}
/* }}} */
/* Reverse via operand swap (like the natural-comparator family), not a
* multiply, so it stays a single frame mirroring the forward variant. */
static zend_never_inline int php_array_reverse_key_compare_long(Bucket *a, Bucket *b) /* {{{ */
{
RETURN_STABLE_SORT(a, b, php_array_key_compare_long_i(b, a));
}
/* }}} */
DEFINE_SORT_VARIANTS(key_compare);
DEFINE_SORT_VARIANTS(key_compare_numeric);
DEFINE_SORT_VARIANTS(key_compare_string_case);
DEFINE_SORT_VARIANTS(key_compare_string);
DEFINE_SORT_VARIANTS(key_compare_string_locale);
DEFINE_SORT_VARIANTS(data_compare);
/* Forward (asort_alpha) and reverse (arsort_alpha) consumers both exist, so
* generate the full data_compare_long family: forward php_array_data_compare_long
* and reverse php_array_reverse_data_compare_long, each with an unstable sibling.
* All four are built from the always_inline _i helper by DEFINE_SORT_VARIANTS. */
DEFINE_SORT_VARIANTS(data_compare_long);
DEFINE_SORT_VARIANTS(data_compare_numeric);
DEFINE_SORT_VARIANTS(data_compare_string_case);
DEFINE_SORT_VARIANTS(data_compare_string);
DEFINE_SORT_VARIANTS(data_compare_string_locale);
DEFINE_SORT_VARIANTS(natural_compare);
DEFINE_SORT_VARIANTS(natural_case_compare);
static bucket_compare_func_t php_get_key_compare_func(zend_long sort_type)
{
switch (sort_type & ~PHP_SORT_FLAG_CASE) {
case PHP_SORT_NUMERIC:
return php_array_key_compare_numeric;
case PHP_SORT_STRING:
if (sort_type & PHP_SORT_FLAG_CASE) {
return php_array_key_compare_string_case;
} else {
return php_array_key_compare_string;
}
case PHP_SORT_NATURAL:
if (sort_type & PHP_SORT_FLAG_CASE) {
return php_array_key_compare_string_natural_case;
} else {
return php_array_key_compare_string_natural;
}
case PHP_SORT_LOCALE_STRING:
return php_array_key_compare_string_locale;
case PHP_SORT_REGULAR:
default:
return php_array_key_compare;
}
return NULL;
}
static bucket_compare_func_t php_get_key_reverse_compare_func(zend_long sort_type)
{
switch (sort_type & ~PHP_SORT_FLAG_CASE) {
case PHP_SORT_NUMERIC:
return php_array_reverse_key_compare_numeric;
case PHP_SORT_STRING:
if (sort_type & PHP_SORT_FLAG_CASE) {
return php_array_reverse_key_compare_string_case;
} else {
return php_array_reverse_key_compare_string;
}
case PHP_SORT_NATURAL:
if (sort_type & PHP_SORT_FLAG_CASE) {
return php_array_reverse_key_compare_string_natural_case;
} else {
return php_array_reverse_key_compare_string_natural;
}
case PHP_SORT_LOCALE_STRING:
return php_array_reverse_key_compare_string_locale;
case PHP_SORT_REGULAR:
default:
return php_array_reverse_key_compare;
}
return NULL;
}
static bucket_compare_func_t php_get_data_compare_func(zend_long sort_type) /* {{{ */
{
switch (sort_type & ~PHP_SORT_FLAG_CASE) {
case PHP_SORT_NUMERIC:
return php_array_data_compare_numeric;
case PHP_SORT_STRING:
if (sort_type & PHP_SORT_FLAG_CASE) {
return php_array_data_compare_string_case;
} else {
return php_array_data_compare_string;
}
case PHP_SORT_NATURAL:
if (sort_type & PHP_SORT_FLAG_CASE) {
return php_array_natural_case_compare;
} else {
return php_array_natural_compare;
}
case PHP_SORT_LOCALE_STRING:
return php_array_data_compare_string_locale;
case PHP_SORT_REGULAR:
default:
return php_array_data_compare;
}
return NULL;
}
static bucket_compare_func_t php_get_data_reverse_compare_func(zend_long sort_type) /* {{{ */
{
switch (sort_type & ~PHP_SORT_FLAG_CASE) {
case PHP_SORT_NUMERIC:
return php_array_reverse_data_compare_numeric;
case PHP_SORT_STRING:
if (sort_type & PHP_SORT_FLAG_CASE) {
return php_array_reverse_data_compare_string_case;
} else {
return php_array_reverse_data_compare_string;
}
case PHP_SORT_NATURAL:
if (sort_type & PHP_SORT_FLAG_CASE) {
return php_array_reverse_natural_case_compare;
} else {
return php_array_reverse_natural_compare;
}
case PHP_SORT_LOCALE_STRING:
return php_array_reverse_data_compare_string_locale;
case PHP_SORT_REGULAR:
default:
return php_array_reverse_data_compare;
}
return NULL;
}
/* _alpha sibling of php_get_data_reverse_compare_func: for the default
* SORT_REGULAR, scan the array's value types once and return a reverse
* comparator specialized to a homogeneous scalar kind, skipping zend_compare's
* per-comparison type dispatch on the O(n log n) sort. Returns NULL to let the
* caller fall back to the exact baseline comparator.
*
* all IS_LONG -> php_array_reverse_data_compare_long (exact integer compare;
* numeric_compare_function would
* misorder longs beyond 2^53)
* all IS_DOUBLE -> php_array_reverse_data_compare_numeric (matches zend_compare
* IS_DOUBLE/IS_DOUBLE exactly)
*
* Strings are deliberately NOT specialized: under SORT_REGULAR, zend_compare()
* compares two numeric strings numerically ('100' > '20' > '9'), a per-pair
* rule that no simpler comparator replicates -- only zend_compare() itself is
* correct, so the string case falls back to the baseline.
*
* Any reference, non-scalar (object/array/null/bool/resource), mixed scalar
* kind, or hole also falls back to the baseline. References are excluded from
* the fast paths to keep the specialized hot comparators branch-free (the long
* comparator reads Z_LVAL directly, which is only valid without a ref wrapper).
* Only arsort_alpha reaches this helper; the original comparator selectors and
* their callers stay untouched. */
static bucket_compare_func_t php_get_specialized_data_reverse_compare_func(HashTable *ht) /* {{{ */
{
if (ht->nNumOfElements < 2) {
return NULL;
}
int kind = 0; /* 0=unknown, 1=long, 2=double */
zval *zv;
ZEND_HASH_FOREACH_VAL(ht, zv) {
if (UNEXPECTED(Z_TYPE_P(zv) == IS_UNDEF)) {
continue;
}
if (UNEXPECTED(Z_TYPE_P(zv) == IS_REFERENCE)) {
return NULL;
}
int k;
switch (Z_TYPE_P(zv)) {
case IS_LONG: k = 1; break;
case IS_DOUBLE: k = 2; break;
default: return NULL;
}
if (kind == 0) {
kind = k;
} else if (kind != k) {
return NULL;
}
} ZEND_HASH_FOREACH_END();
switch (kind) {
case 1: return php_array_reverse_data_compare_long;
case 2: return php_array_reverse_data_compare_numeric;
default: return NULL;
}
}
/* }}} */
/* _alpha sibling of php_get_data_compare_func: for the default SORT_REGULAR,
* scan the array's value types once and return a forward (ascending)
* comparator specialized to a homogeneous scalar kind, skipping zend_compare's
* per-comparison type dispatch on the O(n log n) sort. Returns NULL to let the
* caller fall back to the exact baseline comparator.
*
* all IS_LONG -> php_array_data_compare_long (exact integer compare;
* numeric_compare_function would
* misorder longs beyond 2^53)
* all IS_DOUBLE -> php_array_data_compare_numeric (matches zend_compare
* IS_DOUBLE/IS_DOUBLE exactly)
*
* Strings are deliberately NOT specialized: under SORT_REGULAR, zend_compare()
* compares two numeric strings numerically ('100' > '20' > '9'), a per-pair
* rule that no simpler comparator replicates -- only zend_compare() itself is
* correct, so the string case falls back to the baseline.
*
* Any reference, non-scalar (object/array/null/bool/resource), mixed scalar
* kind, or hole also falls back to the baseline. References are excluded from
* the fast paths to keep the specialized hot comparators branch-free (the long
* comparator reads Z_LVAL directly, which is only valid without a ref wrapper).
* Only asort_alpha reaches this helper; the original comparator selectors and
* their callers stay untouched. */
static bucket_compare_func_t php_get_specialized_data_compare_func(HashTable *ht) /* {{{ */
{
if (ht->nNumOfElements < 2) {
return NULL;
}
int kind = 0; /* 0=unknown, 1=long, 2=double */
zval *zv;
ZEND_HASH_FOREACH_VAL(ht, zv) {
if (UNEXPECTED(Z_TYPE_P(zv) == IS_UNDEF)) {
continue;
}
if (UNEXPECTED(Z_TYPE_P(zv) == IS_REFERENCE)) {
return NULL;
}
int k;
switch (Z_TYPE_P(zv)) {
case IS_LONG: k = 1; break;
case IS_DOUBLE: k = 2; break;
default: return NULL;
}
if (kind == 0) {
kind = k;
} else if (kind != k) {
return NULL;
}
} ZEND_HASH_FOREACH_END();
switch (kind) {
case 1: return php_array_data_compare_long;
case 2: return php_array_data_compare_numeric;
default: return NULL;
}
}
/* }}} */