forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring.zig
1483 lines (1220 loc) · 51.4 KB
/
string.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 bun = @import("root").bun;
const JSC = bun.JSC;
const JSValue = bun.JSC.JSValue;
const Parent = @This();
const OOM = bun.OOM;
pub const BufferOwnership = enum(u32) {
BufferInternal,
BufferOwned,
BufferSubstring,
BufferExternal,
};
pub const WTFStringImpl = *WTFStringImplStruct;
pub const WTFStringImplStruct = extern struct {
m_refCount: u32 = 0,
m_length: u32 = 0,
m_ptr: extern union { latin1: [*]const u8, utf16: [*]const u16 },
m_hashAndFlags: u32 = 0,
// ---------------------------------------------------------------------
// These details must stay in sync with WTFStringImpl.h in WebKit!
// ---------------------------------------------------------------------
const s_flagCount: u32 = 8;
const s_flagMask: u32 = (1 << s_flagCount) - 1;
const s_flagStringKindCount: u32 = 4;
const s_hashZeroValue: u32 = 0;
const s_hashFlagStringKindIsAtom: u32 = @as(1, u32) << (s_flagStringKindCount);
const s_hashFlagStringKindIsSymbol: u32 = @as(1, u32) << (s_flagStringKindCount + 1);
const s_hashMaskStringKind: u32 = s_hashFlagStringKindIsAtom | s_hashFlagStringKindIsSymbol;
const s_hashFlagDidReportCost: u32 = @as(1, u32) << 3;
const s_hashFlag8BitBuffer: u32 = 1 << 2;
const s_hashMaskBufferOwnership: u32 = (1 << 0) | (1 << 1);
/// The bottom bit in the ref count indicates a static (immortal) string.
const s_refCountFlagIsStaticString = 0x1;
/// This allows us to ref / deref without disturbing the static string flag.
const s_refCountIncrement = 0x2;
// ---------------------------------------------------------------------
pub fn refCount(this: WTFStringImpl) u32 {
return this.m_refCount / s_refCountIncrement;
}
pub fn isStatic(this: WTFStringImpl) bool {
return this.m_refCount & s_refCountIncrement != 0;
}
pub fn byteLength(this: WTFStringImpl) usize {
return if (this.is8Bit()) this.m_length else this.m_length * 2;
}
extern fn WTFStringImpl__isThreadSafe(WTFStringImpl) bool;
pub fn isThreadSafe(this: WTFStringImpl) bool {
return WTFStringImpl__isThreadSafe(this);
}
pub fn byteSlice(this: WTFStringImpl) []const u8 {
return this.m_ptr.latin1[0..this.byteLength()];
}
pub inline fn is8Bit(self: WTFStringImpl) bool {
return (self.m_hashAndFlags & s_hashFlag8BitBuffer) != 0;
}
pub inline fn length(self: WTFStringImpl) u32 {
return self.m_length;
}
pub inline fn utf16Slice(self: WTFStringImpl) []const u16 {
bun.assert(!is8Bit(self));
return self.m_ptr.utf16[0..length(self)];
}
pub inline fn latin1Slice(self: WTFStringImpl) []const u8 {
bun.assert(is8Bit(self));
return self.m_ptr.latin1[0..length(self)];
}
/// Caller must ensure that the string is 8-bit and ASCII.
pub inline fn utf8Slice(self: WTFStringImpl) []const u8 {
if (comptime bun.Environment.allow_assert)
bun.assert(canUseAsUTF8(self));
return self.m_ptr.latin1[0..length(self)];
}
pub fn toZigString(this: WTFStringImpl) ZigString {
if (this.is8Bit()) {
return ZigString.init(this.latin1Slice());
} else {
return ZigString.initUTF16(this.utf16Slice());
}
}
pub inline fn deref(self: WTFStringImpl) void {
JSC.markBinding(@src());
const current_count = self.refCount();
bun.assert(current_count > 0);
Bun__WTFStringImpl__deref(self);
if (comptime bun.Environment.allow_assert) {
if (current_count > 1) {
bun.assert(self.refCount() < current_count or self.isStatic());
}
}
}
pub inline fn ref(self: WTFStringImpl) void {
JSC.markBinding(@src());
const current_count = self.refCount();
bun.assert(current_count > 0);
Bun__WTFStringImpl__ref(self);
bun.assert(self.refCount() > current_count or self.isStatic());
}
pub fn toLatin1Slice(this: WTFStringImpl) ZigString.Slice {
this.ref();
return ZigString.Slice.init(this.refCountAllocator(), this.latin1Slice());
}
extern fn Bun__WTFStringImpl__ensureHash(this: WTFStringImpl) void;
/// Compute the hash() if necessary
pub fn ensureHash(this: WTFStringImpl) void {
JSC.markBinding(@src());
Bun__WTFStringImpl__ensureHash(this);
}
pub fn toUTF8(this: WTFStringImpl, allocator: std.mem.Allocator) ZigString.Slice {
if (this.is8Bit()) {
if (bun.strings.toUTF8FromLatin1(allocator, this.latin1Slice()) catch bun.outOfMemory()) |utf8| {
return ZigString.Slice.init(allocator, utf8.items);
}
return this.toLatin1Slice();
}
return ZigString.Slice.init(
allocator,
bun.strings.toUTF8Alloc(allocator, this.utf16Slice()) catch bun.outOfMemory(),
);
}
pub const max = std.math.maxInt(u32);
pub fn toUTF8WithoutRef(this: WTFStringImpl, allocator: std.mem.Allocator) ZigString.Slice {
if (this.is8Bit()) {
if (bun.strings.toUTF8FromLatin1(allocator, this.latin1Slice()) catch bun.outOfMemory()) |utf8| {
return ZigString.Slice.init(allocator, utf8.items);
}
return ZigString.Slice.fromUTF8NeverFree(this.latin1Slice());
}
return ZigString.Slice.init(
allocator,
bun.strings.toUTF8Alloc(allocator, this.utf16Slice()) catch bun.outOfMemory(),
);
}
pub fn toOwnedSliceZ(this: WTFStringImpl, allocator: std.mem.Allocator) [:0]u8 {
if (this.is8Bit()) {
if (bun.strings.toUTF8FromLatin1Z(allocator, this.latin1Slice()) catch bun.outOfMemory()) |utf8| {
return utf8.items[0 .. utf8.items.len - 1 :0];
}
return allocator.dupeZ(u8, this.latin1Slice()) catch bun.outOfMemory();
}
return bun.strings.toUTF8AllocZ(allocator, this.utf16Slice()) catch bun.outOfMemory();
}
pub fn toUTF8IfNeeded(this: WTFStringImpl, allocator: std.mem.Allocator) ?ZigString.Slice {
if (this.is8Bit()) {
if (bun.strings.toUTF8FromLatin1(allocator, this.latin1Slice()) catch bun.outOfMemory()) |utf8| {
return ZigString.Slice.init(allocator, utf8.items);
}
return null;
}
return ZigString.Slice.init(
allocator,
bun.strings.toUTF8Alloc(allocator, this.utf16Slice()) catch bun.outOfMemory(),
);
}
/// Avoid using this in code paths that are about to get the string as a UTF-8
/// In that case, use toUTF8IfNeeded instead.
pub fn canUseAsUTF8(this: WTFStringImpl) bool {
return this.is8Bit() and bun.strings.isAllASCII(this.latin1Slice());
}
pub fn utf8ByteLength(this: WTFStringImpl) usize {
if (this.is8Bit()) {
const input = this.latin1Slice();
return if (input.len > 0) JSC.WebCore.Encoder.byteLengthU8(input.ptr, input.len, .utf8) else 0;
} else {
const input = this.utf16Slice();
return if (input.len > 0) JSC.WebCore.Encoder.byteLengthU16(input.ptr, input.len, .utf8) else 0;
}
}
pub fn utf16ByteLength(this: WTFStringImpl) usize {
// All latin1 characters fit in a single UTF-16 code unit.
return this.length() * 2;
}
pub fn latin1ByteLength(this: WTFStringImpl) usize {
// Not all UTF-16 characters fit are representable in latin1.
// Those get truncated?
return this.length();
}
pub fn refCountAllocator(self: WTFStringImpl) std.mem.Allocator {
return std.mem.Allocator{ .ptr = self, .vtable = StringImplAllocator.VTablePtr };
}
pub fn hasPrefix(self: WTFStringImpl, text: []const u8) bool {
return Bun__WTFStringImpl__hasPrefix(self, text.ptr, text.len);
}
extern fn Bun__WTFStringImpl__deref(self: WTFStringImpl) void;
extern fn Bun__WTFStringImpl__ref(self: WTFStringImpl) void;
extern fn Bun__WTFStringImpl__hasPrefix(self: *const WTFStringImplStruct, offset: [*]const u8, length: usize) bool;
};
pub const StringImplAllocator = struct {
fn alloc(ptr: *anyopaque, len: usize, _: u8, _: usize) ?[*]u8 {
var this = bun.cast(WTFStringImpl, ptr);
const len_ = this.byteLength();
if (len_ != len) {
// we don't actually allocate, we just reference count
return null;
}
this.ref();
// we should never actually allocate
return @constCast(this.m_ptr.latin1);
}
fn resize(_: *anyopaque, _: []u8, _: u8, _: usize, _: usize) bool {
return false;
}
pub fn free(
ptr: *anyopaque,
buf: []u8,
_: u8,
_: usize,
) void {
var this = bun.cast(WTFStringImpl, ptr);
bun.assert(this.latin1Slice().ptr == buf.ptr);
bun.assert(this.latin1Slice().len == buf.len);
this.deref();
}
pub const VTable = std.mem.Allocator.VTable{
.alloc = &alloc,
.resize = &resize,
.free = &free,
};
pub const VTablePtr = &VTable;
};
pub const Tag = enum(u8) {
/// String is not valid. Observed on some failed operations.
/// To prevent crashes, this value acts similarly to .Empty (such as length = 0)
Dead = 0,
/// String is backed by a WTF::StringImpl from JavaScriptCore.
/// Can be in either `latin1` or `utf16le` encodings.
WTFStringImpl = 1,
/// Memory has an unknown owner, likely in Bun's Zig codebase. If `isGloballyAllocated`
/// is set, then it is owned by mimalloc. When converted to JSValue it has to be cloned
/// into a WTF::String.
/// Can be in either `utf8` or `utf16le` encodings.
ZigString = 2,
/// Static memory that is guaranteed to never be freed. When converted to WTF::String,
/// the memory is not cloned, but instead referenced with WTF::ExternalStringImpl.
/// Can be in either `utf8` or `utf16le` encodings.
StaticZigString = 3,
/// String is ""
Empty = 4,
};
const ZigString = bun.JSC.ZigString;
pub const StringImpl = extern union {
ZigString: ZigString,
WTFStringImpl: WTFStringImpl,
StaticZigString: ZigString,
Dead: void,
Empty: void,
};
/// Prefer using String instead of ZigString in new code.
pub const String = extern struct {
pub const name = "BunString";
tag: Tag,
value: StringImpl,
pub const empty = String{ .tag = .Empty, .value = .{ .Empty = {} } };
pub const dead = String{ .tag = .Dead, .value = .{ .Dead = {} } };
pub const StringImplAllocator = Parent.StringImplAllocator;
extern fn BunString__fromLatin1(bytes: [*]const u8, len: usize) String;
extern fn BunString__fromBytes(bytes: [*]const u8, len: usize) String;
extern fn BunString__fromUTF16(bytes: [*]const u16, len: usize) String;
extern fn BunString__fromUTF16ToLatin1(bytes: [*]const u16, len: usize) String;
extern fn BunString__fromLatin1Unitialized(len: usize) String;
extern fn BunString__fromUTF16Unitialized(len: usize) String;
pub fn ascii(bytes: []const u8) String {
return String{ .tag = .ZigString, .value = .{ .ZigString = ZigString.init(bytes) } };
}
pub fn isGlobal(this: String) bool {
return this.tag == Tag.ZigString and this.value.ZigString.isGloballyAllocated();
}
pub fn ensureHash(this: String) void {
if (this.tag == .WTFStringImpl) this.value.WTFStringImpl.ensureHash();
}
pub fn transferToJS(this: *String, globalThis: *JSC.JSGlobalObject) JSC.JSValue {
const js_value = this.toJS(globalThis);
this.deref();
this.* = dead;
return js_value;
}
pub fn toOwnedSlice(this: String, allocator: std.mem.Allocator) ![]u8 {
const bytes, _ = try this.toOwnedSliceReturningAllASCII(allocator);
return bytes;
}
pub fn toOwnedSliceReturningAllASCII(this: String, allocator: std.mem.Allocator) OOM!struct { []u8, bool } {
switch (this.tag) {
.ZigString => return .{ try this.value.ZigString.toOwnedSlice(allocator), true },
.WTFStringImpl => {
var utf8_slice = this.value.WTFStringImpl.toUTF8WithoutRef(allocator);
if (utf8_slice.allocator.get()) |alloc| {
if (!isWTFAllocator(alloc)) {
return .{ @constCast(utf8_slice.slice()), false };
}
}
return .{ @constCast((try utf8_slice.clone(allocator)).slice()), true };
},
.StaticZigString => return .{ try this.value.StaticZigString.toOwnedSlice(allocator), false },
else => return .{ &[_]u8{}, false },
}
}
pub fn createIfDifferent(other: String, utf8_slice: []const u8) String {
if (other.tag == .WTFStringImpl) {
if (other.eqlUTF8(utf8_slice)) {
return other.dupeRef();
}
}
return createUTF8(utf8_slice);
}
fn createUninitializedLatin1(len: usize) struct { String, []u8 } {
bun.assert(len > 0);
const string = BunString__fromLatin1Unitialized(len);
const wtf = string.value.WTFStringImpl;
return .{
string,
@constCast(wtf.m_ptr.latin1[0..wtf.m_length]),
};
}
fn createUninitializedUTF16(len: usize) struct { String, []u16 } {
bun.assert(len > 0);
const string = BunString__fromUTF16Unitialized(len);
const wtf = string.value.WTFStringImpl;
return .{
string,
@constCast(wtf.m_ptr.utf16[0..wtf.m_length]),
};
}
const WTFStringEncoding = enum {
latin1,
utf16,
pub fn Byte(comptime this: WTFStringEncoding) type {
return switch (this) {
.latin1 => u8,
.utf16 => u16,
};
}
};
/// Allocate memory for a WTF::String of a given length and encoding, and
/// return the string and a mutable slice for that string.
///
/// This is not allowed on zero-length strings, in this case you should
/// check earlier and use String.empty in that case.
///
/// If the length is too large, this will return a dead string.
pub fn createUninitialized(
comptime kind: WTFStringEncoding,
len: usize,
) struct { String, [](kind.Byte()) } {
bun.assert(len > 0);
return switch (comptime kind) {
.latin1 => createUninitializedLatin1(len),
.utf16 => createUninitializedUTF16(len),
};
}
pub fn createLatin1(bytes: []const u8) String {
JSC.markBinding(@src());
if (bytes.len == 0) return String.empty;
return BunString__fromLatin1(bytes.ptr, bytes.len);
}
pub fn createUTF8(bytes: []const u8) String {
JSC.markBinding(@src());
if (bytes.len == 0) return String.empty;
return BunString__fromBytes(bytes.ptr, bytes.len);
}
pub fn createUTF16(bytes: []const u16) String {
if (bytes.len == 0) return String.empty;
if (bun.strings.firstNonASCII16([]const u16, bytes) == null) {
return BunString__fromUTF16ToLatin1(bytes.ptr, bytes.len);
}
return BunString__fromUTF16(bytes.ptr, bytes.len);
}
pub fn createFormat(comptime fmt: [:0]const u8, args: anytype) OOM!String {
if (comptime std.meta.fieldNames(@TypeOf(args)).len == 0) {
return String.static(fmt);
}
var sba = std.heap.stackFallback(16384, bun.default_allocator);
const alloc = sba.get();
const buf = try std.fmt.allocPrint(alloc, fmt, args);
defer alloc.free(buf);
return createUTF8(buf);
}
pub fn createFromOSPath(os_path: bun.OSPathSlice) String {
return switch (@TypeOf(os_path)) {
[]const u8 => createUTF8(os_path),
[]const u16 => createUTF16(os_path),
else => @compileError("unreachable"),
};
}
pub fn isEmpty(this: String) bool {
return this.tag == .Empty or this.length() == 0;
}
pub fn dupeRef(this: String) String {
this.ref();
return this;
}
pub fn clone(this: String) String {
if (this.tag == .WTFStringImpl) {
return this.dupeRef();
}
if (this.isEmpty()) {
return String.empty;
}
if (this.isUTF16()) {
const new, const bytes = createUninitialized(.utf16, this.length());
if (new.tag != .Dead) {
@memcpy(bytes, this.value.ZigString.utf16Slice());
}
return new;
}
return createUTF8(this.byteSlice());
}
extern fn BunString__createAtom(bytes: [*]const u8, len: usize) String;
extern fn BunString__tryCreateAtom(bytes: [*]const u8, len: usize) String;
/// Must be given ascii input
pub fn createAtomASCII(bytes: []const u8) String {
return BunString__createAtom(bytes.ptr, bytes.len);
}
/// Will return null if the input is non-ascii or too long
pub fn tryCreateAtom(bytes: []const u8) ?String {
const atom = BunString__tryCreateAtom(bytes.ptr, bytes.len);
return if (atom.tag == .Dead) null else atom;
}
/// Atomized strings are interned strings
/// They're de-duplicated in a threadlocal hash table
/// They cannot be used from other threads.
pub fn createAtomIfPossible(bytes: []const u8) String {
if (bytes.len < 64) {
if (tryCreateAtom(bytes)) |atom| {
return atom;
}
}
return createUTF8(bytes);
}
pub fn utf8ByteLength(this: String) usize {
return switch (this.tag) {
.WTFStringImpl => this.value.WTFStringImpl.utf8ByteLength(),
.ZigString => this.value.ZigString.utf8ByteLength(),
.StaticZigString => this.value.StaticZigString.utf8ByteLength(),
.Dead, .Empty => 0,
};
}
pub fn utf16ByteLength(this: String) usize {
return switch (this.tag) {
.WTFStringImpl => this.value.WTFStringImpl.utf16ByteLength(),
.StaticZigString, .ZigString => this.value.ZigString.utf16ByteLength(),
.Dead, .Empty => 0,
};
}
pub fn latin1ByteLength(this: String) usize {
return switch (this.tag) {
.WTFStringImpl => this.value.WTFStringImpl.latin1ByteLength(),
.StaticZigString, .ZigString => this.value.ZigString.latin1ByteLength(),
.Dead, .Empty => 0,
};
}
pub fn trunc(this: String, len: usize) String {
if (this.length() <= len) {
return this;
}
return String.init(this.toZigString().trunc(len));
}
pub fn toOwnedSliceZ(this: String, allocator: std.mem.Allocator) ![:0]u8 {
return this.toZigString().toOwnedSliceZ(allocator);
}
/// Create a bun.String from a slice. This is never a copy.
/// For strings created from static string literals, use `String.static`
pub fn init(value: anytype) String {
const Type = @TypeOf(value);
return switch (Type) {
String => value,
ZigString => .{ .tag = .ZigString, .value = .{ .ZigString = value } },
[:0]u8, []u8, [:0]const u8, []const u8 => .{ .tag = .ZigString, .value = .{ .ZigString = ZigString.fromBytes(value) } },
[:0]u16, []u16, [:0]const u16, []const u16 => .{ .tag = .ZigString, .value = .{ .ZigString = ZigString.from16Slice(value) } },
WTFStringImpl => .{ .tag = .WTFStringImpl, .value = .{ .WTFStringImpl = value } },
*const ZigString, *ZigString => .{ .tag = .ZigString, .value = .{ .ZigString = value.* } },
*const [0:0]u8 => .{ .tag = .Empty, .value = .{ .Empty = {} } },
else => {
const info = @typeInfo(Type);
// Zig string literals
if (info == .Pointer and info.Pointer.size == .One and info.Pointer.is_const) {
const child_info = @typeInfo(info.Pointer.child);
if (child_info == .Array and child_info.Array.child == u8) {
if (child_info.Array.len == 0) return String.empty;
return static(value);
}
}
@compileError("Unsupported type for String " ++ @typeName(Type));
},
};
}
pub fn static(input: [:0]const u8) String {
return .{
.tag = .StaticZigString,
.value = .{ .StaticZigString = ZigString.init(input) },
};
}
pub fn toErrorInstance(this: *const String, globalObject: *JSC.JSGlobalObject) JSC.JSValue {
defer this.deref();
return JSC__createError(globalObject, this);
}
pub fn toTypeErrorInstance(this: *const String, globalObject: *JSC.JSGlobalObject) JSC.JSValue {
defer this.deref();
return JSC__createTypeError(globalObject, this);
}
pub fn toRangeErrorInstance(this: *const String, globalObject: *JSC.JSGlobalObject) JSC.JSValue {
defer this.deref();
return JSC__createRangeError(globalObject, this);
}
extern fn BunString__createExternal(
bytes: [*]const u8,
len: usize,
isLatin1: bool,
ptr: ?*anyopaque,
callback: ?*const fn (*anyopaque, *anyopaque, u32) callconv(.C) void,
) String;
extern fn BunString__createStaticExternal(
bytes: [*]const u8,
len: usize,
isLatin1: bool,
) String;
/// ctx is the pointer passed into `createExternal`
/// buffer is the pointer to the buffer, either [*]u8 or [*]u16
/// len is the number of characters in that buffer.
pub const ExternalStringImplFreeFunction = fn (ctx: *anyopaque, buffer: *anyopaque, len: u32) callconv(.C) void;
pub fn createExternal(bytes: []const u8, isLatin1: bool, ctx: *anyopaque, callback: ?*const ExternalStringImplFreeFunction) String {
JSC.markBinding(@src());
bun.assert(bytes.len > 0);
if (bytes.len > max_length()) {
if (callback) |cb| {
cb(ctx, @ptrCast(@constCast(bytes.ptr)), @truncate(bytes.len));
}
return dead;
}
return BunString__createExternal(bytes.ptr, bytes.len, isLatin1, ctx, callback);
}
/// This should rarely be used. The WTF::StringImpl* will never be freed.
///
/// So this really only makes sense when you need to dynamically allocate a
/// string that will never be freed.
pub fn createStaticExternal(bytes: []const u8, isLatin1: bool) String {
JSC.markBinding(@src());
bun.assert(bytes.len > 0);
return BunString__createStaticExternal(bytes.ptr, bytes.len, isLatin1);
}
extern fn BunString__createExternalGloballyAllocatedLatin1(
bytes: [*]u8,
len: usize,
) String;
extern fn BunString__createExternalGloballyAllocatedUTF16(
bytes: [*]u16,
len: usize,
) String;
/// Max WTFStringImpl length.
/// **Not** in bytes. In characters.
pub inline fn max_length() usize {
return JSC.string_allocation_limit;
}
/// If the allocation fails, this will free the bytes and return a dead string.
pub fn createExternalGloballyAllocated(comptime kind: WTFStringEncoding, bytes: []kind.Byte()) String {
JSC.markBinding(@src());
bun.assert(bytes.len > 0);
if (bytes.len > max_length()) {
bun.default_allocator.free(bytes);
return dead;
}
return switch (comptime kind) {
.latin1 => BunString__createExternalGloballyAllocatedLatin1(bytes.ptr, bytes.len),
.utf16 => BunString__createExternalGloballyAllocatedUTF16(bytes.ptr, bytes.len),
};
}
pub fn fromUTF8(value: []const u8) String {
return String.init(ZigString.initUTF8(value));
}
pub fn fromUTF16(value: []const u16) String {
return String.init(ZigString.initUTF16(value));
}
pub fn fromBytes(value: []const u8) String {
return String.init(ZigString.fromBytes(value));
}
pub fn format(self: String, comptime fmt: []const u8, opts: std.fmt.FormatOptions, writer: anytype) !void {
try self.toZigString().format(fmt, opts, writer);
}
/// Deprecated: use `fromJS2` to handle errors explicitly
pub fn fromJS(value: bun.JSC.JSValue, globalObject: *JSC.JSGlobalObject) String {
JSC.markBinding(@src());
var out: String = String.dead;
if (BunString__fromJS(globalObject, value, &out)) {
return out;
} else {
return String.dead;
}
}
pub fn fromJS2(value: bun.JSC.JSValue, globalObject: *JSC.JSGlobalObject) bun.JSError!String {
var out: String = String.dead;
if (BunString__fromJS(globalObject, value, &out)) {
if (comptime bun.Environment.isDebug) {
bun.assert(out.tag != .Dead);
}
return out;
} else {
if (comptime bun.Environment.isDebug) {
bun.assert(globalObject.hasException());
}
return error.JSError;
}
}
pub fn fromJSRef(value: bun.JSC.JSValue, globalObject: *JSC.JSGlobalObject) bun.JSError!String {
JSC.markBinding(@src());
var out: String = String.dead;
if (BunString__fromJSRef(globalObject, value, &out)) {
return out;
} else {
if (comptime bun.Environment.isDebug) {
bun.assert(globalObject.hasException());
}
return error.JSError;
}
}
pub fn tryFromJS(value: bun.JSC.JSValue, globalObject: *JSC.JSGlobalObject) ?String {
JSC.markBinding(@src());
var out: String = String.dead;
if (BunString__fromJS(globalObject, value, &out)) {
return out;
} else {
return null; //TODO: return error.JSError
}
}
pub fn toJS(this: *const String, globalObject: *bun.JSC.JSGlobalObject) JSC.JSValue {
JSC.markBinding(@src());
return BunString__toJS(globalObject, this);
}
pub fn toJSDOMURL(this: *String, globalObject: *bun.JSC.JSGlobalObject) JSC.JSValue {
JSC.markBinding(@src());
return BunString__toJSDOMURL(globalObject, this);
}
extern fn BunString__createArray(
globalObject: *bun.JSC.JSGlobalObject,
ptr: [*]const String,
len: usize,
) JSC.JSValue;
/// calls toJS on all elements of `array`.
pub fn toJSArray(globalObject: *bun.JSC.JSGlobalObject, array: []const bun.String) JSC.JSValue {
JSC.markBinding(@src());
return BunString__createArray(globalObject, array.ptr, array.len);
}
pub fn toZigString(this: String) ZigString {
if (this.tag == .StaticZigString or this.tag == .ZigString) {
return this.value.ZigString;
}
if (this.tag == .WTFStringImpl)
return this.value.WTFStringImpl.toZigString();
return ZigString.Empty;
}
pub fn toWTF(this: *String) void {
JSC.markBinding(@src());
BunString__toWTFString(this);
}
pub inline fn length(this: String) usize {
return if (this.tag == .WTFStringImpl)
this.value.WTFStringImpl.length()
else
this.toZigString().length();
}
pub inline fn utf16(self: String) []const u16 {
if (self.tag == .Empty)
return &[_]u16{};
if (self.tag == .WTFStringImpl) {
return self.value.WTFStringImpl.utf16Slice();
}
return self.toZigString().utf16SliceAligned();
}
pub inline fn latin1(self: String) []const u8 {
if (self.tag == .Empty)
return &[_]u8{};
if (self.tag == .WTFStringImpl) {
return self.value.WTFStringImpl.latin1Slice();
}
return self.toZigString().slice();
}
pub fn isUTF8(self: String) bool {
if (!(self.tag == .ZigString or self.tag == .StaticZigString))
return false;
return self.value.ZigString.isUTF8();
}
pub inline fn asUTF8(self: String) ?[]const u8 {
if (self.tag == .WTFStringImpl) {
if (self.value.WTFStringImpl.is8Bit() and bun.strings.isAllASCII(self.value.WTFStringImpl.latin1Slice())) {
return self.value.WTFStringImpl.latin1Slice();
}
return null;
}
if (self.tag == .ZigString or self.tag == .StaticZigString) {
if (self.value.ZigString.isUTF8()) {
return self.value.ZigString.slice();
}
if (bun.strings.isAllASCII(self.toZigString().slice())) {
return self.value.ZigString.slice();
}
return null;
}
return "";
}
pub fn encoding(self: String) bun.strings.EncodingNonAscii {
if (self.isUTF16()) {
return .utf16;
}
if (self.isUTF8()) {
return .utf8;
}
return .latin1;
}
pub fn githubAction(self: String) ZigString.GithubActionFormatter {
return self.toZigString().githubAction();
}
pub fn byteSlice(this: String) []const u8 {
return switch (this.tag) {
.ZigString, .StaticZigString => this.value.ZigString.byteSlice(),
.WTFStringImpl => this.value.WTFStringImpl.byteSlice(),
else => &[_]u8{},
};
}
pub fn isUTF16(self: String) bool {
if (self.tag == .WTFStringImpl)
return !self.value.WTFStringImpl.is8Bit();
if (self.tag == .ZigString or self.tag == .StaticZigString)
return self.value.ZigString.is16Bit();
return false;
}
extern fn BunString__toJSON(
globalObject: *bun.JSC.JSGlobalObject,
this: *String,
) JSC.JSValue;
pub fn toJSByParseJSON(self: *String, globalObject: *JSC.JSGlobalObject) JSC.JSValue {
JSC.markBinding(@src());
return BunString__toJSON(globalObject, self);
}
pub fn encodeInto(self: String, out: []u8, comptime enc: JSC.Node.Encoding) !usize {
if (self.isUTF16()) {
return JSC.WebCore.Encoder.encodeIntoFrom16(self.utf16(), out, enc, true);
}
if (self.isUTF8()) {
@panic("TODO");
}
return JSC.WebCore.Encoder.encodeIntoFrom8(self.latin1(), out, enc);
}
pub fn encode(self: String, enc: JSC.Node.Encoding) []u8 {
return self.toZigString().encodeWithAllocator(bun.default_allocator, enc);
}
pub inline fn utf8(self: String) []const u8 {
if (comptime bun.Environment.allow_assert) {
bun.assert(self.tag == .ZigString or self.tag == .StaticZigString);
bun.assert(self.canBeUTF8());
}
return self.value.ZigString.slice();
}
pub fn canBeUTF8(self: String) bool {
if (self.tag == .WTFStringImpl)
return self.value.WTFStringImpl.is8Bit() and bun.strings.isAllASCII(self.value.WTFStringImpl.latin1Slice());
if (self.tag == .ZigString or self.tag == .StaticZigString) {
if (self.value.ZigString.isUTF8()) {
return true;
}
return bun.strings.isAllASCII(self.toZigString().slice());
}
return self.tag == .Empty;
}
pub fn substring(this: String, start_index: usize) String {
const len = this.length();
return this.substringWithLen(@min(len, start_index), len);
}
pub fn substringWithLen(this: String, start_index: usize, end_index: usize) String {
switch (this.tag) {
.ZigString, .StaticZigString => {
return String.init(this.value.ZigString.substringWithLen(start_index, end_index));
},
.WTFStringImpl => {
if (this.value.WTFStringImpl.is8Bit()) {
return String.init(ZigString.init(this.value.WTFStringImpl.latin1Slice()[start_index..end_index]));
} else {
return String.init(ZigString.initUTF16(this.value.WTFStringImpl.utf16Slice()[start_index..end_index]));
}
},
else => return this,
}
}
pub fn toUTF8(this: String, allocator: std.mem.Allocator) ZigString.Slice {
if (this.tag == .WTFStringImpl) {
return this.value.WTFStringImpl.toUTF8(allocator);
}
if (this.tag == .ZigString) {
return this.value.ZigString.toSlice(allocator);
}
if (this.tag == .StaticZigString) {
return ZigString.Slice.fromUTF8NeverFree(this.value.StaticZigString.slice());
}
return ZigString.Slice.empty;
}
/// This is the same as toUTF8, but it doesn't increment the reference count for latin1 strings
pub fn toUTF8WithoutRef(this: String, allocator: std.mem.Allocator) ZigString.Slice {
if (this.tag == .WTFStringImpl) {
return this.value.WTFStringImpl.toUTF8WithoutRef(allocator);
}
if (this.tag == .ZigString) {
return this.value.ZigString.toSlice(allocator);
}
if (this.tag == .StaticZigString) {
return ZigString.Slice.fromUTF8NeverFree(this.value.StaticZigString.slice());
}
return ZigString.Slice.empty;
}
pub fn toSlice(this: String, allocator: std.mem.Allocator) SliceWithUnderlyingString {
return SliceWithUnderlyingString{
.utf8 = this.toUTF8(allocator),
.underlying = this,
};
}
pub fn toThreadSafeSlice(this: *String, allocator: std.mem.Allocator) SliceWithUnderlyingString {
if (this.tag == .WTFStringImpl) {
if (!this.value.WTFStringImpl.isThreadSafe()) {
const slice = this.value.WTFStringImpl.toUTF8WithoutRef(allocator);
if (slice.allocator.isNull()) {
// this was a WTF-allocated string
// We're going to need to clone it across the threads
// so let's just do that now instead of creating another copy.
return .{