-
Notifications
You must be signed in to change notification settings - Fork 64
/
stringzilla.h
1273 lines (1104 loc) 路 54.8 KB
/
stringzilla.h
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
#ifndef STRINGZILLA_H_
#define STRINGZILLA_H_
#if defined(__AVX2__)
#include <x86intrin.h>
#endif
#if defined(__ARM_NEON)
#include <arm_neon.h>
#endif
#if defined(__ARM_FEATURE_CRC32)
#include <arm_acle.h>
#endif
/**
* Intrinsics aliases for MSVC, GCC, and Clang.
*/
#ifdef _MSC_VER
#include <intrin.h>
#define popcount64 __popcnt64
#define ctz64 _tzcnt_u64
#define clz64 _lzcnt_u64
#else
#define popcount64 __builtin_popcountll
#define ctz64 __builtin_ctzll
#define clz64 __builtin_clzll
#endif
/**
* @brief Generally `NULL` is coming from locale.h, stddef.h, stdio.h, stdlib.h, string.h, time.h, and wchar.h,
* according to the C standard.
*/
#ifndef NULL
#define NULL ((void *)0)
#endif
/**
* @brief Compile-time assert macro.
*/
#define SZ_STATIC_ASSERT(condition, name) \
typedef struct { \
int static_assert_##name : (condition) ? 1 : -1; \
} sz_static_assert_##name##_t
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Analogous to `sz_size_t` and `std::sz_size_t`, unsigned integer, identical to pointer size.
* 64-bit on most platforms where pointers are 64-bit.
* 32-bit on platforms where pointers are 32-bit.
*/
#if defined(__LP64__) || defined(_LP64) || defined(__x86_64__) || defined(_WIN64)
typedef unsigned long long sz_size_t;
#else
typedef unsigned sz_size_t;
#endif
SZ_STATIC_ASSERT(sizeof(sz_size_t) == sizeof(void *), sz_size_t_must_be_pointer_size);
typedef int sz_bool_t; // Only one relevant bit
typedef unsigned sz_u32_t; // Always 32 bits
typedef unsigned long long sz_u64_t; // Always 64 bits
typedef char const *sz_string_start_t; // A type alias for `char const * `
/**
* @brief For faster bounded Levenstein (Edit) distance computation no more than 255 characters are supported.
*/
typedef unsigned char levenstein_distance_t;
/**
* @brief Helper construct for higher-level bindings.
*/
typedef struct sz_string_view_t {
sz_string_start_t start;
sz_size_t length;
} sz_string_view_t;
/**
* @brief Internal data-structure, used to address "anomalies" (often prefixes),
* during substring search. Always a 32-bit unsigned integer, containing 4 chars.
*/
typedef union _sz_anomaly_t {
unsigned u32;
unsigned char u8s[4];
} _sz_anomaly_t;
/**
* @brief This is a slightly faster alternative to `strncmp(a, b, length) == 0`.
* Doesn't provide major performance improvements, but helps avoid the LibC dependency.
* @return 1 for `true`, and 0 for `false`.
*/
inline static sz_bool_t sz_equal(sz_string_start_t a, sz_string_start_t b, sz_size_t length) {
sz_string_start_t const a_end = a + length;
while (a != a_end && *a == *b) a++, b++;
return a_end == a;
}
/**
* @brief Count the number of occurrences of a @b single-character needle in an arbitrary length haystack.
* This implementation uses hardware-agnostic SWAR technique, to process 8 characters at a time.
*/
inline static sz_size_t sz_count_char_swar(sz_string_start_t const haystack,
sz_size_t const haystack_length,
sz_string_start_t const needle) {
sz_size_t result = 0;
sz_string_start_t text = haystack;
sz_string_start_t const end = haystack + haystack_length;
// Process the misaligned head, to void UB on unaligned 64-bit loads.
for (; ((sz_size_t)text & 7ull) && text < end; ++text) result += *text == *needle;
// This code simulates hyper-scalar execution, comparing 8 characters at a time.
sz_u64_t nnnnnnnn = *needle;
nnnnnnnn |= nnnnnnnn << 8;
nnnnnnnn |= nnnnnnnn << 16;
nnnnnnnn |= nnnnnnnn << 32;
for (; text + 8 <= end; text += 8) {
sz_u64_t text_slice = *(sz_u64_t const *)text;
sz_u64_t match_indicators = ~(text_slice ^ nnnnnnnn);
match_indicators &= match_indicators >> 1;
match_indicators &= match_indicators >> 2;
match_indicators &= match_indicators >> 4;
match_indicators &= 0x0101010101010101;
result += popcount64(match_indicators);
}
for (; text < end; ++text) result += *text == *needle;
return result;
}
/**
* @brief Find the first occurrence of a @b single-character needle in an arbitrary length haystack.
* This implementation uses hardware-agnostic SWAR technique, to process 8 characters at a time.
* Identical to `memchr(haystack, needle[0], haystack_length)`.
*/
inline static sz_string_start_t sz_find_1char_swar(sz_string_start_t const haystack,
sz_size_t const haystack_length,
sz_string_start_t const needle) {
sz_string_start_t text = haystack;
sz_string_start_t const end = haystack + haystack_length;
// Process the misaligned head, to void UB on unaligned 64-bit loads.
for (; ((sz_size_t)text & 7ull) && text < end; ++text)
if (*text == *needle) return text;
// This code simulates hyper-scalar execution, analyzing 8 offsets at a time.
sz_u64_t nnnnnnnn = *needle;
nnnnnnnn |= nnnnnnnn << 8; // broadcast `needle` into `nnnnnnnn`
nnnnnnnn |= nnnnnnnn << 16; // broadcast `needle` into `nnnnnnnn`
nnnnnnnn |= nnnnnnnn << 32; // broadcast `needle` into `nnnnnnnn`
for (; text + 8 <= end; text += 8) {
sz_u64_t text_slice = *(sz_u64_t const *)text;
sz_u64_t match_indicators = ~(text_slice ^ nnnnnnnn);
match_indicators &= match_indicators >> 1;
match_indicators &= match_indicators >> 2;
match_indicators &= match_indicators >> 4;
match_indicators &= 0x0101010101010101;
if (match_indicators != 0) return text + ctz64(match_indicators) / 8;
}
for (; text < end; ++text)
if (*text == *needle) return text;
return NULL;
}
/**
* @brief Find the last occurrence of a @b single-character needle in an arbitrary length haystack.
* This implementation uses hardware-agnostic SWAR technique, to process 8 characters at a time.
* Identical to `memrchr(haystack, needle[0], haystack_length)`.
*/
inline static sz_string_start_t sz_rfind_1char_swar(sz_string_start_t const haystack,
sz_size_t const haystack_length,
sz_string_start_t const needle) {
sz_string_start_t const end = haystack + haystack_length;
sz_string_start_t text = end - 1;
// Process the misaligned head, to void UB on unaligned 64-bit loads.
for (; ((sz_size_t)text & 7ull) && text >= haystack; --text)
if (*text == *needle) return text;
// This code simulates hyper-scalar execution, analyzing 8 offsets at a time.
sz_u64_t nnnnnnnn = *needle;
nnnnnnnn |= nnnnnnnn << 8; // broadcast `needle` into `nnnnnnnn`
nnnnnnnn |= nnnnnnnn << 16; // broadcast `needle` into `nnnnnnnn`
nnnnnnnn |= nnnnnnnn << 32; // broadcast `needle` into `nnnnnnnn`
for (; text - 8 >= haystack; text -= 8) {
sz_u64_t text_slice = *(sz_u64_t const *)text;
sz_u64_t match_indicators = ~(text_slice ^ nnnnnnnn);
match_indicators &= match_indicators >> 1;
match_indicators &= match_indicators >> 2;
match_indicators &= match_indicators >> 4;
match_indicators &= 0x0101010101010101;
if (match_indicators != 0) return text - 8 + clz64(match_indicators) / 8;
}
for (; text >= haystack; --text)
if (*text == *needle) return text;
return NULL;
}
/**
* @brief Find the first occurrence of a @b two-character needle in an arbitrary length haystack.
* This implementation uses hardware-agnostic SWAR technique, to process 8 characters at a time.
*/
inline static sz_string_start_t sz_find_2char_swar(sz_string_start_t const haystack,
sz_size_t const haystack_length,
sz_string_start_t const needle) {
sz_string_start_t text = haystack;
sz_string_start_t const end = haystack + haystack_length;
// Process the misaligned head, to void UB on unaligned 64-bit loads.
for (; ((sz_size_t)text & 7ull) && text + 2 <= end; ++text)
if (text[0] == needle[0] && text[1] == needle[1]) return text;
// This code simulates hyper-scalar execution, analyzing 7 offsets at a time.
sz_u64_t nnnn = ((sz_u64_t)(needle[0]) << 0) | ((sz_u64_t)(needle[1]) << 8); // broadcast `needle` into `nnnn`
nnnn |= nnnn << 16; // broadcast `needle` into `nnnn`
nnnn |= nnnn << 32; // broadcast `needle` into `nnnn`
for (; text + 8 <= end; text += 7) {
sz_u64_t text_slice = *(sz_u64_t const *)text;
sz_u64_t even_indicators = ~(text_slice ^ nnnn);
sz_u64_t odd_indicators = ~((text_slice << 8) ^ nnnn);
// For every even match - 2 char (16 bits) must be identical.
even_indicators &= even_indicators >> 1;
even_indicators &= even_indicators >> 2;
even_indicators &= even_indicators >> 4;
even_indicators &= even_indicators >> 8;
even_indicators &= 0x0001000100010001;
// For every odd match - 2 char (16 bits) must be identical.
odd_indicators &= odd_indicators >> 1;
odd_indicators &= odd_indicators >> 2;
odd_indicators &= odd_indicators >> 4;
odd_indicators &= odd_indicators >> 8;
odd_indicators &= 0x0001000100010000;
if (even_indicators + odd_indicators) {
sz_u64_t match_indicators = even_indicators | (odd_indicators >> 8);
return text + ctz64(match_indicators) / 8;
}
}
for (; text + 2 <= end; ++text)
if (text[0] == needle[0] && text[1] == needle[1]) return text;
return NULL;
}
/**
* @brief Find the first occurrence of a three-character needle in an arbitrary length haystack.
* This implementation uses hardware-agnostic SWAR technique, to process 8 characters at a time.
*/
inline static sz_string_start_t sz_find_3char_swar(sz_string_start_t const haystack,
sz_size_t const haystack_length,
sz_string_start_t const needle) {
sz_string_start_t text = haystack;
sz_string_start_t end = haystack + haystack_length;
// Process the misaligned head, to void UB on unaligned 64-bit loads.
for (; ((sz_size_t)text & 7ull) && text + 3 <= end; ++text)
if (text[0] == needle[0] && text[1] == needle[1] && text[2] == needle[2]) return text;
// This code simulates hyper-scalar execution, analyzing 6 offsets at a time.
// We have two unused bytes at the end.
sz_u64_t nn = // broadcast `needle` into `nn`
(sz_u64_t)(needle[0] << 0) | // broadcast `needle` into `nn`
((sz_u64_t)(needle[1]) << 8) | // broadcast `needle` into `nn`
((sz_u64_t)(needle[2]) << 16); // broadcast `needle` into `nn`
nn |= nn << 24; // broadcast `needle` into `nn`
nn <<= 16; // broadcast `needle` into `nn`
for (; text + 8 <= end; text += 6) {
sz_u64_t text_slice = *(sz_u64_t const *)text;
sz_u64_t first_indicators = ~(text_slice ^ nn);
sz_u64_t second_indicators = ~((text_slice << 8) ^ nn);
sz_u64_t third_indicators = ~((text_slice << 16) ^ nn);
// For every first match - 3 chars (24 bits) must be identical.
// For that merge every byte state and then combine those three-way.
first_indicators &= first_indicators >> 1;
first_indicators &= first_indicators >> 2;
first_indicators &= first_indicators >> 4;
first_indicators =
(first_indicators >> 16) & (first_indicators >> 8) & (first_indicators >> 0) & 0x0000010000010000;
// For every second match - 3 chars (24 bits) must be identical.
// For that merge every byte state and then combine those three-way.
second_indicators &= second_indicators >> 1;
second_indicators &= second_indicators >> 2;
second_indicators &= second_indicators >> 4;
second_indicators =
(second_indicators >> 16) & (second_indicators >> 8) & (second_indicators >> 0) & 0x0000010000010000;
// For every third match - 3 chars (24 bits) must be identical.
// For that merge every byte state and then combine those three-way.
third_indicators &= third_indicators >> 1;
third_indicators &= third_indicators >> 2;
third_indicators &= third_indicators >> 4;
third_indicators =
(third_indicators >> 16) & (third_indicators >> 8) & (third_indicators >> 0) & 0x0000010000010000;
sz_u64_t match_indicators = first_indicators | (second_indicators >> 8) | (third_indicators >> 16);
if (match_indicators != 0) return text + ctz64(match_indicators) / 8;
}
for (; text + 3 <= end; ++text)
if (text[0] == needle[0] && text[1] == needle[1] && text[2] == needle[2]) return text;
return NULL;
}
/**
* @brief Find the first occurrence of a @b four-character needle in an arbitrary length haystack.
* This implementation uses hardware-agnostic SWAR technique, to process 8 characters at a time.
*/
inline static sz_string_start_t sz_find_4char_swar(sz_string_start_t const haystack,
sz_size_t const haystack_length,
sz_string_start_t const needle) {
sz_string_start_t text = haystack;
sz_string_start_t end = haystack + haystack_length;
// Process the misaligned head, to void UB on unaligned 64-bit loads.
for (; ((sz_size_t)text & 7ull) && text + 4 <= end; ++text)
if (text[0] == needle[0] && text[1] == needle[1] && text[2] == needle[2] && text[3] == needle[3]) return text;
// This code simulates hyper-scalar execution, analyzing 4 offsets at a time.
sz_u64_t nn = (sz_u64_t)(needle[0] << 0) | ((sz_u64_t)(needle[1]) << 8) | ((sz_u64_t)(needle[2]) << 16) |
((sz_u64_t)(needle[3]) << 24);
nn |= nn << 32;
//
unsigned char offset_in_slice[16] = {0};
offset_in_slice[0x2] = offset_in_slice[0x6] = offset_in_slice[0xA] = offset_in_slice[0xE] = 1;
offset_in_slice[0x4] = offset_in_slice[0xC] = 2;
offset_in_slice[0x8] = 3;
// We can perform 5 comparisons per load, but it's easier to perform 4, minimizing the size of the lookup table.
for (; text + 8 <= end; text += 4) {
sz_u64_t text_slice = *(sz_u64_t const *)text;
sz_u64_t text01 = (text_slice & 0x00000000FFFFFFFF) | ((text_slice & 0x000000FFFFFFFF00) << 24);
sz_u64_t text23 = ((text_slice & 0x0000FFFFFFFF0000) >> 16) | ((text_slice & 0x00FFFFFFFF000000) << 8);
sz_u64_t text01_indicators = ~(text01 ^ nn);
sz_u64_t text23_indicators = ~(text23 ^ nn);
// For every first match - 4 chars (32 bits) must be identical.
text01_indicators &= text01_indicators >> 1;
text01_indicators &= text01_indicators >> 2;
text01_indicators &= text01_indicators >> 4;
text01_indicators &= text01_indicators >> 8;
text01_indicators &= text01_indicators >> 16;
text01_indicators &= 0x0000000100000001;
// For every first match - 4 chars (32 bits) must be identical.
text23_indicators &= text23_indicators >> 1;
text23_indicators &= text23_indicators >> 2;
text23_indicators &= text23_indicators >> 4;
text23_indicators &= text23_indicators >> 8;
text23_indicators &= text23_indicators >> 16;
text23_indicators &= 0x0000000100000001;
if (text01_indicators + text23_indicators) {
// Assuming we have performed 4 comparisons, we can only have 2^4=16 outcomes.
// Which is small enough for a lookup table.
unsigned char match_indicators = (unsigned char)( //
(text01_indicators >> 31) | (text01_indicators << 0) | //
(text23_indicators >> 29) | (text23_indicators << 2));
return text + offset_in_slice[match_indicators];
}
}
for (; text + 4 <= end; ++text)
if (text[0] == needle[0] && text[1] == needle[1] && text[2] == needle[2] && text[3] == needle[3]) return text;
return NULL;
}
/**
* @brief Trivial substring search with scalar SWAR code. Instead of comparing characters one-by-one
* it compares 4-byte anomalies first, most commonly prefixes. It's computationally cheaper.
* Matching performance fluctuates between 1 GB/s and 3,5 GB/s per core.
*/
inline static sz_string_start_t sz_find_substring_swar( //
sz_string_start_t const haystack,
sz_size_t const haystack_length,
sz_string_start_t const needle,
sz_size_t const needle_length) {
if (haystack_length < needle_length) return NULL;
sz_size_t anomaly_offset = 0;
switch (needle_length) {
case 0: return NULL;
case 1: return sz_find_1char_swar(haystack, haystack_length, needle);
case 2: return sz_find_2char_swar(haystack, haystack_length, needle);
case 3: return sz_find_3char_swar(haystack, haystack_length, needle);
case 4: return sz_find_4char_swar(haystack, haystack_length, needle);
default: {
sz_string_start_t text = haystack;
sz_string_start_t const end = haystack + haystack_length;
_sz_anomaly_t n_anomaly, h_anomaly;
sz_size_t const n_suffix_len = needle_length - 4 - anomaly_offset;
sz_string_start_t n_suffix_ptr = needle + 4 + anomaly_offset;
n_anomaly.u8s[0] = needle[anomaly_offset];
n_anomaly.u8s[1] = needle[anomaly_offset + 1];
n_anomaly.u8s[2] = needle[anomaly_offset + 2];
n_anomaly.u8s[3] = needle[anomaly_offset + 3];
h_anomaly.u8s[0] = haystack[0];
h_anomaly.u8s[1] = haystack[1];
h_anomaly.u8s[2] = haystack[2];
h_anomaly.u8s[3] = haystack[3];
text += anomaly_offset;
while (text + needle_length <= end) {
h_anomaly.u8s[3] = text[3];
if (h_anomaly.u32 == n_anomaly.u32) // Match anomaly.
if (sz_equal(text + 4, n_suffix_ptr, n_suffix_len)) // Match suffix.
return text;
h_anomaly.u32 >>= 8;
++text;
}
return NULL;
}
}
}
/**
* Helper function, used in substring search operations.
*/
inline static void _sz_find_substring_populate_anomaly( //
sz_string_start_t const needle,
sz_size_t const needle_length,
_sz_anomaly_t *anomaly_out,
_sz_anomaly_t *mask_out) {
_sz_anomaly_t anomaly;
_sz_anomaly_t mask;
switch (needle_length) {
case 1:
mask.u8s[0] = 0xFF, mask.u8s[1] = mask.u8s[2] = mask.u8s[3] = 0;
anomaly.u8s[0] = needle[0], anomaly.u8s[1] = anomaly.u8s[2] = anomaly.u8s[3] = 0;
break;
case 2:
mask.u8s[0] = mask.u8s[1] = 0xFF, mask.u8s[2] = mask.u8s[3] = 0;
anomaly.u8s[0] = needle[0], anomaly.u8s[1] = needle[1], anomaly.u8s[2] = anomaly.u8s[3] = 0;
break;
case 3:
mask.u8s[0] = mask.u8s[1] = mask.u8s[2] = 0xFF, mask.u8s[3] = 0;
anomaly.u8s[0] = needle[0], anomaly.u8s[1] = needle[1], anomaly.u8s[2] = needle[2], anomaly.u8s[3] = 0;
break;
default:
mask.u32 = 0xFFFFFFFF;
anomaly.u8s[0] = needle[0], anomaly.u8s[1] = needle[1], anomaly.u8s[2] = needle[2], anomaly.u8s[3] = needle[3];
break;
}
*anomaly_out = anomaly;
*mask_out = mask;
}
#if defined(__AVX2__)
/**
* @brief Substring-search implementation, leveraging x86 AVX2 intrinsics and speculative
* execution capabilities on modern CPUs. Performing 4 unaligned vector loads per cycle
* was practically more efficient than loading once and shifting around, as introduces
* less data dependencies.
*/
inline static sz_string_start_t sz_find_substring_avx2(sz_string_start_t const haystack,
sz_size_t const haystack_length,
sz_string_start_t const needle,
sz_size_t const needle_length) {
// Precomputed constants
sz_string_start_t const end = haystack + haystack_length;
_sz_anomaly_t anomaly;
_sz_anomaly_t mask;
_sz_find_substring_populate_anomaly(needle, needle_length, &anomaly, &mask);
__m256i const anomalies = _mm256_set1_epi32(anomaly.u32);
__m256i const masks = _mm256_set1_epi32(mask.u32);
// Top level for-loop changes dramatically.
// In sequential computing model for 32 offsets we would do:
// + 32 comparions.
// + 32 branches.
// In vectorized computations models:
// + 4 vectorized comparisons.
// + 4 movemasks.
// + 3 bitwise ANDs.
// + 1 heavy (but very unlikely) branch.
sz_string_start_t text = haystack;
while (text + needle_length + 32 <= end) {
// Performing many unaligned loads ends up being faster than loading once and shuffling around.
__m256i texts0 = _mm256_and_si256(_mm256_loadu_si256((__m256i const *)(text + 0)), masks);
int matches0 = _mm256_movemask_epi8(_mm256_cmpeq_epi32(texts0, anomalies));
__m256i texts1 = _mm256_and_si256(_mm256_loadu_si256((__m256i const *)(text + 1)), masks);
int matches1 = _mm256_movemask_epi8(_mm256_cmpeq_epi32(texts1, anomalies));
__m256i text2 = _mm256_and_si256(_mm256_loadu_si256((__m256i const *)(text + 2)), masks);
int matches2 = _mm256_movemask_epi8(_mm256_cmpeq_epi32(text2, anomalies));
__m256i texts3 = _mm256_and_si256(_mm256_loadu_si256((__m256i const *)(text + 3)), masks);
int matches3 = _mm256_movemask_epi8(_mm256_cmpeq_epi32(texts3, anomalies));
if (matches0 | matches1 | matches2 | matches3) {
int matches = //
(matches0 & 0x11111111) | //
(matches1 & 0x22222222) | //
(matches2 & 0x44444444) | //
(matches3 & 0x88888888);
sz_size_t first_match_offset = ctz64(matches);
if (needle_length > 4) {
if (sz_equal(text + first_match_offset + 4, needle + 4, needle_length - 4)) {
return text + first_match_offset;
}
else { text += first_match_offset + 1; }
}
else { return text + first_match_offset; }
}
else { text += 32; }
}
// Don't forget the last (up to 35) characters.
return sz_find_substring_swar(text, end - text, needle, needle_length);
}
#endif // x86 AVX2
#if defined(__ARM_NEON)
/**
* @brief Substring-search implementation, leveraging Arm Neon intrinsics and speculative
* execution capabilities on modern CPUs. Performing 4 unaligned vector loads per cycle
* was practically more efficient than loading once and shifting around, as introduces
* less data dependencies.
*/
inline static sz_string_start_t sz_find_substring_neon(sz_string_start_t const haystack,
sz_size_t const haystack_length,
sz_string_start_t const needle,
sz_size_t const needle_length) {
// Precomputed constants
sz_string_start_t const end = haystack + haystack_length;
_sz_anomaly_t anomaly;
_sz_anomaly_t mask;
_sz_find_substring_populate_anomaly(needle, needle_length, &anomaly, &mask);
uint32x4_t const anomalies = vld1q_dup_u32(&anomaly.u32);
uint32x4_t const masks = vld1q_dup_u32(&mask.u32);
uint32x4_t matches, matches0, matches1, matches2, matches3;
sz_string_start_t text = haystack;
while (text + needle_length + 16 <= end) {
// Each of the following `matchesX` contains only 4 relevant bits - one per word.
// Each signifies a match at the given offset.
matches0 = vceqq_u32(vandq_u32(vreinterpretq_u32_u8(vld1q_u8((unsigned char *)text + 0)), masks), anomalies);
matches1 = vceqq_u32(vandq_u32(vreinterpretq_u32_u8(vld1q_u8((unsigned char *)text + 1)), masks), anomalies);
matches2 = vceqq_u32(vandq_u32(vreinterpretq_u32_u8(vld1q_u8((unsigned char *)text + 2)), masks), anomalies);
matches3 = vceqq_u32(vandq_u32(vreinterpretq_u32_u8(vld1q_u8((unsigned char *)text + 3)), masks), anomalies);
matches = vorrq_u32(vorrq_u32(matches0, matches1), vorrq_u32(matches2, matches3));
if (vmaxvq_u32(matches)) {
// Let's isolate the match from every word
matches0 = vandq_u32(matches0, vdupq_n_u32(0x00000001));
matches1 = vandq_u32(matches1, vdupq_n_u32(0x00000002));
matches2 = vandq_u32(matches2, vdupq_n_u32(0x00000004));
matches3 = vandq_u32(matches3, vdupq_n_u32(0x00000008));
matches = vorrq_u32(vorrq_u32(matches0, matches1), vorrq_u32(matches2, matches3));
// By now, every 32-bit word of `matches` no more than 4 set bits.
// Meaning that we can narrow it down to a single 16-bit word.
uint16x4_t matches_u16x4 = vmovn_u32(matches);
uint16_t matches_u16 = //
(vget_lane_u16(matches_u16x4, 0) << 0) | //
(vget_lane_u16(matches_u16x4, 1) << 4) | //
(vget_lane_u16(matches_u16x4, 2) << 8) | //
(vget_lane_u16(matches_u16x4, 3) << 12);
// Find the first match
sz_size_t first_match_offset = ctz64(matches_u16);
if (needle_length > 4) {
if (sz_equal(text + first_match_offset + 4, needle + 4, needle_length - 4)) {
return text + first_match_offset;
}
else { text += first_match_offset + 1; }
}
else { return text + first_match_offset; }
}
else { text += 16; }
}
// Don't forget the last (up to 16+3=19) characters.
return sz_find_substring_swar(text, end - text, needle, needle_length);
}
#endif // Arm Neon
inline static sz_size_t sz_count_char(sz_string_start_t const haystack,
sz_size_t const haystack_length,
sz_string_start_t const needle) {
return sz_count_char_swar(haystack, haystack_length, needle);
}
inline static sz_string_start_t sz_find_1char(sz_string_start_t const haystack,
sz_size_t const haystack_length,
sz_string_start_t const needle) {
return sz_find_1char_swar(haystack, haystack_length, needle);
}
inline static sz_string_start_t sz_rfind_1char(sz_string_start_t const haystack,
sz_size_t const haystack_length,
sz_string_start_t const needle) {
return sz_rfind_1char_swar(haystack, haystack_length, needle);
}
inline static sz_string_start_t sz_find_substring(sz_string_start_t const haystack,
sz_size_t const haystack_length,
sz_string_start_t const needle,
sz_size_t const needle_length) {
if (haystack_length < needle_length || needle_length == 0) return NULL;
#if defined(__ARM_NEON)
return sz_find_substring_neon(haystack, haystack_length, needle, needle_length);
#elif defined(__AVX2__)
return sz_find_substring_avx2(haystack, haystack_length, needle, needle_length);
#else
return sz_find_substring_swar(haystack, haystack_length, needle, needle_length);
#endif
}
/**
* @brief Maps any ASCII character to itself, or the lowercase variant, if available.
*/
inline static char sz_tolower_ascii(char c) {
static unsigned char lowered[256] = {
0, 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, 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, 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, //
224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, //
240, 241, 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 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, //
};
return *(char *)&lowered[(int)c];
}
/**
* @brief Maps any ASCII character to itself, or the uppercase variant, if available.
*/
inline static char sz_toupper_ascii(char c) {
static unsigned char upped[256] = {
0, 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, 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, 91, 92, 93, 94, 95, //
96, 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, 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, //
224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, //
240, 241, 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 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, //
};
return *(char *)&upped[(int)c];
}
/**
* @brief Load a 64-bit unsigned integer from a potentially unaligned pointer.
*
* @note This function uses compiler-specific attributes or keywords to
* ensure correct and efficient unaligned loads. It's designed to work
* with both MSVC and GCC/Clang.
*/
inline static sz_u64_t sz_u64_unaligned_load(void const *ptr) {
#ifdef _MSC_VER
return *((__unaligned sz_u64_t *)ptr);
#else
__attribute__((aligned(1))) sz_u64_t const *uptr = (sz_u64_t const *)ptr;
return *uptr;
#endif
}
/**
* @brief Reverse the byte order of a 64-bit unsigned integer.
*
* @note This function uses compiler-specific intrinsics to achieve the
* byte-reversal. It's designed to work with both MSVC and GCC/Clang.
*/
inline static sz_u64_t sz_u64_byte_reverse(sz_u64_t val) {
#ifdef _MSC_VER
return _byteswap_uint64(val);
#else
return __builtin_bswap64(val);
#endif
}
/**
* @brief Compute the logarithm base 2 of an integer.
*
* @note If n is 0, the function returns 0 to avoid undefined behavior.
* @note This function uses compiler-specific intrinsics or built-ins
* to achieve the computation. It's designed to work with GCC/Clang and MSVC.
*/
inline static sz_size_t sz_log2i(sz_size_t n) {
if (n == 0) return 0;
#ifdef _WIN64
#ifdef _MSC_VER
unsigned long index;
if (_BitScanReverse64(&index, n)) return index;
return 0; // This line might be redundant due to the initial check, but it's safer to include it.
#else
return 63 - __builtin_clzll(n);
#endif
#elif defined(_WIN32)
#ifdef _MSC_VER
unsigned long index;
if (_BitScanReverse(&index, n)) return index;
return 0; // Same note as above.
#else
return 31 - __builtin_clz(n);
#endif
#else
// Handle non-Windows platforms. You can further differentiate between 32-bit and 64-bit if needed.
#if defined(__LP64__)
return 63 - __builtin_clzll(n);
#else
return 31 - __builtin_clz(n);
#endif
#endif
}
/**
* @brief Char-level lexicographic comparison of two strings.
* Doesn't provide major performance improvements, but helps avoid the LibC dependency.
*/
inline static sz_bool_t sz_is_less_ascii(sz_string_start_t a,
sz_size_t const a_length,
sz_string_start_t b,
sz_size_t const b_length) {
sz_size_t min_length = (a_length < b_length) ? a_length : b_length;
sz_string_start_t const min_end = a + min_length;
while (a + 8 <= min_end && sz_u64_unaligned_load(a) == sz_u64_unaligned_load(b)) a += 8, b += 8;
while (a != min_end && *a == *b) a++, b++;
return a != min_end ? (*a < *b) : (a_length < b_length);
}
/**
* @brief Char-level lexicographic comparison of two strings, insensitive to the case of ASCII symbols.
* Doesn't provide major performance improvements, but helps avoid the LibC dependency.
*/
inline static sz_bool_t sz_is_less_uncased_ascii(sz_string_start_t const a,
sz_size_t const a_length,
sz_string_start_t const b,
sz_size_t const b_length) {
sz_size_t min_length = (a_length < b_length) ? a_length : b_length;
for (sz_size_t i = 0; i < min_length; ++i) {
char a_lower = sz_tolower_ascii(a[i]);
char b_lower = sz_tolower_ascii(b[i]);
if (a_lower < b_lower) return 1;
if (a_lower > b_lower) return 0;
}
return a_length < b_length;
}
/**
* @brief Helper, that swaps two 64-bit integers representing the order of elements in the sequence.
*/
inline static void _sz_swap_order(sz_u64_t *a, sz_u64_t *b) {
sz_u64_t t = *a;
*a = *b;
*b = t;
}
struct sz_sequence_t;
typedef sz_string_start_t (*sz_sequence_member_start_t)(struct sz_sequence_t const *, sz_size_t);
typedef sz_size_t (*sz_sequence_member_length_t)(struct sz_sequence_t const *, sz_size_t);
typedef sz_bool_t (*sz_sequence_predicate_t)(struct sz_sequence_t const *, sz_size_t);
typedef sz_bool_t (*sz_sequence_comparator_t)(struct sz_sequence_t const *, sz_size_t, sz_size_t);
typedef sz_bool_t (*sz_string_is_less_t)(sz_string_start_t, sz_size_t, sz_string_start_t, sz_size_t);
typedef struct sz_sequence_t {
sz_u64_t *order;
sz_size_t count;
sz_sequence_member_start_t get_start;
sz_sequence_member_length_t get_length;
void const *handle;
} sz_sequence_t;
/**
* @brief Similar to `std::partition`, given a predicate splits the sequence into two parts.
* The algorithm is unstable, meaning that elements may change relative order, as long
* as they are in the right partition. This is the simpler algorithm for partitioning.
*/
inline static sz_size_t sz_partition(sz_sequence_t *sequence, sz_sequence_predicate_t predicate) {
sz_size_t matches = 0;
while (matches != sequence->count && predicate(sequence, sequence->order[matches])) ++matches;
for (sz_size_t i = matches + 1; i < sequence->count; ++i)
if (predicate(sequence, sequence->order[i]))
_sz_swap_order(sequence->order + i, sequence->order + matches), ++matches;
return matches;
}
/**
* @brief Inplace `std::set_union` for two consecutive chunks forming the same continuous `sequence`.
*
* @param partition The number of elements in the first sub-sequence in `sequence`.
* @param less Comparison function, to determine the lexicographic ordering.
*/
inline static void sz_merge(sz_sequence_t *sequence, sz_size_t partition, sz_sequence_comparator_t less) {
sz_size_t start_b = partition + 1;
// If the direct merge is already sorted
if (!less(sequence, sequence->order[start_b], sequence->order[partition])) return;
sz_size_t start_a = 0;
while (start_a <= partition && start_b <= sequence->count) {
// If element 1 is in right place
if (!less(sequence, sequence->order[start_b], sequence->order[start_a])) { start_a++; }
else {
sz_size_t value = sequence->order[start_b];
sz_size_t index = start_b;
// Shift all the elements between element 1
// element 2, right by 1.
while (index != start_a) { sequence->order[index] = sequence->order[index - 1], index--; }
sequence->order[start_a] = value;
// Update all the pointers
start_a++;
partition++;
start_b++;
}
}
}
inline static void sz_sort_insertion(sz_sequence_t *sequence, sz_sequence_comparator_t less) {
sz_u64_t *keys = sequence->order;
sz_size_t keys_count = sequence->count;
for (sz_size_t i = 1; i < keys_count; i++) {
sz_u64_t i_key = keys[i];
sz_size_t j = i;
for (; j > 0 && less(sequence, i_key, keys[j - 1]); --j) keys[j] = keys[j - 1];
keys[j] = i_key;
}
}
inline static void _sz_sift_down(
sz_sequence_t *sequence, sz_sequence_comparator_t less, sz_u64_t *order, sz_size_t start, sz_size_t end) {
sz_size_t root = start;
while (2 * root + 1 <= end) {
sz_size_t child = 2 * root + 1;
if (child + 1 <= end && less(sequence, order[child], order[child + 1])) { child++; }
if (!less(sequence, order[root], order[child])) { return; }
_sz_swap_order(order + root, order + child);
root = child;
}
}
inline static void _sz_heapify(sz_sequence_t *sequence,
sz_sequence_comparator_t less,
sz_u64_t *order,
sz_size_t count) {
sz_size_t start = (count - 2) / 2;
while (1) {
_sz_sift_down(sequence, less, order, start, count - 1);
if (start == 0) return;
start--;
}
}
inline static void _sz_heapsort(sz_sequence_t *sequence,
sz_sequence_comparator_t less,
sz_size_t first,
sz_size_t last) {
sz_u64_t *order = sequence->order;
sz_size_t count = last - first;
_sz_heapify(sequence, less, order + first, count);
sz_size_t end = count - 1;
while (end > 0) {
_sz_swap_order(order + first, order + first + end);
end--;
_sz_sift_down(sequence, less, order + first, 0, end);
}
}
inline static void _sz_introsort(
sz_sequence_t *sequence, sz_sequence_comparator_t less, sz_size_t first, sz_size_t last, sz_size_t depth) {
sz_size_t length = last - first;
switch (length) {
case 0:
case 1: return;
case 2:
if (less(sequence, sequence->order[first + 1], sequence->order[first]))
_sz_swap_order(&sequence->order[first], &sequence->order[first + 1]);
return;
case 3: {
sz_u64_t a = sequence->order[first];
sz_u64_t b = sequence->order[first + 1];
sz_u64_t c = sequence->order[first + 2];
if (less(sequence, b, a)) _sz_swap_order(&a, &b);
if (less(sequence, c, b)) _sz_swap_order(&c, &b);
if (less(sequence, b, a)) _sz_swap_order(&a, &b);
sequence->order[first] = a;
sequence->order[first + 1] = b;
sequence->order[first + 2] = c;
return;
}
}
// Until a certain length, the quadratic-complexity insertion-sort is fine
if (length <= 16) {
sz_sequence_t sub_seq = *sequence;
sub_seq.order += first;
sub_seq.count = length;
sz_sort_insertion(&sub_seq, less);
return;
}
// Fallback to N-logN-complexity heap-sort
if (depth == 0) {
_sz_heapsort(sequence, less, first, last);
return;
}
--depth;
// Median-of-three logic to choose pivot
sz_size_t median = first + length / 2;
if (less(sequence, sequence->order[median], sequence->order[first]))
_sz_swap_order(&sequence->order[first], &sequence->order[median]);
if (less(sequence, sequence->order[last - 1], sequence->order[first]))
_sz_swap_order(&sequence->order[first], &sequence->order[last - 1]);
if (less(sequence, sequence->order[median], sequence->order[last - 1]))
_sz_swap_order(&sequence->order[median], &sequence->order[last - 1]);
// Partition using the median-of-three as the pivot
sz_u64_t pivot = sequence->order[median];
sz_size_t left = first;
sz_size_t right = last - 1;
while (1) {
while (less(sequence, sequence->order[left], pivot)) left++;
while (less(sequence, pivot, sequence->order[right])) right--;
if (left >= right) break;
_sz_swap_order(&sequence->order[left], &sequence->order[right]);
left++;
right--;
}
// Recursively sort the partitions
_sz_introsort(sequence, less, first, left, depth);
_sz_introsort(sequence, less, right + 1, last, depth);
}
inline static void sz_sort_introsort(sz_sequence_t *sequence, sz_sequence_comparator_t less) {
sz_size_t depth_limit = 2 * sz_log2i(sequence->count);
_sz_introsort(sequence, less, 0, sequence->count, depth_limit);
}
inline static void _sz_sort_recursion( //
sz_sequence_t *sequence,
sz_size_t bit_idx,
sz_size_t bit_max,
sz_sequence_comparator_t comparator,
sz_size_t partial_order_length) {
if (!sequence->count) return;
// Partition a range of integers according to a specific bit value
sz_size_t split = 0;
{
sz_u64_t mask = (1ull << 63) >> bit_idx;
while (split != sequence->count && !(sequence->order[split] & mask)) ++split;