-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
string_immutable.zig
6544 lines (5630 loc) · 242 KB
/
string_immutable.zig
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
const std = @import("std");
const expect = std.testing.expect;
const Environment = @import("./env.zig");
const string = bun.string;
const stringZ = bun.stringZ;
const CodePoint = bun.CodePoint;
const bun = @import("root").bun;
const log = bun.Output.scoped(.STR, true);
const js_lexer = @import("./js_lexer.zig");
const grapheme = @import("./grapheme.zig");
const JSC = bun.JSC;
const OOM = bun.OOM;
pub const Encoding = enum {
ascii,
utf8,
latin1,
utf16,
};
/// Returned by classification functions that do not discriminate between utf8 and ascii.
pub const EncodingNonAscii = enum {
utf8,
utf16,
latin1,
};
pub inline fn containsChar(self: string, char: u8) bool {
return indexOfChar(self, char) != null;
}
pub inline fn contains(self: string, str: string) bool {
return containsT(u8, self, str);
}
pub inline fn containsT(comptime T: type, self: []const T, str: []const T) bool {
return indexOfT(T, self, str) != null;
}
pub inline fn containsCaseInsensitiveASCII(self: string, str: string) bool {
var start: usize = 0;
while (start + str.len <= self.len) {
if (eqlCaseInsensitiveASCIIIgnoreLength(self[start..][0..str.len], str)) {
return true;
}
start += 1;
}
return false;
}
pub inline fn removeLeadingDotSlash(slice: []const u8) []const u8 {
if (slice.len >= 2) {
if ((@as(u16, @bitCast(slice[0..2].*)) == comptime std.mem.readInt(u16, "./", .little)) or
(Environment.isWindows and @as(u16, @bitCast(slice[0..2].*)) == comptime std.mem.readInt(u16, ".\\", .little)))
{
return slice[2..];
}
}
return slice;
}
// TODO: remove this
pub const w = toUTF16Literal;
pub fn toUTF16Literal(comptime str: []const u8) [:0]const u16 {
return literal(u16, str);
}
pub fn literal(comptime T: type, comptime str: []const u8) *const [literalLength(T, str):0]T {
const Holder = struct {
pub const value = switch (T) {
u8 => (str[0..str.len].* ++ .{0})[0..str.len :0],
u16 => std.unicode.utf8ToUtf16LeStringLiteral(str),
else => @compileError("unsupported type " ++ @typeName(T) ++ " in strings.literal() call."),
};
};
return Holder.value;
}
fn literalLength(comptime T: type, comptime str: string) usize {
return comptime switch (T) {
u8 => str.len,
u16 => std.unicode.calcUtf16LeLen(str) catch unreachable,
else => 0, // let other errors report first
};
}
pub const OptionalUsize = std.meta.Int(.unsigned, @bitSizeOf(usize) - 1);
pub fn indexOfAny(slice: string, comptime str: []const u8) ?OptionalUsize {
switch (comptime str.len) {
0 => @compileError("str cannot be empty"),
1 => return indexOfChar(slice, str[0]),
else => {},
}
var remaining = slice;
if (remaining.len == 0) return null;
if (comptime Environment.enableSIMD) {
while (remaining.len >= ascii_vector_size) {
const vec: AsciiVector = remaining[0..ascii_vector_size].*;
var cmp: AsciiVectorU1 = @bitCast(vec == @as(AsciiVector, @splat(@as(u8, str[0]))));
inline for (str[1..]) |c| {
cmp |= @bitCast(vec == @as(AsciiVector, @splat(@as(u8, c))));
}
if (@reduce(.Max, cmp) > 0) {
const bitmask = @as(AsciiVectorInt, @bitCast(cmp));
const first = @ctz(bitmask);
return @as(OptionalUsize, @intCast(first + slice.len - remaining.len));
}
remaining = remaining[ascii_vector_size..];
}
if (comptime Environment.allow_assert) assert(remaining.len < ascii_vector_size);
}
for (remaining, 0..) |c, i| {
if (strings.indexOfChar(str, c) != null) {
return @as(OptionalUsize, @intCast(i + slice.len - remaining.len));
}
}
return null;
}
pub fn indexOfAny16(self: []const u16, comptime str: anytype) ?OptionalUsize {
return indexOfAnyT(u16, self, str);
}
pub fn indexOfAnyT(comptime T: type, str: []const T, comptime chars: anytype) ?OptionalUsize {
if (T == u8) return indexOfAny(str, chars);
for (str, 0..) |c, i| {
inline for (chars) |a| {
if (c == a) {
return @as(OptionalUsize, @intCast(i));
}
}
}
return null;
}
pub inline fn containsComptime(self: string, comptime str: string) bool {
if (comptime str.len == 0) @compileError("Don't call this with an empty string plz.");
const start = std.mem.indexOfScalar(u8, self, str[0]) orelse return false;
var remain = self[start..];
const Int = std.meta.Int(.unsigned, str.len * 8);
while (remain.len >= comptime str.len) {
if (@as(Int, @bitCast(remain.ptr[0..str.len].*)) == @as(Int, @bitCast(str.ptr[0..str.len].*))) {
return true;
}
const next_start = std.mem.indexOfScalar(u8, remain[1..], str[0]) orelse return false;
remain = remain[1 + next_start ..];
}
return false;
}
pub const includes = contains;
pub fn inMapCaseInsensitive(self: []const u8, comptime ComptimeStringMap: anytype) ?ComptimeStringMap.Value {
return bun.String.ascii(self).inMapCaseInsensitive(ComptimeStringMap);
}
pub inline fn containsAny(in: anytype, target: string) bool {
for (in) |str| if (contains(if (@TypeOf(str) == u8) &[1]u8{str} else bun.span(str), target)) return true;
return false;
}
/// https://docs.npmjs.com/cli/v8/configuring-npm/package-json
/// - The name must be less than or equal to 214 characters. This includes the scope for scoped packages.
/// - The names of scoped packages can begin with a dot or an underscore. This is not permitted without a scope.
/// - New packages must not have uppercase letters in the name.
/// - The name ends up being part of a URL, an argument on the command line, and
/// a folder name. Therefore, the name can't contain any non-URL-safe
/// characters.
pub fn isNPMPackageName(target: string) bool {
if (target.len == 0) return false;
if (target.len > 214) return false;
const scoped = switch (target[0]) {
// Old packages may have capital letters
'A'...'Z', 'a'...'z', '0'...'9', '$', '-' => false,
'@' => true,
else => return false,
};
var slash_index: usize = 0;
for (target[1..], 0..) |c, i| {
switch (c) {
// Old packages may have capital letters
'A'...'Z', 'a'...'z', '0'...'9', '-', '_', '.' => {},
'/' => {
if (!scoped) return false;
if (slash_index > 0) return false;
slash_index = i + 1;
},
// issue#7045, package "@~3/svelte_mount"
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent#description
// It escapes all characters except: A–Z a–z 0–9 - _ . ! ~ * ' ( )
'!', '~', '*', '\'', '(', ')' => {
if (!scoped or slash_index > 0) return false;
},
else => return false,
}
}
return !scoped or slash_index > 0 and slash_index + 1 < target.len;
}
pub fn isUUID(str: string) bool {
if (str.len != uuid_len) return false;
for (0..8) |i| {
switch (str[i]) {
'0'...'9', 'a'...'f', 'A'...'F' => {},
else => return false,
}
}
if (str[8] != '-') return false;
for (9..13) |i| {
switch (str[i]) {
'0'...'9', 'a'...'f', 'A'...'F' => {},
else => return false,
}
}
if (str[13] != '-') return false;
for (14..18) |i| {
switch (str[i]) {
'0'...'9', 'a'...'f', 'A'...'F' => {},
else => return false,
}
}
if (str[18] != '-') return false;
for (19..23) |i| {
switch (str[i]) {
'0'...'9', 'a'...'f', 'A'...'F' => {},
else => return false,
}
}
if (str[23] != '-') return false;
for (24..36) |i| {
switch (str[i]) {
'0'...'9', 'a'...'f', 'A'...'F' => {},
else => return false,
}
}
return true;
}
pub const uuid_len = 36;
pub fn startsWithUUID(str: string) bool {
return isUUID(str[0..@min(str.len, uuid_len)]);
}
/// https://github.com/npm/cli/blob/63d6a732c3c0e9c19fd4d147eaa5cc27c29b168d/node_modules/%40npmcli/redact/lib/matchers.js#L7
/// /\b(npms?_)[a-zA-Z0-9]{36,48}\b/gi
/// Returns the length of the secret if one exist.
pub fn startsWithNpmSecret(str: string) u8 {
if (str.len < "npm_".len + 36) return 0;
if (!strings.hasPrefixCaseInsensitive(str, "npm")) return 0;
var i: u8 = "npm".len;
if (str[i] == '_') {
i += 1;
} else if (str[i] == 's' or str[i] == 'S') {
i += 1;
if (str[i] != '_') return 0;
i += 1;
} else {
return 0;
}
const min_len = i + 36;
const max_len = i + 48;
while (i < max_len) : (i += 1) {
if (i == str.len) {
return if (i >= min_len) i else 0;
}
switch (str[i]) {
'0'...'9', 'a'...'z', 'A'...'Z' => {},
else => return if (i >= min_len) i else 0,
}
}
return i;
}
fn startsWithRedactedItem(text: string, comptime item: string) ?struct { usize, usize } {
if (!strings.hasPrefixComptime(text, item)) return null;
var whitespace = false;
var offset: usize = item.len;
while (offset < text.len and std.ascii.isWhitespace(text[offset])) {
offset += 1;
whitespace = true;
}
if (offset == text.len) return null;
const cont = js_lexer.isIdentifierContinue(text[offset]);
// must be another identifier
if (!whitespace and cont) return null;
// `null` is not returned after this point. Redact to the next
// newline if anything is unexpected
if (cont) return .{ offset, indexOfChar(text[offset..], '\n') orelse text[offset..].len };
offset += 1;
var end = offset;
while (end < text.len and std.ascii.isWhitespace(text[end])) {
end += 1;
}
if (end == text.len) {
return .{ offset, text[offset..].len };
}
switch (text[end]) {
inline '\'', '"', '`' => |q| {
// attempt to find closing
const opening = end;
end += 1;
while (end < text.len) {
switch (text[end]) {
'\\' => {
// skip
end += 1;
end += 1;
},
q => {
// closing
return .{ opening + 1, (end - 1) - opening };
},
else => {
end += 1;
},
}
}
const len = strings.indexOfChar(text[offset..], '\n') orelse text[offset..].len;
return .{ offset, len };
},
else => {
const len = strings.indexOfChar(text[offset..], '\n') orelse text[offset..].len;
return .{ offset, len };
},
}
}
/// Returns offset and length of first secret found.
pub fn startsWithSecret(str: string) ?struct { usize, usize } {
if (startsWithRedactedItem(str, "_auth")) |auth| {
const offset, const len = auth;
return .{ offset, len };
}
if (startsWithRedactedItem(str, "_authToken")) |auth_token| {
const offset, const len = auth_token;
return .{ offset, len };
}
if (startsWithRedactedItem(str, "email")) |email| {
const offset, const len = email;
return .{ offset, len };
}
if (startsWithRedactedItem(str, "_password")) |password| {
const offset, const len = password;
return .{ offset, len };
}
if (startsWithRedactedItem(str, "token")) |token| {
const offset, const len = token;
return .{ offset, len };
}
if (startsWithUUID(str)) {
return .{ 0, 36 };
}
const npm_secret_len = startsWithNpmSecret(str);
if (npm_secret_len > 0) {
return .{ 0, npm_secret_len };
}
if (findUrlPassword(str)) |url_pass| {
const offset, const len = url_pass;
return .{ offset, len };
}
return null;
}
pub fn findUrlPassword(text: string) ?struct { usize, usize } {
if (!strings.hasPrefixComptime(text, "http")) return null;
var offset: usize = "http".len;
if (hasPrefixComptime(text[offset..], "://")) {
offset += "://".len;
} else if (hasPrefixComptime(text[offset..], "s://")) {
offset += "s://".len;
} else {
return null;
}
var remain = text[offset..];
const end = indexOfChar(remain, '\n') orelse remain.len;
remain = remain[0..end];
const at = indexOfChar(remain, '@') orelse return null;
const colon = indexOfCharNeg(remain[0..at], ':');
if (colon == -1 or colon == at - 1) return null;
offset += @intCast(colon + 1);
const len: usize = at - @as(usize, @intCast(colon + 1));
return .{ offset, len };
}
pub fn indexAnyComptime(target: string, comptime chars: string) ?usize {
for (target, 0..) |parent, i| {
inline for (chars) |char| {
if (char == parent) return i;
}
}
return null;
}
pub fn indexAnyComptimeT(comptime T: type, target: []const T, comptime chars: []const T) ?usize {
for (target, 0..) |parent, i| {
inline for (chars) |char| {
if (char == parent) return i;
}
}
return null;
}
pub fn indexEqualAny(in: anytype, target: string) ?usize {
for (in, 0..) |str, i| if (eqlLong(str, target, true)) return i;
return null;
}
pub fn repeatingAlloc(allocator: std.mem.Allocator, count: usize, char: u8) ![]u8 {
const buf = try allocator.alloc(u8, count);
repeatingBuf(buf, char);
return buf;
}
pub fn repeatingBuf(self: []u8, char: u8) void {
@memset(self, char);
}
pub fn indexOfCharNeg(self: string, char: u8) i32 {
for (self, 0..) |c, i| {
if (c == char) return @as(i32, @intCast(i));
}
return -1;
}
pub fn indexOfSigned(self: string, str: string) i32 {
const i = std.mem.indexOf(u8, self, str) orelse return -1;
return @as(i32, @intCast(i));
}
pub inline fn lastIndexOfChar(self: []const u8, char: u8) ?usize {
if (comptime Environment.isLinux) {
if (@inComptime()) {
return lastIndexOfCharT(u8, self, char);
}
const start = bun.C.memrchr(self.ptr, char, self.len) orelse return null;
const i = @intFromPtr(start) - @intFromPtr(self.ptr);
return @intCast(i);
}
return lastIndexOfCharT(u8, self, char);
}
pub inline fn lastIndexOfCharT(comptime T: type, self: []const T, char: T) ?usize {
return std.mem.lastIndexOfScalar(T, self, char);
}
pub inline fn lastIndexOf(self: string, str: string) ?usize {
return std.mem.lastIndexOf(u8, self, str);
}
pub inline fn indexOf(self: string, str: string) ?usize {
if (comptime !bun.Environment.isNative) {
return std.mem.indexOf(u8, self, str);
}
const self_len = self.len;
const str_len = str.len;
// > Both old and new libc's have the bug that if needle is empty,
// > haystack-1 (instead of haystack) is returned. And glibc 2.0 makes it
// > worse, returning a pointer to the last byte of haystack. This is fixed
// > in glibc 2.1.
if (self_len == 0 or str_len == 0 or self_len < str_len)
return null;
const self_ptr = self.ptr;
const str_ptr = str.ptr;
if (str_len == 1)
return indexOfCharUsize(self, str_ptr[0]);
const start = bun.C.memmem(self_ptr, self_len, str_ptr, str_len) orelse return null;
const i = @intFromPtr(start) - @intFromPtr(self_ptr);
bun.unsafeAssert(i < self_len);
return @as(usize, @intCast(i));
}
pub fn indexOfT(comptime T: type, haystack: []const T, needle: []const T) ?usize {
if (T == u8) return indexOf(haystack, needle);
return std.mem.indexOf(T, haystack, needle);
}
pub fn split(self: string, delimiter: string) SplitIterator {
return SplitIterator{
.buffer = self,
.index = 0,
.delimiter = delimiter,
};
}
pub const SplitIterator = struct {
buffer: []const u8,
index: ?usize,
delimiter: []const u8,
const Self = @This();
/// Returns a slice of the first field. This never fails.
/// Call this only to get the first field and then use `next` to get all subsequent fields.
pub fn first(self: *Self) []const u8 {
bun.unsafeAssert(self.index.? == 0);
return self.next().?;
}
/// Returns a slice of the next field, or null if splitting is complete.
pub fn next(self: *Self) ?[]const u8 {
const start = self.index orelse return null;
const end = if (indexOf(self.buffer[start..], self.delimiter)) |delim_start| blk: {
const del = delim_start + start;
self.index = del + self.delimiter.len;
break :blk delim_start + start;
} else blk: {
self.index = null;
break :blk self.buffer.len;
};
return self.buffer[start..end];
}
/// Returns a slice of the remaining bytes. Does not affect iterator state.
pub fn rest(self: Self) []const u8 {
const end = self.buffer.len;
const start = self.index orelse end;
return self.buffer[start..end];
}
/// Resets the iterator to the initial slice.
pub fn reset(self: *Self) void {
self.index = 0;
}
};
// --
// This is faster when the string is found, by about 2x for a 8 MB file.
// It is slower when the string is NOT found
// fn indexOfPosN(comptime T: type, buf: []const u8, start_index: usize, delimiter: []const u8, comptime n: comptime_int) ?usize {
// const k = delimiter.len;
// const V8x32 = @Vector(n, T);
// const V1x32 = @Vector(n, u1);
// const Vbx32 = @Vector(n, bool);
// const first = @splat(n, delimiter[0]);
// const last = @splat(n, delimiter[k - 1]);
// var end: usize = start_index + n;
// var start: usize = end - n;
// while (end < buf.len) {
// start = end - n;
// const last_end = @min(end + k - 1, buf.len);
// const last_start = last_end - n;
// // Look for the first character in the delimter
// const first_chunk: V8x32 = buf[start..end][0..n].*;
// const last_chunk: V8x32 = buf[last_start..last_end][0..n].*;
// const mask = @bitCast(V1x32, first == first_chunk) & @bitCast(V1x32, last == last_chunk);
// if (@reduce(.Or, mask) != 0) {
// // TODO: Use __builtin_clz???
// for (@as([n]bool, @bitCast(Vbx32, mask))) |match, i| {
// if (match and eqlLong(buf[start + i .. start + i + k], delimiter, false)) {
// return start + i;
// }
// }
// }
// end = @min(end + n, buf.len);
// }
// if (start < buf.len) return std.mem.indexOfPos(T, buf, start_index, delimiter);
// return null; // Not found
// }
pub fn cat(allocator: std.mem.Allocator, first: string, second: string) !string {
var out = try allocator.alloc(u8, first.len + second.len);
bun.copy(u8, out, first);
bun.copy(u8, out[first.len..], second);
return out;
}
// 31 character string or a slice
pub const StringOrTinyString = struct {
pub const Max = 31;
const Buffer = [Max]u8;
remainder_buf: Buffer = undefined,
meta: packed struct {
remainder_len: u7 = 0,
is_tiny_string: u1 = 0,
} = .{},
comptime {
bun.unsafeAssert(@sizeOf(@This()) == 32);
}
pub inline fn slice(this: *const StringOrTinyString) []const u8 {
// This is a switch expression instead of a statement to make sure it uses the faster assembly
return switch (this.meta.is_tiny_string) {
1 => this.remainder_buf[0..this.meta.remainder_len],
0 => @as([*]const u8, @ptrFromInt(std.mem.readInt(usize, this.remainder_buf[0..@sizeOf(usize)], .little)))[0..std.mem.readInt(usize, this.remainder_buf[@sizeOf(usize) .. @sizeOf(usize) * 2], .little)],
};
}
pub fn deinit(this: *StringOrTinyString, _: std.mem.Allocator) void {
if (this.meta.is_tiny_string == 1) return;
// var slice_ = this.slice();
// allocator.free(slice_);
}
pub fn initAppendIfNeeded(stringy: string, comptime Appender: type, appendy: Appender) OOM!StringOrTinyString {
if (stringy.len <= StringOrTinyString.Max) {
return StringOrTinyString.init(stringy);
}
return StringOrTinyString.init(try appendy.append(string, stringy));
}
pub fn initLowerCaseAppendIfNeeded(stringy: string, comptime Appender: type, appendy: Appender) OOM!StringOrTinyString {
if (stringy.len <= StringOrTinyString.Max) {
return StringOrTinyString.initLowerCase(stringy);
}
return StringOrTinyString.init(try appendy.appendLowerCase(string, stringy));
}
pub fn init(stringy: string) StringOrTinyString {
switch (stringy.len) {
0 => {
return StringOrTinyString{ .meta = .{
.is_tiny_string = 1,
.remainder_len = 0,
} };
},
1...(@sizeOf(Buffer)) => {
@setRuntimeSafety(false);
var tiny = StringOrTinyString{ .meta = .{
.is_tiny_string = 1,
.remainder_len = @as(u7, @truncate(stringy.len)),
} };
@memcpy(tiny.remainder_buf[0..tiny.meta.remainder_len], stringy[0..tiny.meta.remainder_len]);
return tiny;
},
else => {
var tiny = StringOrTinyString{ .meta = .{
.is_tiny_string = 0,
.remainder_len = 0,
} };
std.mem.writeInt(usize, tiny.remainder_buf[0..@sizeOf(usize)], @intFromPtr(stringy.ptr), .little);
std.mem.writeInt(usize, tiny.remainder_buf[@sizeOf(usize) .. @sizeOf(usize) * 2], stringy.len, .little);
return tiny;
},
}
}
pub fn initLowerCase(stringy: string) StringOrTinyString {
switch (stringy.len) {
0 => {
return StringOrTinyString{ .meta = .{
.is_tiny_string = 1,
.remainder_len = 0,
} };
},
1...(@sizeOf(Buffer)) => {
@setRuntimeSafety(false);
var tiny = StringOrTinyString{ .meta = .{
.is_tiny_string = 1,
.remainder_len = @as(u7, @truncate(stringy.len)),
} };
_ = copyLowercase(stringy, &tiny.remainder_buf);
return tiny;
},
else => {
var tiny = StringOrTinyString{ .meta = .{
.is_tiny_string = 0,
.remainder_len = 0,
} };
std.mem.writeInt(usize, tiny.remainder_buf[0..@sizeOf(usize)], @intFromPtr(stringy.ptr), .little);
std.mem.writeInt(usize, tiny.remainder_buf[@sizeOf(usize) .. @sizeOf(usize) * 2], stringy.len, .little);
return tiny;
},
}
}
};
pub fn copyLowercase(in: string, out: []u8) string {
var in_slice = in;
var out_slice = out;
begin: while (true) {
for (in_slice, 0..) |c, i| {
switch (c) {
'A'...'Z' => {
bun.copy(u8, out_slice, in_slice[0..i]);
out_slice[i] = std.ascii.toLower(c);
const end = i + 1;
in_slice = in_slice[end..];
out_slice = out_slice[end..];
continue :begin;
},
else => {},
}
}
bun.copy(u8, out_slice, in_slice);
break :begin;
}
return out[0..in.len];
}
pub fn copyLowercaseIfNeeded(in: string, out: []u8) string {
var in_slice = in;
var out_slice = out;
var any = false;
begin: while (true) {
for (in_slice, 0..) |c, i| {
switch (c) {
'A'...'Z' => {
bun.copy(u8, out_slice, in_slice[0..i]);
out_slice[i] = std.ascii.toLower(c);
const end = i + 1;
in_slice = in_slice[end..];
out_slice = out_slice[end..];
any = true;
continue :begin;
},
else => {},
}
}
if (any) bun.copy(u8, out_slice, in_slice);
break :begin;
}
return if (any) out[0..in.len] else in;
}
/// Copy a string into a buffer
/// Return the copied version
pub fn copy(buf: []u8, src: []const u8) []const u8 {
const len = @min(buf.len, src.len);
if (len > 0)
@memcpy(buf[0..len], src[0..len]);
return buf[0..len];
}
/// startsWith except it checks for non-empty strings
pub fn hasPrefix(self: string, str: string) bool {
return str.len > 0 and startsWith(self, str);
}
pub fn startsWith(self: string, str: string) bool {
if (str.len > self.len) {
return false;
}
return eqlLong(self[0..str.len], str, false);
}
/// Transliterated from:
/// https://github.com/rust-lang/rust/blob/91376f416222a238227c84a848d168835ede2cc3/library/core/src/str/mod.rs#L188
pub fn isOnCharBoundary(self: string, idx: usize) bool {
// 0 is always ok.
// Test for 0 explicitly so that it can optimize out the check
// easily and skip reading string data for that case.
// Note that optimizing `self.get(..idx)` relies on this.
if (idx == 0) {
return true;
}
// For `idx >= self.len` we have two options:
//
// - idx == self.len
// Empty strings are valid, so return true
// - idx > self.len
// In this case return false
//
// The check is placed exactly here, because it improves generated
// code on higher opt-levels. See PR #84751 for more details.
// TODO(zack) this code is optimized for Rust's `self.as_bytes().get(idx)` function, don'
if (idx >= self.len) return idx == self.len;
return isUtf8CharBoundary(self[idx]);
}
pub fn isUtf8CharBoundary(c: u8) bool {
// This is bit magic equivalent to: b < 128 || b >= 192
return @as(i8, @intCast(c)) >= -0x40;
}
pub fn startsWithCaseInsensitiveAscii(self: string, prefix: string) bool {
return self.len >= prefix.len and eqlCaseInsensitiveASCII(self[0..prefix.len], prefix, false);
}
pub fn startsWithGeneric(comptime T: type, self: []const T, str: []const T) bool {
if (str.len > self.len) {
return false;
}
return eqlLong(bun.reinterpretSlice(u8, self[0..str.len]), str, false);
}
pub inline fn endsWith(self: string, str: string) bool {
return str.len == 0 or @call(bun.callmod_inline, std.mem.endsWith, .{ u8, self, str });
}
pub inline fn endsWithComptime(self: string, comptime str: anytype) bool {
return self.len >= str.len and eqlComptimeIgnoreLen(self[self.len - str.len .. self.len], comptime str);
}
pub inline fn startsWithChar(self: string, char: u8) bool {
return self.len > 0 and self[0] == char;
}
pub inline fn endsWithChar(self: string, char: u8) bool {
return self.len > 0 and self[self.len - 1] == char;
}
pub inline fn endsWithCharOrIsZeroLength(self: string, char: u8) bool {
return self.len == 0 or self[self.len - 1] == char;
}
pub fn withoutTrailingSlash(this: string) []const u8 {
var href = this;
while (href.len > 1 and (switch (href[href.len - 1]) {
'/', '\\' => true,
else => false,
})) {
href.len -= 1;
}
return href;
}
/// Does not strip the device root (C:\ or \\Server\Share\ portion off of the path)
pub fn withoutTrailingSlashWindowsPath(input: string) []const u8 {
if (Environment.isPosix or input.len < 3 or input[1] != ':')
return withoutTrailingSlash(input);
const root_len = bun.path.windowsFilesystemRoot(input).len + 1;
var path = input;
while (path.len > root_len and (switch (path[path.len - 1]) {
'/', '\\' => true,
else => false,
})) {
path.len -= 1;
}
bun.assert(!isWindowsAbsolutePathMissingDriveLetter(u8, path));
return path;
}
pub fn withoutLeadingSlash(this: string) []const u8 {
return std.mem.trimLeft(u8, this, "/");
}
pub fn withoutLeadingPathSeparator(this: string) []const u8 {
return std.mem.trimLeft(u8, this, &.{std.fs.path.sep});
}
pub fn endsWithAny(self: string, str: string) bool {
const end = self[self.len - 1];
for (str) |char| {
if (char == end) {
return true;
}
}
return false;
}
pub fn quotedAlloc(allocator: std.mem.Allocator, self: string) !string {
var count: usize = 0;
for (self) |char| {
count += @intFromBool(char == '"');
}
if (count == 0) {
return allocator.dupe(u8, self);
}
var i: usize = 0;
var out = try allocator.alloc(u8, self.len + count);
for (self) |char| {
if (char == '"') {
out[i] = '\\';
i += 1;
}
out[i] = char;
i += 1;
}
return out;
}
pub fn eqlAnyComptime(self: string, comptime list: []const string) bool {
inline for (list) |item| {
if (eqlComptimeCheckLenWithType(u8, self, item, true)) return true;
}
return false;
}
/// Count the occurrences of a character in an ASCII byte array
/// uses SIMD
pub fn countChar(self: string, char: u8) usize {
var total: usize = 0;
var remaining = self;
const splatted: AsciiVector = @splat(char);
while (remaining.len >= 16) {
const vec: AsciiVector = remaining[0..ascii_vector_size].*;
const cmp = @popCount(@as(@Vector(ascii_vector_size, u1), @bitCast(vec == splatted)));
total += @as(usize, @reduce(.Add, cmp));
remaining = remaining[ascii_vector_size..];
}
while (remaining.len > 0) {
total += @as(usize, @intFromBool(remaining[0] == char));
remaining = remaining[1..];
}
return total;
}
pub fn endsWithAnyComptime(self: string, comptime str: string) bool {
if (comptime str.len < 10) {
const last = self[self.len - 1];
inline for (str) |char| {
if (char == last) {
return true;
}
}
return false;
} else {
return endsWithAny(self, str);
}
}
pub fn eql(self: string, other: anytype) bool {
if (self.len != other.len) return false;
if (comptime @TypeOf(other) == *string) {
return eql(self, other.*);
}
for (self, 0..) |c, i| {
if (other[i] != c) return false;
}
return true;
}
pub fn eqlComptimeT(comptime T: type, self: []const T, comptime alt: anytype) bool {
if (T == u16) {
return eqlComptimeUTF16(self, alt);
}
return eqlComptime(self, alt);
}
pub fn eqlComptime(self: string, comptime alt: anytype) bool {
return eqlComptimeCheckLenWithType(u8, self, alt, true);