forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_immutable.zig
4730 lines (4024 loc) · 177 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;
pub const joiner = @import("./string_joiner.zig");
const log = bun.Output.scoped(.STR, true);
pub const Encoding = enum {
ascii,
utf8,
latin1,
utf16,
};
pub inline fn containsChar(self: string, char: u8) bool {
return indexOfChar(self, char) != null;
}
pub inline fn contains(self: string, str: string) bool {
return indexOf(self, str) != null;
}
pub fn w(comptime str: []const u8) [:0]const u16 {
comptime var output: [str.len + 1]u16 = undefined;
for (str, 0..) |c, i| {
output[i] = c;
}
output[str.len] = 0;
const Static = struct {
pub const literal: [:0]const u16 = output[0 .. output.len - 1 :0];
};
return Static.literal;
}
pub fn toUTF16Literal(comptime str: []const u8) []const u16 {
return comptime brk: {
comptime var output: [str.len]u16 = undefined;
for (str, 0..) |c, i| {
output[i] = c;
}
const Static = struct {
pub const literal: []const u16 = output[0..];
};
break :brk Static.literal;
};
}
pub const OptionalUsize = std.meta.Int(.unsigned, @bitSizeOf(usize) - 1);
pub fn indexOfAny(slice: string, comptime str: anytype) ?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) std.debug.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 {
for (self, 0..) |c, i| {
inline for (str) |a| {
if (c == a) {
return @as(OptionalUsize, @intCast(i));
}
}
}
return null;
}
pub inline fn containsComptime(self: string, comptime str: string) bool {
var remain = self;
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;
}
remain = remain[str.len..];
}
return false;
}
pub const includes = contains;
pub fn inMapCaseInsensitive(self: string, comptime ComptimeStringMap: anytype) ?ComptimeStringMap.Value {
return bun.String.static(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 inline 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;
},
else => return false,
}
}
return !scoped or slash_index > 0 and slash_index + 1 < target.len;
}
pub inline fn indexAny(in: anytype, target: string) ?usize {
for (in, 0..) |str, i| if (indexOf(str, target) != null) return i;
return null;
}
pub inline 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 inline 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 {
var 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 {
var i: u32 = 0;
while (i < self.len) : (i += 1) {
if (self[i] == char) return @as(i32, @intCast(i));
}
return -1;
}
/// Format a string to an ECMAScript identifier.
/// Unlike the string_mutable.zig version, this always allocate/copy
pub fn fmtIdentifier(name: string) FormatValidIdentifier {
return FormatValidIdentifier{ .name = name };
}
/// Format a string to an ECMAScript identifier.
/// Different implementation than string_mutable because string_mutable may avoid allocating
/// This will always allocate
pub const FormatValidIdentifier = struct {
name: string,
const js_lexer = @import("./js_lexer.zig");
pub fn format(self: FormatValidIdentifier, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
var iterator = strings.CodepointIterator.init(self.name);
var cursor = strings.CodepointIterator.Cursor{};
var has_needed_gap = false;
var needs_gap = false;
var start_i: usize = 0;
if (!iterator.next(&cursor)) {
try writer.writeAll("_");
return;
}
// Common case: no gap necessary. No allocation necessary.
needs_gap = !js_lexer.isIdentifierStart(cursor.c);
if (!needs_gap) {
// Are there any non-alphanumeric chars at all?
while (iterator.next(&cursor)) {
if (!js_lexer.isIdentifierContinue(cursor.c) or cursor.width > 1) {
needs_gap = true;
start_i = cursor.i;
break;
}
}
}
if (needs_gap) {
needs_gap = false;
if (start_i > 0) try writer.writeAll(self.name[0..start_i]);
var slice = self.name[start_i..];
iterator = strings.CodepointIterator.init(slice);
cursor = strings.CodepointIterator.Cursor{};
while (iterator.next(&cursor)) {
if (js_lexer.isIdentifierContinue(cursor.c) and cursor.width == 1) {
if (needs_gap) {
try writer.writeAll("_");
needs_gap = false;
has_needed_gap = true;
}
try writer.writeAll(slice[cursor.i .. cursor.i + @as(u32, cursor.width)]);
} else if (!needs_gap) {
needs_gap = true;
// skip the code point, replace it with a single _
}
}
// If it ends with an emoji
if (needs_gap) {
try writer.writeAll("_");
needs_gap = false;
has_needed_gap = true;
}
return;
}
try writer.writeAll(self.name);
}
};
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: string, char: u8) ?usize {
return std.mem.lastIndexOfScalar(u8, 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);
std.debug.assert(i < self_len);
return @as(usize, @intCast(i));
}
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 {
std.debug.assert(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;
}
// 30 character string or a slice
pub const StringOrTinyString = struct {
pub const Max = 30;
const Buffer = [Max]u8;
remainder_buf: Buffer = undefined,
remainder_len: u7 = 0,
is_tiny_string: u1 = 0,
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.is_tiny_string) {
1 => this.remainder_buf[0..this.remainder_len],
0 => @as([*]const u8, @ptrFromInt(std.mem.readIntNative(usize, this.remainder_buf[0..@sizeOf(usize)])))[0..std.mem.readIntNative(usize, this.remainder_buf[@sizeOf(usize) .. @sizeOf(usize) * 2])],
};
}
pub fn deinit(this: *StringOrTinyString, _: std.mem.Allocator) void {
if (this.is_tiny_string == 1) return;
// var slice_ = this.slice();
// allocator.free(slice_);
}
pub fn initAppendIfNeeded(stringy: string, comptime Appender: type, appendy: Appender) !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) !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{ .is_tiny_string = 1, .remainder_len = 0 };
},
1...(@sizeOf(Buffer)) => {
@setRuntimeSafety(false);
var tiny = StringOrTinyString{
.is_tiny_string = 1,
.remainder_len = @as(u7, @truncate(stringy.len)),
};
@memcpy(tiny.remainder_buf[0..tiny.remainder_len], stringy[0..tiny.remainder_len]);
return tiny;
},
else => {
var tiny = StringOrTinyString{
.is_tiny_string = 0,
.remainder_len = 0,
};
std.mem.writeIntNative(usize, tiny.remainder_buf[0..@sizeOf(usize)], @intFromPtr(stringy.ptr));
std.mem.writeIntNative(usize, tiny.remainder_buf[@sizeOf(usize) .. @sizeOf(usize) * 2], stringy.len);
return tiny;
},
}
}
pub fn initLowerCase(stringy: string) StringOrTinyString {
switch (stringy.len) {
0 => {
return StringOrTinyString{ .is_tiny_string = 1, .remainder_len = 0 };
},
1...(@sizeOf(Buffer)) => {
@setRuntimeSafety(false);
var tiny = StringOrTinyString{
.is_tiny_string = 1,
.remainder_len = @as(u7, @truncate(stringy.len)),
};
_ = copyLowercase(stringy, &tiny.remainder_buf);
return tiny;
},
else => {
var tiny = StringOrTinyString{
.is_tiny_string = 0,
.remainder_len = 0,
};
std.mem.writeIntNative(usize, tiny.remainder_buf[0..@sizeOf(usize)], @intFromPtr(stringy.ptr));
std.mem.writeIntNative(usize, tiny.remainder_buf[@sizeOf(usize) .. @sizeOf(usize) * 2], stringy.len);
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;
}
test "indexOf" {
const fixtures = .{
.{
"0123456789",
"456",
},
.{
"/foo/bar/baz/bacon/eggs/lettuce/tomatoe",
"bacon",
},
.{
"/foo/bar/baz/bacon////eggs/lettuce/tomatoe",
"eggs",
},
.{
"////////////////zfoo/bar/baz/bacon/eggs/lettuce/tomatoe",
"/",
},
.{
"/okay/well/thats/even/longer/now/well/thats/even/longer/now/well/thats/even/longer/now/foo/bar/baz/bacon/eggs/lettuce/tomatoe",
"/tomatoe",
},
.{
"/okay///////////so much length i can't believe it!much length i can't believe it!much length i can't believe it!much length i can't believe it!much length i can't believe it!much length i can't believe it!much length i can't believe it!much length i can't believe it!/well/thats/even/longer/now/well/thats/even/longer/now/well/thats/even/longer/now/foo/bar/baz/bacon/eggs/lettuce/tomatoe",
"/tomatoe",
},
};
inline for (fixtures) |pair| {
try std.testing.expectEqual(
indexOf(pair[0], pair[1]).?,
std.mem.indexOf(u8, pair[0], pair[1]).?,
);
}
}
test "eqlComptimeCheckLen" {
try std.testing.expectEqual(eqlComptime("bun-darwin-aarch64.zip", "bun-darwin-aarch64.zip"), true);
const sizes = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 23, 22, 24 };
inline for (sizes) |size| {
var buf: [size]u8 = undefined;
@memset(&buf, 'a');
var buf_copy: [size]u8 = undefined;
@memset(&buf_copy, 'a');
var bad: [size]u8 = undefined;
@memset(&bad, 'b');
try std.testing.expectEqual(std.mem.eql(u8, &buf, &buf_copy), eqlComptime(&buf, comptime brk: {
var buf_copy_: [size]u8 = undefined;
@memset(&buf_copy_, 'a');
break :brk buf_copy_;
}));
try std.testing.expectEqual(std.mem.eql(u8, &buf, &bad), eqlComptime(&bad, comptime brk: {
var buf_copy_: [size]u8 = undefined;
@memset(&buf_copy_, 'a');
break :brk buf_copy_;
}));
}
}
test "eqlComptimeUTF16" {
try std.testing.expectEqual(eqlComptimeUTF16(toUTF16Literal("bun-darwin-aarch64.zip"), "bun-darwin-aarch64.zip"), true);
const sizes = [_]u16{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 23, 22, 24 };
inline for (sizes) |size| {
var buf: [size]u16 = undefined;
@memset(&buf, @as(u8, 'a'));
var buf_copy: [size]u16 = undefined;
@memset(&buf_copy, @as(u8, 'a'));
var bad: [size]u16 = undefined;
@memset(&bad, @as(u16, 'b'));
try std.testing.expectEqual(std.mem.eql(u16, &buf, &buf_copy), eqlComptimeUTF16(&buf, comptime &brk: {
var buf_copy_: [size]u8 = undefined;
@memset(&buf_copy_, @as(u8, 'a'));
break :brk buf_copy_;
}));
try std.testing.expectEqual(std.mem.eql(u16, &buf, &bad), eqlComptimeUTF16(&bad, comptime &brk: {
var buf_copy_: [size]u8 = undefined;
@memset(&buf_copy_, @as(u8, 'a'));
break :brk buf_copy_;
}));
}
}
test "copyLowercase" {
{
var in = "Hello, World!";
var out = std.mem.zeroes([in.len]u8);
var out_ = copyLowercase(in, &out);
try std.testing.expectEqualStrings(out_, "hello, world!");
}
{
var in = "_ListCache";
var out = std.mem.zeroes([in.len]u8);
var out_ = copyLowercase(in, &out);
try std.testing.expectEqualStrings(out_, "_listcache");
}
}
test "StringOrTinyString" {
const correct: string = "helloooooooo";
const big = "wawaweewaverylargeihaveachairwawaweewaverylargeihaveachairwawaweewaverylargeihaveachairwawaweewaverylargeihaveachair";
var str = StringOrTinyString.init(correct);
try std.testing.expectEqualStrings(correct, str.slice());
str = StringOrTinyString.init(big);
try std.testing.expectEqualStrings(big, str.slice());
try std.testing.expect(@sizeOf(StringOrTinyString) == 32);
}
test "StringOrTinyString Lowercase" {
const correct: string = "HELLO!!!!!";
var str = StringOrTinyString.initLowerCase(correct);
try std.testing.expectEqualStrings("hello!!!!!", str.slice());
}
/// 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);
}
pub inline fn endsWith(self: string, str: string) bool {
return str.len == 0 or @call(.always_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 or self[self.len - 1] == char;
}
pub fn withoutTrailingSlash(this: string) []const u8 {
var href = this;
while (href.len > 1 and href[href.len - 1] == '/') {
href.len -= 1;
}
return href;
}
pub fn withTrailingSlash(dir: string, in: string) []const u8 {
if (comptime Environment.allow_assert) std.debug.assert(bun.isSliceInBuffer(dir, in));
return in[0..@min(strings.withoutTrailingSlash(in[0..@min(dir.len + 1, in.len)]).len + 1, in.len)];
}
pub fn withoutLeadingSlash(this: string) []const u8 {
return std.mem.trimLeft(u8, this, "/");
}
pub fn endsWithAny(self: string, str: string) bool {
const end = self[self.len - 1];
for (str) |char| {
if (char == end) {
return true;
}
}
return false;
}
// Formats a string to be safe to output in a Github action.
// - Encodes "\n" as "%0A" to support multi-line strings.
// https://github.com/actions/toolkit/issues/193#issuecomment-605394935
// - Strips ANSI output as it will appear malformed.
pub fn githubActionWriter(writer: anytype, self: string) !void {
var offset: usize = 0;
const end = @as(u32, @truncate(self.len));
while (offset < end) {
if (indexOfNewlineOrNonASCIIOrANSI(self, @as(u32, @truncate(offset)))) |i| {
const byte = self[i];
if (byte > 0x7F) {
offset += @max(wtf8ByteSequenceLength(byte), 1);
continue;
}
if (i > 0) {
try writer.writeAll(self[offset..i]);
}
var n: usize = 1;
if (byte == '\n') {
try writer.writeAll("%0A");
} else if (i + 1 < end) {
const next = self[i + 1];
if (byte == '\r' and next == '\n') {
n += 1;
try writer.writeAll("%0A");
} else if (byte == '\x1b' and next == '[') {
n += 1;
if (i + 2 < end) {
const remain = self[(i + 2)..@min(i + 5, end)];
if (indexOfChar(remain, 'm')) |j| {
n += j + 1;
}
}
}
}
offset = i + n;
} else {
try writer.writeAll(self[offset..end]);
break;
}
}
}
pub const GithubActionFormatter = struct {
text: string,
pub fn format(this: GithubActionFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
try githubActionWriter(writer, this.text);
}
};
pub fn githubAction(self: string) strings.GithubActionFormatter {
return GithubActionFormatter{
.text = self,
};
}
pub fn quotedWriter(writer: anytype, self: string) !void {
var remain = self;
if (strings.containsNewlineOrNonASCIIOrQuote(remain)) {
try bun.js_printer.writeJSONString(self, @TypeOf(writer), writer, strings.Encoding.utf8);
} else {
try writer.writeAll("\"");
try writer.writeAll(self);
try writer.writeAll("\"");
}
}
pub const QuotedFormatter = struct {
text: []const u8,
pub fn format(this: QuotedFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
try strings.quotedWriter(writer, this.text);
}
};
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;
}
test "countChar" {
try std.testing.expectEqual(countChar("hello there", ' '), 1);
try std.testing.expectEqual(countChar("hello;;;there", ';'), 3);
try std.testing.expectEqual(countChar("hello there", 'z'), 0);
try std.testing.expectEqual(countChar("hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there ", ' '), 28);
try std.testing.expectEqual(countChar("hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there ", 'z'), 0);
try std.testing.expectEqual(countChar("hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there", ' '), 27);
}
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 inline fn eqlInsensitive(self: string, other: anytype) bool {
return std.ascii.eqlIgnoreCase(self, other);
}
pub fn eqlComptime(self: string, comptime alt: anytype) bool {
return eqlComptimeCheckLenWithType(u8, self, alt, true);
}
pub fn eqlComptimeUTF16(self: []const u16, comptime alt: []const u8) bool {
return eqlComptimeCheckLenWithType(u16, self, comptime toUTF16Literal(alt), true);
}
pub fn eqlComptimeIgnoreLen(self: string, comptime alt: anytype) bool {
return eqlComptimeCheckLenWithType(u8, self, alt, false);
}
pub fn hasPrefixComptime(self: string, comptime alt: anytype) bool {
return self.len >= alt.len and eqlComptimeCheckLenWithType(u8, self[0..alt.len], alt, false);
}
inline fn eqlComptimeCheckLenWithKnownType(comptime Type: type, a: []const Type, comptime b: []const Type, comptime check_len: bool) bool {
@setEvalBranchQuota(9999);
if (comptime check_len) {
if (comptime b.len == 0) {
return a.len == 0;
}
switch (a.len) {
b.len => {},
else => return false,
}
}
const len = comptime b.len;
comptime var dword_length = b.len >> if (Environment.isNative) 3 else 2;
const slice = b;
const divisor = comptime @sizeOf(Type);
comptime var b_ptr: usize = 0;
inline while (dword_length > 0) : (dword_length -= 1) {
if (@as(usize, @bitCast(a[b_ptr..][0 .. @sizeOf(usize) / divisor].*)) != comptime @as(usize, @bitCast((slice[b_ptr..])[0 .. @sizeOf(usize) / divisor].*)))
return false;
comptime b_ptr += @sizeOf(usize);
if (comptime b_ptr == b.len) return true;
}
if (comptime @sizeOf(usize) == 8) {
if (comptime (len & 4) != 0) {
if (@as(u32, @bitCast(a[b_ptr..][0 .. @sizeOf(u32) / divisor].*)) != comptime @as(u32, @bitCast((slice[b_ptr..])[0 .. @sizeOf(u32) / divisor].*)))
return false;
comptime b_ptr += @sizeOf(u32);
if (comptime b_ptr == b.len) return true;
}
}
if (comptime (len & 2) != 0) {
if (@as(u16, @bitCast(a[b_ptr..][0 .. @sizeOf(u16) / divisor].*)) != comptime @as(u16, @bitCast(slice[b_ptr .. b_ptr + (@sizeOf(u16) / divisor)].*)))
return false;
comptime b_ptr += @sizeOf(u16);
if (comptime b_ptr == b.len) return true;
}
if ((comptime (len & 1) != 0) and a[b_ptr] != comptime b[b_ptr]) return false;
return true;
}
/// Check if two strings are equal with one of the strings being a comptime-known value
///
/// strings.eqlComptime(input, "hello world");
/// strings.eqlComptime(input, "hai");
pub inline fn eqlComptimeCheckLenWithType(comptime Type: type, a: []const Type, comptime b: anytype, comptime check_len: bool) bool {
return eqlComptimeCheckLenWithKnownType(comptime Type, a, if (@typeInfo(@TypeOf(b)) != .Pointer) &b else b, comptime check_len);
}
pub fn eqlCaseInsensitiveASCIIIgnoreLength(
a: string,
b: string,
) bool {
return eqlCaseInsensitiveASCII(a, b, false);
}
pub fn eqlCaseInsensitiveASCIIICheckLength(
a: string,
b: string,
) bool {
return eqlCaseInsensitiveASCII(a, b, true);
}