forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_mutable.zig
451 lines (370 loc) · 15.2 KB
/
string_mutable.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
const std = @import("std");
const expect = std.testing.expect;
const bun = @import("root").bun;
const strings = bun.strings;
const js_lexer = bun.js_lexer;
const string = bun.string;
const stringZ = bun.stringZ;
const CodePoint = bun.CodePoint;
const OOM = bun.OOM;
pub const MutableString = struct {
allocator: std.mem.Allocator,
list: std.ArrayListUnmanaged(u8),
pub fn init2048(allocator: std.mem.Allocator) std.mem.Allocator.Error!MutableString {
return MutableString.init(allocator, 2048);
}
pub const Writer = std.io.Writer(*@This(), OOM, MutableString.writeAll);
pub fn writer(self: *MutableString) Writer {
return Writer{
.context = self,
};
}
pub fn isEmpty(this: *const MutableString) bool {
return this.list.items.len == 0;
}
pub fn deinit(str: *MutableString) void {
if (str.list.capacity > 0) {
str.list.expandToCapacity();
str.list.clearAndFree(str.allocator);
}
}
pub fn owns(this: *const MutableString, items: []const u8) bool {
return bun.isSliceInBuffer(items, this.list.items.ptr[0..this.list.capacity]);
}
pub fn growIfNeeded(self: *MutableString, amount: usize) OOM!void {
try self.list.ensureUnusedCapacity(self.allocator, amount);
}
pub fn write(self: *MutableString, bytes: anytype) OOM!usize {
bun.debugAssert(bytes.len == 0 or !bun.isSliceInBuffer(bytes, self.list.allocatedSlice()));
try self.list.appendSlice(self.allocator, bytes);
return bytes.len;
}
pub fn bufferedWriter(self: *MutableString) BufferedWriter {
return BufferedWriter{ .context = self };
}
pub fn init(allocator: std.mem.Allocator, capacity: usize) OOM!MutableString {
return MutableString{ .allocator = allocator, .list = if (capacity > 0)
try std.ArrayListUnmanaged(u8).initCapacity(allocator, capacity)
else
std.ArrayListUnmanaged(u8){} };
}
pub fn initEmpty(allocator: std.mem.Allocator) MutableString {
return MutableString{ .allocator = allocator, .list = .{} };
}
pub const ensureUnusedCapacity = growIfNeeded;
pub fn initCopy(allocator: std.mem.Allocator, str: anytype) OOM!MutableString {
var mutable = try MutableString.init(allocator, str.len);
try mutable.copy(str);
return mutable;
}
/// Convert it to an ASCII identifier. Note: If you change this to a non-ASCII
/// identifier, you're going to potentially cause trouble with non-BMP code
/// points in target environments that don't support bracketed Unicode escapes.
pub fn ensureValidIdentifier(str: string, allocator: std.mem.Allocator) !string {
if (str.len == 0) {
return "_";
}
var iterator = strings.CodepointIterator.init(str);
var cursor = strings.CodepointIterator.Cursor{};
var has_needed_gap = false;
var needs_gap = false;
var start_i: usize = 0;
if (!iterator.next(&cursor)) return "_";
const JSLexerTables = @import("./js_lexer_tables.zig");
// 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) {
return JSLexerTables.StrictModeReservedWordsRemap.get(str) orelse str;
}
if (needs_gap) {
var mutable = try MutableString.initCopy(allocator, if (start_i == 0)
// the first letter can be a non-identifier start
// https://github.com/oven-sh/bun/issues/2946
"_"
else
str[0..start_i]);
needs_gap = false;
var items = str[start_i..];
iterator = strings.CodepointIterator.init(items);
cursor = strings.CodepointIterator.Cursor{};
while (iterator.next(&cursor)) {
if (js_lexer.isIdentifierContinue(cursor.c) and cursor.width == 1) {
if (needs_gap) {
try mutable.appendChar('_');
needs_gap = false;
has_needed_gap = true;
}
try mutable.append(items[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 mutable.appendChar('_');
needs_gap = false;
has_needed_gap = true;
}
if (comptime bun.Environment.allow_assert) {
bun.assert(js_lexer.isIdentifier(mutable.list.items));
}
return try mutable.list.toOwnedSlice(allocator);
}
return str;
}
pub fn len(self: *const MutableString) usize {
return self.list.items.len;
}
pub fn copy(self: *MutableString, str: anytype) !void {
try self.list.ensureTotalCapacity(self.allocator, str[0..].len);
if (self.list.items.len == 0) {
try self.list.insertSlice(self.allocator, 0, str);
} else {
try self.list.replaceRange(self.allocator, 0, str[0..].len, str[0..]);
}
}
pub inline fn growBy(self: *MutableString, amount: usize) !void {
try self.list.ensureUnusedCapacity(self.allocator, amount);
}
pub inline fn appendSlice(self: *MutableString, items: []const u8) !void {
try self.list.appendSlice(self.allocator, items);
}
pub inline fn appendSliceExact(self: *MutableString, items: []const u8) !void {
if (items.len == 0) return;
try self.list.ensureTotalCapacityPrecise(self.allocator, self.list.items.len + items.len);
var end = self.list.items.ptr + self.list.items.len;
self.list.items.len += items.len;
@memcpy(end[0..items.len], items);
}
pub inline fn reset(
self: *MutableString,
) void {
self.list.clearRetainingCapacity();
}
pub inline fn resetTo(
self: *MutableString,
index: usize,
) void {
bun.assert(index <= self.list.capacity);
self.list.items.len = index;
}
pub fn inflate(self: *MutableString, amount: usize) !void {
try self.list.resize(self.allocator, amount);
}
pub inline fn appendCharNTimes(self: *MutableString, char: u8, n: usize) !void {
try self.list.appendNTimes(self.allocator, char, n);
}
pub inline fn appendChar(self: *MutableString, char: u8) !void {
try self.list.append(self.allocator, char);
}
pub inline fn appendCharAssumeCapacity(self: *MutableString, char: u8) void {
self.list.appendAssumeCapacity(char);
}
pub inline fn append(self: *MutableString, char: []const u8) !void {
try self.list.appendSlice(self.allocator, char);
}
pub inline fn appendInt(self: *MutableString, int: u64) !void {
const count = bun.fmt.fastDigitCount(int);
try self.list.ensureUnusedCapacity(self.allocator, count);
const old = self.list.items.len;
self.list.items.len += count;
bun.assert(count == bun.fmt.formatIntBuf(self.list.items.ptr[old .. old + count], int, 10, .lower, .{}));
}
pub inline fn appendAssumeCapacity(self: *MutableString, char: []const u8) void {
self.list.appendSliceAssumeCapacity(
char,
);
}
pub inline fn lenI(self: *MutableString) i32 {
return @as(i32, @intCast(self.list.items.len));
}
pub fn toOwnedSlice(self: *MutableString) string {
return self.list.toOwnedSlice(self.allocator) catch bun.outOfMemory(); // TODO
}
pub fn slice(self: *MutableString) []u8 {
return self.list.items;
}
/// Clear the existing value without freeing the memory or shrinking the capacity.
pub fn move(self: *MutableString) []u8 {
const out = self.list.items;
self.list = .{};
return out;
}
/// Appends `0` if needed
pub fn sliceWithSentinel(self: *MutableString) [:0]u8 {
if (self.list.items.len > 0 and self.list.items[self.list.items.len - 1] != 0) {
self.list.append(
self.allocator,
0,
) catch unreachable;
}
return self.list.items[0 .. self.list.items.len - 1 :0];
}
pub fn toOwnedSliceLength(self: *MutableString, length: usize) string {
self.list.shrinkAndFree(self.allocator, length);
return self.list.toOwnedSlice(self.allocator) catch bun.outOfMemory(); // TODO
}
pub fn containsChar(self: *const MutableString, char: u8) bool {
return self.indexOfChar(char) != null;
}
pub fn indexOfChar(self: *const MutableString, char: u8) ?u32 {
return strings.indexOfChar(self.list.items, char);
}
pub fn lastIndexOfChar(self: *const MutableString, char: u8) ?usize {
return strings.lastIndexOfChar(self.list.items, char);
}
pub fn lastIndexOf(self: *const MutableString, str: u8) ?usize {
return strings.lastIndexOfChar(self.list.items, str);
}
pub fn indexOf(self: *const MutableString, str: u8) ?usize {
return std.mem.indexOf(u8, self.list.items, str);
}
pub fn eql(self: *MutableString, other: anytype) bool {
return std.mem.eql(u8, self.list.items, other);
}
pub fn toSocketBuffers(self: *MutableString, comptime count: usize, ranges: anytype) [count]std.posix.iovec_const {
var buffers: [count]std.posix.iovec_const = undefined;
inline for (&buffers, ranges) |*b, r| {
b.* = .{
.iov_base = self.list.items[r[0]..r[1]].ptr,
.iov_len = self.list.items[r[0]..r[1]].len,
};
}
return buffers;
}
pub const BufferedWriter = struct {
context: *MutableString,
buffer: [max]u8 = undefined,
pos: usize = 0,
const max = 2048;
pub const Writer = std.io.Writer(*BufferedWriter, anyerror, BufferedWriter.writeAll);
inline fn remain(this: *BufferedWriter) []u8 {
return this.buffer[this.pos..];
}
pub fn flush(this: *BufferedWriter) !void {
_ = try this.context.writeAll(this.buffer[0..this.pos]);
this.pos = 0;
}
pub fn writeAll(this: *BufferedWriter, bytes: []const u8) anyerror!usize {
const pending = bytes;
if (pending.len >= max) {
try this.flush();
try this.context.append(pending);
return pending.len;
}
if (pending.len > 0) {
if (pending.len + this.pos > max) {
try this.flush();
}
@memcpy(this.remain()[0..pending.len], pending);
this.pos += pending.len;
}
return pending.len;
}
const E = bun.JSAst.E;
/// Write a E.String to the buffer.
/// This automatically encodes UTF-16 into UTF-8 using
/// the same code path as TextEncoder
pub fn writeString(this: *BufferedWriter, bytes: *E.String) anyerror!usize {
if (bytes.isUTF8()) {
return try this.writeAll(bytes.slice(this.context.allocator));
}
return try this.writeAll16(bytes.slice16());
}
/// Write a UTF-16 string to the (UTF-8) buffer
/// This automatically encodes UTF-16 into UTF-8 using
/// the same code path as TextEncoder
pub fn writeAll16(this: *BufferedWriter, bytes: []const u16) anyerror!usize {
const pending = bytes;
if (pending.len >= max) {
try this.flush();
try this.context.list.ensureUnusedCapacity(this.context.allocator, bytes.len * 2);
const decoded = strings.copyUTF16IntoUTF8(
this.remain()[0 .. bytes.len * 2],
[]const u16,
bytes,
true,
);
this.context.list.items.len += @as(usize, decoded.written);
return pending.len;
}
if (pending.len > 0) {
if ((pending.len * 2) + this.pos > max) {
try this.flush();
}
const decoded = strings.copyUTF16IntoUTF8(
this.remain()[0 .. bytes.len * 2],
[]const u16,
bytes,
true,
);
this.pos += @as(usize, decoded.written);
}
return pending.len;
}
pub fn writeHTMLAttributeValueString(this: *BufferedWriter, str: *E.String) anyerror!void {
if (str.isUTF8()) {
try this.writeHTMLAttributeValue(str.slice(this.context.allocator));
return;
}
try this.writeHTMLAttributeValue16(str.slice16());
}
pub fn writeHTMLAttributeValue(this: *BufferedWriter, bytes: []const u8) anyerror!void {
var items = bytes;
while (items.len > 0) {
// TODO: SIMD
if (strings.indexOfAny(items, "\"<>")) |j| {
_ = try this.writeAll(items[0..j]);
_ = switch (items[j]) {
'"' => try this.writeAll("""),
'<' => try this.writeAll("<"),
'>' => try this.writeAll(">"),
else => unreachable,
};
items = items[j + 1 ..];
continue;
}
_ = try this.writeAll(items);
break;
}
}
pub fn writeHTMLAttributeValue16(this: *BufferedWriter, bytes: []const u16) anyerror!void {
var items = bytes;
while (items.len > 0) {
if (strings.indexOfAny16(items, "\"<>")) |j| {
// this won't handle strings larger than 4 GB
// that's fine though, 4 GB of SSR'd HTML is quite a lot...
_ = try this.writeAll16(items[0..j]);
_ = switch (items[j]) {
'"' => try this.writeAll("""),
'<' => try this.writeAll("<"),
'>' => try this.writeAll(">"),
else => unreachable,
};
items = items[j + 1 ..];
continue;
}
_ = try this.writeAll16(items);
break;
}
}
pub fn writer(this: *BufferedWriter) BufferedWriter.Writer {
return BufferedWriter.Writer{ .context = this };
}
};
pub fn writeAll(self: *MutableString, bytes: string) OOM!usize {
try self.list.appendSlice(self.allocator, bytes);
return bytes.len;
}
};