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
//! `VecExt` / `ByteVecExt` — Zig-ported method vocabulary on `Vec<T>`.
//!
//! Migration shim from the deleted `BabyList<T>` (see
//! `docs/BABYLIST_REPLACEMENT.md`): every former `BabyList<T>` site is now a
//! plain `Vec<T>`, and these traits supply the Zig method names (`.slice()`,
//! `.append()`, `.init_capacity()`, …) so call sites needed only a type-level
//! rewrite. `Vec` aborts on OOM, so these methods are infallible and return
//! `T` / `()` directly (the original `Result<_, AllocError>` shim has been
//! removed — `?`/`handle_oom` at call sites is no longer needed).
//!
//! NOTE: `.first()`/`.last()`/`.insert()`/`.contains()`/`.clone()` are
//! intentionally *not* provided — they collide with `Vec`/slice inherent
//! methods whose return types differ. Call sites that relied on the old
//! variants are patched at the call site to `.first_mut()` / `.to_vec()` etc.
#[cfg(bao_nightly)]
extern crate alloc;
use bun_alloc::core_alloc::Allocator;
use core::fmt;
use core::mem::ManuallyDrop;
use bun_alloc::AllocError;
use bun_core::strings;
pub trait VecExt<T>: Sized {
// ── constructors ──────────────────────────────────────────────────────
fn init_capacity(n: usize) -> Self;
fn init_one(value: T) -> Self;
fn from_slice(items: &[T]) -> Self
where
T: Clone;
fn move_from_list(list: Vec<T>) -> Self;
fn from_owned_slice(items: Box<[T]>) -> Self;
fn init_with_buffer_vec(buffer: Vec<T>) -> Self;
/// Arena-builder → owned `Vec<T>`. In Zig this was zero-copy (arena ptr
/// adopted as `Borrowed`); in the Rust port the linker always called
/// `transfer_ownership` afterwards (full copy), so doing the copy up-front
/// here is no worse and lets the arena round-trip disappear.
///
/// # Safety
/// Bitwise-**moves** every element out of `items` into a fresh allocation.
/// `items` must be a leaked bump-arena slice (`into_bump_slice_mut` /
/// `alloc_slice_*`) that will *never* have its elements read or dropped
/// again — i.e. no live `Vec<T>`/`BumpVec<T>` may still own them. Passing
/// a slice borrowed from a container that runs element destructors yields
/// a double-drop (PTR_AUDIT.md class #1: bitwise-copy of Drop-carrying
/// type while source is still live).
unsafe fn from_bump_slice(items: &mut [T]) -> Self;
/// Safe sibling of [`from_bump_slice`] for `T: Copy` — the
/// "source must never be element-dropped again" precondition holds
/// vacuously (`Copy` ⇒ no `Drop`), so the bitwise move degenerates to a
/// plain copy and needs no `unsafe` at the call site. Takes `&[T]`
/// (read-only) since nothing is logically moved out.
///
/// Covers the dominant js_parser pattern
/// `arena.alloc_slice_copy(&[a, b]) → unsafe { from_bump_slice(..) }`
/// (invariant: bump arena outlives the AST). Callers may pass the bump
/// slice directly, or skip the intermediate bump alloc entirely and pass
/// the stack array — both compile to one memcpy into the global heap.
fn from_arena_slice(items: &[T]) -> Self
where
T: Copy;
/// Safe sibling of [`from_bump_slice`]: consumes an `ArenaVec` (sole owner
/// of its elements + arena buffer), bitwise-moves every element into a
/// fresh global-allocator `Vec<T>`, and leaks the now-logically-empty
/// arena buffer back to the bump (reclaimed on arena reset, which never
/// runs element destructors). Ownership of every `T` transfers exactly
/// once, so no double-drop and no allocator-identity confusion is
/// possible at the call site.
///
/// Prefer this over `unsafe { from_bump_slice(v.into_bump_slice_mut()) }`
/// — it encodes the "source is leaked, never dropped again" contract in
/// the type system instead of a `// SAFETY:` comment.
fn from_bump_vec(v: bun_alloc::ArenaVec<'_, T>) -> Self;
/// Arena pre-reservation: `Vec` cannot allocate from a bump arena, so this
/// becomes a global-allocator `with_capacity`. The arena is ignored.
fn init_capacity_in(_arena: &bun_alloc::Arena, cap: usize) -> Self;
/// Wrap a borrowed slice as a `Vec<T>` that **must not be dropped or
/// grown**. Same hazard as the original — callers wrap in `ManuallyDrop`.
/// Kept only for the `StreamResult::Temporary*` pattern; new code should
/// take `&[T]` instead.
unsafe fn from_borrowed_slice_dangerous(items: &[T]) -> ManuallyDrop<Self>;
// ── accessors ─────────────────────────────────────────────────────────
fn slice(&self) -> &[T];
fn slice_mut(&mut self) -> &mut [T];
fn slice_const(&self) -> &[T];
fn at(&self, index: usize) -> &T;
fn mut_(&mut self, index: usize) -> &mut T;
/// `.len` field access (old struct stored a `u32`); kept for sites that did
/// arithmetic on the raw `u32`.
fn len_u32(&self) -> u32;
fn cap_u32(&self) -> u32;
// ── mutation ──────────────────────────────────────────────────────────
fn append(&mut self, value: T);
fn append_assume_capacity(&mut self, value: T);
fn append_slice(&mut self, vals: &[T])
where
T: Clone;
fn append_slice_assume_capacity(&mut self, vals: &[T])
where
T: Copy;
fn ensure_total_capacity(&mut self, n: usize);
fn ensure_total_capacity_precise(&mut self, n: usize);
fn ensure_unused_capacity(&mut self, n: usize);
fn shrink_retaining_capacity(&mut self, new_len: usize);
fn shrink_and_free(&mut self, new_len: usize);
fn clear_retaining_capacity(&mut self);
fn clear_and_free(&mut self);
/// Drop the first `n` elements in place via `copy_within(n.., 0)` +
/// `truncate` (capacity retained). `n == 0` is a no-op; `n >= len`
/// degenerates to `clear()`. See [`bun_core::vec::drain_front`].
fn drain_front(&mut self, n: usize)
where
T: Copy;
fn ordered_remove(&mut self, index: usize) -> T;
fn insert_slice(&mut self, index: usize, vals: &[T])
where
T: Clone;
fn replace_range(&mut self, start: usize, len: usize, new_items: &[T])
where
T: Clone;
/// # Safety
/// Exposes `self[len..capacity]` as initialized. Every element must be
/// overwritten before any read (including Drop). Prefer
/// [`unused_capacity_slice`] for `T` with validity invariants.
unsafe fn expand_to_capacity(&mut self);
/// # Safety
/// Returns `&mut [T]` over `additional` uninitialized elements. Caller
/// must fully initialize the slice before any read/drop. Prefer
/// [`unused_capacity_slice`] + `set_len` for non-POD `T`.
unsafe fn writable_slice(&mut self, additional: usize) -> &mut [T];
/// # Safety
/// As [`writable_slice`] but skips `reserve`; caller must guarantee
/// `len + additional <= capacity` (debug-asserted). Zig:
/// `ArrayList.addManyAsSliceAssumeCapacity`.
unsafe fn writable_slice_assume_capacity(&mut self, additional: usize) -> &mut [T];
/// # Safety
/// As [`writable_slice`] but uses `reserve_exact` so the allocation grows
/// to *exactly* `len + additional`. Use when the buffer is the final
/// single-shot blob (sourcemap finalize, etc.).
unsafe fn writable_slice_exact(&mut self, additional: usize) -> &mut [T];
/// Reserves `additional` and returns the first `additional` slots of
/// spare capacity as `MaybeUninit<T>`. Safe sibling of [`writable_slice`]:
/// caller writes some prefix then calls `set_len` (or [`uv_commit`] for
/// `Vec<u8>`) to commit. Unlike `spare_capacity_mut()` the returned slice
/// is exactly `additional` long, not `capacity - len`.
fn reserve_spare(&mut self, additional: usize) -> &mut [core::mem::MaybeUninit<T>];
/// `reserve(additional)` then [`expand_to_capacity`], returning the
/// freshly-exposed tail as a raw `(ptr, len)` pair — i.e.
/// `(next_out, avail_out)` for C streaming APIs (zlib, brotli, zstd).
/// Unlike [`writable_slice`] this exposes the *full* over-allocated
/// capacity (`cap - prev_len`), not exactly `additional`, so the FFI
/// callee can use the allocator's slack. Pass `additional = 0` when the
/// caller has already reserved.
///
/// # Safety
/// Same as [`expand_to_capacity`]: every byte in `[prev_len, cap)` must be
/// written by the FFI callee (or `len` truncated back) before any read.
unsafe fn reserve_expand_tail(&mut self, additional: usize) -> (*mut T, usize);
// ── ownership transfer ────────────────────────────────────────────────
fn move_to_list(&mut self) -> Vec<T>;
fn move_to_list_managed(&mut self) -> Vec<T>;
fn to_owned_slice(&mut self) -> Box<[T]>;
/// No-op for `Vec` — already globally owned. Kept so cat-4 call sites
/// (`LinkerGraph::load`) compile during incremental migration; delete once
/// all callers are gone.
#[inline]
fn transfer_ownership(&mut self) {}
/// Non-owning header alias. For `Vec` this is `from_raw_parts` into a
/// `ManuallyDrop` — same UB-if-dropped contract as before.
fn shallow_copy(&self) -> ManuallyDrop<Self>;
fn shallow_clone(&self) -> ManuallyDrop<Self>;
// ── misc ──────────────────────────────────────────────────────────────
fn unused_capacity_slice(&mut self) -> &mut [core::mem::MaybeUninit<T>];
fn allocated_slice(&mut self) -> &mut [core::mem::MaybeUninit<T>];
fn memory_cost(&self) -> usize;
fn sort_asc(&mut self)
where
T: AsRef<[u8]>;
fn sort(&mut self, less_than: impl FnMut(&T, &T) -> bool);
fn deep_clone_with<F>(&self, clone_one: F) -> Self
where
F: FnMut(&T) -> T;
fn try_deep_clone_with<F, E>(&self, clone_one: F) -> Result<Self, E>
where
F: FnMut(&T) -> Result<T, E>,
E: From<AllocError>;
}
// Generic over `A` so the impl serves both `Vec<T>` (Global) and
// `Vec<T, AstAlloc>` (AST-arena lists — `ExprNodeList`/`DeclList`/
// `PropertyList`). `A: Default` lets every constructor produce the right
// allocator without a value in hand; both `Global` and `AstAlloc` are ZSTs
// with `Default`, so `A::default()` is free.
// Dual-mode stamp: the same impl body serves core's `Vec<T, A>` on
// nightly (byte-identical) and the allocator_api2 mirror on stable —
// this is the orphan-rule key that unlocks AstVec/arena-Vec consumers
// (W1: ast/css/sourcemap) on the stable channel.
//
// Construction shim: the body below builds vecs through `VecExtCtor` so the
// SAME items compile for allocator-parameterized targets (nightly std
// `Vec<T, A>`, stable api2 `Vec<T, A>`) AND for the plain Global std
// `Vec<T>` that stable Rust offers (its `with_capacity_in` /
// `from_raw_parts_in` / `new_in` are nightly-only, so the Global std vec
// gets its own `VecExt` imprint on stable — without it every downstream
// std `Vec<u8>` buffer loses `.slice()`/`.memory_cost()`/… on stable).
pub(crate) trait VecExtCtor<T>: Sized {
/// `true` when this vec's allocator is the process-global one — then
/// raw-parts adoption of a plain `Vec<T>` buffer is a pointer move.
fn vecext_is_global() -> bool;
fn vecext_with_capacity(n: usize) -> Self;
fn vecext_new_empty() -> Self;
/// # Safety
/// Same contract as `Vec::from_raw_parts`: `ptr` must point to a buffer
/// this vec's allocator owns (or a Global buffer when
/// [`VecExtCtor::vecext_is_global`]), with `len` initialized elements and
/// `cap` capacity; ownership transfers to the returned vec.
unsafe fn vecext_from_raw_parts(ptr: *mut T, len: usize, cap: usize) -> Self;
}
#[cfg(bao_nightly)]
impl<T, A: core::alloc::Allocator + Default + 'static> VecExtCtor<T> for alloc::vec::Vec<T, A> {
#[inline]
fn vecext_is_global() -> bool {
core::any::TypeId::of::<A>() == core::any::TypeId::of::<std::alloc::Global>()
}
#[inline]
fn vecext_with_capacity(n: usize) -> Self {
Self::with_capacity_in(n, A::default())
}
#[inline]
fn vecext_new_empty() -> Self {
Self::new_in(A::default())
}
#[inline]
unsafe fn vecext_from_raw_parts(ptr: *mut T, len: usize, cap: usize) -> Self {
// SAFETY: caller contract on the trait method.
unsafe { Self::from_raw_parts_in(ptr, len, cap, A::default()) }
}
}
#[cfg(not(bao_nightly))]
impl<T, A: allocator_api2::alloc::Allocator + Default + 'static> VecExtCtor<T>
for allocator_api2::vec::Vec<T, A>
{
#[inline]
fn vecext_is_global() -> bool {
core::any::TypeId::of::<A>() == core::any::TypeId::of::<allocator_api2::alloc::Global>()
}
#[inline]
fn vecext_with_capacity(n: usize) -> Self {
Self::with_capacity_in(n, A::default())
}
#[inline]
fn vecext_new_empty() -> Self {
Self::new_in(A::default())
}
#[inline]
unsafe fn vecext_from_raw_parts(ptr: *mut T, len: usize, cap: usize) -> Self {
// SAFETY: caller contract on the trait method.
unsafe { Self::from_raw_parts_in(ptr, len, cap, A::default()) }
}
}
/// The Global std `Vec<T>` imprint — stable channel only. On nightly the
/// blanket parametric impl above already covers it (`Vec<T>` is
/// `Vec<T, Global>`); on stable std's allocator-parameteric Vec is not
/// nameable, so it gets this dedicated Global ctor set.
#[cfg(not(bao_nightly))]
impl<T> VecExtCtor<T> for ::std::vec::Vec<T> {
#[inline]
fn vecext_is_global() -> bool {
true
}
#[inline]
fn vecext_with_capacity(n: usize) -> Self {
Self::with_capacity(n)
}
#[inline]
fn vecext_new_empty() -> Self {
Self::new()
}
#[inline]
unsafe fn vecext_from_raw_parts(ptr: *mut T, len: usize, cap: usize) -> Self {
// SAFETY: caller contract on the trait method.
unsafe { Self::from_raw_parts(ptr, len, cap) }
}
}
macro_rules! impl_vec_ext_for_channel {
(@body) => {
#[inline]
fn init_capacity(n: usize) -> Self {
Self::vecext_with_capacity(n)
}
#[inline]
fn init_one(value: T) -> Self {
let mut v = Self::vecext_with_capacity(1);
v.push(value);
v
}
#[inline]
fn from_slice(items: &[T]) -> Self
where
T: Clone,
{
let mut v = Self::vecext_with_capacity(items.len());
v.extend_from_slice(items);
v
}
#[inline]
fn move_from_list(list: Vec<T>) -> Self {
// Mirror of the `move_to_list` fast-path: when `A == Global` this is a
// pointer adopt (Zig `moveFromList`, baby_list.zig:46), not a realloc.
// Hot Global callers: `FileReader`, `ByteStream`, `shell::Cmd`.
if Self::vecext_is_global() {
let mut list = core::mem::ManuallyDrop::new(list);
// SAFETY: `A == Global`, so `Vec<T>` and `Vec<T, A>` have identical
// layout, allocator, and drop semantics.
return unsafe {
Self::vecext_from_raw_parts(list.as_mut_ptr(), list.len(), list.capacity())
};
}
let mut v = Self::vecext_with_capacity(list.len());
v.extend(list);
v
}
#[inline]
fn from_owned_slice(items: Box<[T]>) -> Self {
Self::move_from_list(items.into_vec())
}
#[inline]
fn init_with_buffer_vec(buffer: Vec<T>) -> Self {
Self::move_from_list(buffer)
}
#[inline]
unsafe fn from_bump_slice(items: &mut [T]) -> Self {
let mut v = Self::vecext_with_capacity(items.len());
// SAFETY: caller contract — `items` is a leaked bump-arena slice
// (`into_bump_slice_mut`); bitwise-move elements into a fresh `A`
// allocation, leaving the arena bytes abandoned (they were already
// leaked into the bump and will never be element-dropped).
unsafe {
core::ptr::copy_nonoverlapping(items.as_ptr(), v.as_mut_ptr(), items.len());
v.set_len(items.len());
}
v
}
#[inline]
fn from_arena_slice(items: &[T]) -> Self
where
T: Copy,
{
// For `T: Copy` the `from_bump_slice` bitwise-move is just a memcpy and
// the source carries no destructor.
let mut v = Self::vecext_with_capacity(items.len());
v.extend_from_slice(items);
v
}
#[inline]
fn from_bump_vec(mut src: bun_alloc::ArenaVec<'_, T>) -> Self {
let len = src.len();
let mut out = Self::vecext_with_capacity(len);
// SAFETY:
// - `src` is the unique owner of `len` initialized `T` at
// `src.as_ptr()`.
// - `out` has `cap >= len` uninit slots at `out.as_mut_ptr()`.
// - Source/dest are distinct allocations (arena heap vs `A` heap),
// so they cannot overlap.
// After the copy, `out` is the sole logical owner of every `T`; its
// `Drop` will run their destructors exactly once. `src.set_len(0)`
// marks the source logically empty so its `Drop` skips element
// destructors but still frees the buffer back to the `MimallocArena`
// (real `mi_free`, not a bump no-op) — without this the scratch buffer
// leaks until arena reset, and the parser's per-node
// `BumpVec → AstVec` pattern (decls/properties/args/items) turns that
// into O(nodes) dead arena bytes (≈+11% transpile RSS on a 5.7 MB
// input). Freeing here makes the scratch slot O(1): mimalloc recycles
// the same size-class block on the next iteration.
unsafe {
core::ptr::copy_nonoverlapping(src.as_ptr(), out.as_mut_ptr(), len);
out.set_len(len);
src.set_len(0);
}
// Buffer freed via `<&MimallocArena as Allocator>::deallocate` → `mi_free`.
drop(src);
out
}
#[inline]
fn init_capacity_in(_arena: &bun_alloc::Arena, cap: usize) -> Self {
Self::vecext_with_capacity(cap)
}
#[inline]
unsafe fn from_borrowed_slice_dangerous(items: &[T]) -> ManuallyDrop<Self> {
// SAFETY: caller must never drop or grow the returned `Vec` — its
// buffer is borrowed. Same contract as the original.
ManuallyDrop::new(unsafe {
Self::vecext_from_raw_parts(items.as_ptr().cast_mut(), items.len(), items.len())
})
}
#[inline]
fn slice(&self) -> &[T] {
self.as_slice()
}
#[inline]
fn slice_mut(&mut self) -> &mut [T] {
self.as_mut_slice()
}
#[inline]
fn slice_const(&self) -> &[T] {
self.as_slice()
}
#[inline]
fn at(&self, index: usize) -> &T {
&self[index]
}
#[inline]
fn mut_(&mut self, index: usize) -> &mut T {
&mut self[index]
}
#[inline]
fn len_u32(&self) -> u32 {
self.len() as u32
}
#[inline]
fn cap_u32(&self) -> u32 {
self.capacity() as u32
}
#[inline]
fn append(&mut self, value: T) {
self.push(value);
}
#[inline]
fn append_assume_capacity(&mut self, value: T) {
debug_assert!(self.len() < self.capacity());
self.push(value);
}
#[inline]
fn append_slice(&mut self, vals: &[T])
where
T: Clone,
{
self.extend_from_slice(vals);
}
#[inline]
fn append_slice_assume_capacity(&mut self, vals: &[T])
where
T: Copy,
{
self.extend_from_slice(vals);
}
#[inline]
fn ensure_total_capacity(&mut self, n: usize) {
let need = n.saturating_sub(self.len());
self.reserve(need);
}
#[inline]
fn ensure_total_capacity_precise(&mut self, n: usize) {
let need = n.saturating_sub(self.len());
self.reserve_exact(need);
}
#[inline]
fn ensure_unused_capacity(&mut self, n: usize) {
self.reserve(n);
}
#[inline]
fn shrink_retaining_capacity(&mut self, new_len: usize) {
self.truncate(new_len);
}
#[inline]
fn shrink_and_free(&mut self, new_len: usize) {
self.truncate(new_len);
self.shrink_to_fit();
}
#[inline]
fn clear_retaining_capacity(&mut self) {
self.clear();
}
#[inline]
fn clear_and_free(&mut self) {
*self = Self::vecext_new_empty();
}
#[inline]
fn drain_front(&mut self, n: usize)
where
T: Copy,
{
// Allocator-free mirror of bun_core::vec::drain_front — works for
// `Vec<T, A>` of any `A` (std VecExt impls span Global and AstAlloc).
if n == 0 {
return;
}
let len = self.len();
if n >= len {
self.clear();
return;
}
self.copy_within(n.., 0);
self.truncate(len - n);
}
#[inline]
fn ordered_remove(&mut self, index: usize) -> T {
self.remove(index)
}
#[inline]
fn insert_slice(&mut self, index: usize, vals: &[T])
where
T: Clone,
{
self.splice(index..index, vals.iter().cloned());
}
#[inline]
fn replace_range(&mut self, start: usize, len: usize, new_items: &[T])
where
T: Clone,
{
self.splice(start..start + len, new_items.iter().cloned());
}
#[inline]
unsafe fn expand_to_capacity(&mut self) {
// SAFETY: caller contract — every element in `[len, cap)` is written
// before being observed.
unsafe { self.set_len(self.capacity()) };
}
unsafe fn writable_slice(&mut self, additional: usize) -> &mut [T] {
self.reserve(additional);
let prev = self.len();
// SAFETY: caller contract — slice is fully written before any read.
unsafe { self.set_len(prev + additional) };
&mut self[prev..]
}
#[inline]
unsafe fn writable_slice_assume_capacity(&mut self, additional: usize) -> &mut [T] {
debug_assert!(self.len() + additional <= self.capacity());
let prev = self.len();
// SAFETY: caller contract — capacity asserted; slice fully written before any read.
unsafe { self.set_len(prev + additional) };
&mut self[prev..]
}
#[inline]
unsafe fn writable_slice_exact(&mut self, additional: usize) -> &mut [T] {
self.reserve_exact(additional);
let prev = self.len();
// SAFETY: caller contract — slice fully written before any read.
unsafe { self.set_len(prev + additional) };
&mut self[prev..]
}
#[inline]
fn reserve_spare(&mut self, additional: usize) -> &mut [core::mem::MaybeUninit<T>] {
self.reserve(additional);
&mut self.spare_capacity_mut()[..additional]
}
#[inline]
unsafe fn reserve_expand_tail(&mut self, additional: usize) -> (*mut T, usize) {
let prev = self.len();
if additional != 0 {
self.reserve(additional);
}
let cap = self.capacity();
// SAFETY: caller contract — `[prev, cap)` is FFI-written or truncated before any read.
unsafe { self.set_len(cap) };
// SAFETY: `prev <= cap`; ptr is within (or one-past) the allocation.
(unsafe { self.as_mut_ptr().add(prev) }, cap - prev)
}
#[inline]
fn move_to_list(&mut self) -> Vec<T> {
let taken = core::mem::replace(self, Self::vecext_new_empty());
// Fast path: `Vec<T, Global>` → `Vec<T>` is a pointer move, not a
// realloc+memcpy. Restores zero-copy behavior on the HTTP streaming
// paths (`RequestContext::response_buf`, `ByteStream`); the copying
// path is still required for `AstAlloc` etc. where the buffer must
// migrate heaps.
if Self::vecext_is_global() {
let mut taken = core::mem::ManuallyDrop::new(taken);
// SAFETY: `A == Global`, so `Vec<T, A>` and `Vec<T>` have the
// same layout, allocator, and drop semantics.
return unsafe {
std::vec::Vec::from_raw_parts(taken.as_mut_ptr(), taken.len(), taken.capacity())
};
}
let mut out = std::vec::Vec::with_capacity(taken.len());
out.extend(taken);
out
}
#[inline]
fn move_to_list_managed(&mut self) -> Vec<T> {
self.move_to_list()
}
#[inline]
fn to_owned_slice(&mut self) -> Box<[T]> {
self.move_to_list().into_boxed_slice()
}
#[inline]
fn shallow_copy(&self) -> ManuallyDrop<Self> {
// SAFETY: caller must not drop/grow the alias; original stays the owner.
ManuallyDrop::new(unsafe {
Self::vecext_from_raw_parts(self.as_ptr().cast_mut(), self.len(), self.capacity())
})
}
#[inline]
fn shallow_clone(&self) -> ManuallyDrop<Self> {
self.shallow_copy()
}
#[inline]
fn unused_capacity_slice(&mut self) -> &mut [core::mem::MaybeUninit<T>] {
self.spare_capacity_mut()
}
#[inline]
fn allocated_slice(&mut self) -> &mut [core::mem::MaybeUninit<T>] {
// SAFETY: ptr[0..cap] is the full allocation.
unsafe {
core::slice::from_raw_parts_mut(
self.as_mut_ptr().cast::<core::mem::MaybeUninit<T>>(),
self.capacity(),
)
}
}
#[inline]
fn memory_cost(&self) -> usize {
self.capacity() * core::mem::size_of::<T>()
}
#[inline]
fn sort_asc(&mut self)
where
T: AsRef<[u8]>,
{
self.sort_unstable_by(|a, b| a.as_ref().cmp(b.as_ref()));
}
#[inline]
fn sort(&mut self, mut less_than: impl FnMut(&T, &T) -> bool) {
self.sort_by(|a, b| {
if less_than(a, b) {
core::cmp::Ordering::Less
} else {
core::cmp::Ordering::Greater
}
});
}
fn deep_clone_with<F>(&self, mut clone_one: F) -> Self
where
F: FnMut(&T) -> T,
{
let mut v = Self::vecext_with_capacity(self.len());
for item in self.iter() {
v.push(clone_one(item));
}
v
}
fn try_deep_clone_with<F, E>(&self, mut clone_one: F) -> Result<Self, E>
where
F: FnMut(&T) -> Result<T, E>,
E: From<AllocError>,
{
let mut v = Self::vecext_with_capacity(self.len());
for item in self.iter() {
v.push(clone_one(item)?);
}
Ok(v)
}
};
($vec:ty, $alloc_trait:path) => {
impl<T, A: $alloc_trait + Default + 'static> VecExt<T> for $vec {
impl_vec_ext_for_channel!(@body);
}
};
($vec:ty) => {
impl<T> VecExt<T> for $vec {
impl_vec_ext_for_channel!(@body);
}
};
}
#[cfg(bao_nightly)]
impl_vec_ext_for_channel!(alloc::vec::Vec<T, A>, core::alloc::Allocator);
#[cfg(not(bao_nightly))]
impl_vec_ext_for_channel!(allocator_api2::vec::Vec<T, A>, allocator_api2::alloc::Allocator);
// The Global std `Vec<T>` on stable — covers every not-yet-migrated
// downstream buffer (plain `Vec<u8>`/`Vec<T>` fields) so `VecExt` methods
// keep resolving on both channels.
#[cfg(not(bao_nightly))]
impl_vec_ext_for_channel!(::std::vec::Vec<T>);
/// `Vec<u8>`-only helpers (Zig `Vec(u8)` extension methods).
pub trait ByteVecExt {
fn append_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<(), AllocError>;
fn write(&mut self, str: &[u8]) -> Result<u32, AllocError>;
fn write_latin1(&mut self, str: &[u8]) -> Result<u32, AllocError>;
fn write_utf16(&mut self, str: &[u16]) -> Result<u32, AllocError>;
fn write_type_as_bytes_assume_capacity<Int: Copy>(&mut self, int: Int);
/// libuv `uv_alloc_cb`-style: ensure **at least** `suggested` bytes of
/// spare capacity past `len()`, then return the *full* spare-capacity
/// slice (`len == capacity - len()`, which may exceed `suggested`).
///
/// Callers that must hand libuv exactly `suggested` bytes slice the
/// result themselves: `&mut v.uv_alloc_spare(n)[..n]`.
fn uv_alloc_spare(&mut self, suggested: usize) -> &mut [core::mem::MaybeUninit<u8>];
/// As [`uv_alloc_spare`] but typed `&mut [u8]` so the result can be used
/// directly as a `uv_buf_t` / `read(2)` target without a per-site cast.
///
/// # Safety
/// The returned bytes are **uninitialised**. Caller must only treat the
/// prefix actually written by the FFI/syscall as initialised (typically by
/// committing with [`uv_commit`]); the bytes must not be read before then.
unsafe fn uv_alloc_spare_u8(&mut self, suggested: usize) -> &mut [u8];
/// Commit `nread` bytes that the FFI/syscall just wrote into the slice
/// returned by [`uv_alloc_spare`] / [`uv_alloc_spare_u8`]: bumps `len` by
/// `nread`. Debug-asserts `len + nread <= capacity`.
///
/// # Safety
/// The `nread` bytes at `[len, len + nread)` must have been initialised by
/// the preceding write into the spare slice.
unsafe fn uv_commit(&mut self, nread: usize);
}
// Dual-channel byte-vec imprint: `ByteVecExt` is implemented for std
// `Vec<u8>` AND the `allocator_api2` mirror on BOTH channels, so downstream
// callers keep passing whichever byte-list type they hold (plain `Vec<u8>`
// buffers like `PipeWriter.list` or arena/API2 lists like
// `MutableString.list`) without per-site conversion. The bodies call only
// channel-agnostic helpers (`strings::*` are generic over
// `bun_core::vec::SpareBytesVec`; the spare-capacity fns likewise).
macro_rules! impl_byte_vec_ext {
($ty:ty) => {
impl ByteVecExt for $ty {
fn append_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<(), AllocError> {
// Neither api2 Vec nor every target here carries an
// io::Write/fmt::Write impl from std; push the fmt pieces
// through a byte-appending adapter — same output as
// `write!(self, "{}", args)` on an io::Write target.
struct FmtSink<'a>(&'a mut $ty);
impl fmt::Write for FmtSink<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.0.extend_from_slice(s.as_bytes());
Ok(())
}
}
use fmt::Write as _;
FmtSink(self).write_fmt(args).map_err(|_| AllocError)
}
fn write(&mut self, str: &[u8]) -> Result<u32, AllocError> {
let initial = self.len();
self.extend_from_slice(str);
Ok((self.len() - initial) as u32)
}
fn write_latin1(&mut self, str: &[u8]) -> Result<u32, AllocError> {
let initial = self.len();
let old = core::mem::take(self);
let old_len = old.len();
*self = strings::allocate_latin1_into_utf8_with_list(old, old_len, str);
Ok((self.len() - initial) as u32)
}
fn write_utf16(&mut self, str: &[u16]) -> Result<u32, AllocError> {
let initial = self.len();
let estimate = if (self.capacity() - self.len()) <= (str.len() * 3 + 2) {
bun_simdutf_sys::simdutf::length::utf8::from::utf16::le(str)
} else {
str.len()
};
self.reserve(estimate);
strings::convert_utf16_to_utf8_append(self, str);
Ok((self.len() - initial) as u32)
}
fn write_type_as_bytes_assume_capacity<Int: Copy>(&mut self, int: Int) {
let size = core::mem::size_of::<Int>();
debug_assert!(self.capacity() >= self.len() + size);
let prev = self.len();
// SAFETY: capacity asserted; writing `size` bytes into the uninit tail.
unsafe {
self.as_mut_ptr()
.add(prev)
.cast::<Int>()
.write_unaligned(int);
self.set_len(prev + size);
}
}
#[inline]
fn uv_alloc_spare(&mut self, suggested: usize) -> &mut [core::mem::MaybeUninit<u8>] {
// `Vec::reserve` already amortises by doubling, so a plain
// `reserve(suggested)` suffices — no manual `cap - len < suggested`
// dance is needed (it short-circuits internally).
self.reserve(suggested);
self.spare_capacity_mut()
}
#[inline]
unsafe fn uv_alloc_spare_u8(&mut self, suggested: usize) -> &mut [u8] {
// SAFETY: caller contract on `uv_alloc_spare_u8` — the returned uninit
// bytes are only read after the FFI-written prefix is committed.
unsafe { bun_core::vec::reserve_spare_bytes(self, suggested) }
}
#[inline]
unsafe fn uv_commit(&mut self, nread: usize) {
// SAFETY: caller contract on `uv_commit` — `[len, len+nread)` was
// initialised by the preceding write into the spare slice.
unsafe { bun_core::vec::commit_spare(self, nread) }
}
}
};
}
impl_byte_vec_ext!(Vec<u8>);
// api2 mirror imprint — stable channel only: there `core_alloc::Global` IS
// api2's Global (satisfies the vec's allocator bound). On nightly
// `core_alloc::Global` is std's Global, which api2's Vec does not accept
// (the hashbrown bridge covers DefaultAlloc/AstAlloc/ArenaPtr, not std
// Global) — and on nightly every byte list rides std Vec anyway.
#[cfg(not(bao_nightly))]
impl_byte_vec_ext!(::allocator_api2::vec::Vec<u8, ::bun_alloc::core_alloc::Global>);
impl crate::pool::ObjectPoolType for Vec<u8> {
const INIT: Option<fn() -> Result<Self, bun_core::Error>> = Some(|| Ok(Vec::new()));
#[inline]
fn reset(&mut self) {
self.clear();
}
}
#[derive(Default)]
pub struct OffsetByteList {
pub head: u32,
pub byte_list: Vec<u8>,
}
impl OffsetByteList {
pub fn init(head: u32, byte_list: Vec<u8>) -> Self {
Self { head, byte_list }
}
pub fn write(&mut self, bytes: &[u8]) -> Result<(), AllocError> {
self.byte_list.extend_from_slice(bytes);
Ok(())
}
pub fn slice(&self) -> &[u8] {
&self.byte_list[..self.head as usize]
}
pub fn remaining(&self) -> &[u8] {
&self.byte_list[self.head as usize..]
}
pub fn consume(&mut self, bytes: u32) {
self.head = self.head.saturating_add(bytes);
if self.head as usize >= self.byte_list.len() {
self.head = 0;
self.byte_list.clear();
}
}
pub fn len(&self) -> u32 {
self.byte_list.len() as u32 - self.head
}
pub fn clear(&mut self) {
self.head = 0;
self.byte_list.clear();
}
pub fn clear_and_free(&mut self) {
// Drop on the taken value frees `byte_list`; nothing is reused.
drop(core::mem::take(self));
}
}
/// Bitwise-move every element of `src` to the **front** of `dst`, shifting
/// `dst`'s existing contents right by `src.len()`. `src` is left empty
/// (capacity retained). This is the mirror of std [`Vec::append`], which
/// moves to the back.
///
/// Free function (not a `VecExt` method) so it is generic over *any*
/// `A: Allocator` — the `VecExt` blanket impl carries an
/// `A: Default + 'static` bound that `&'a MimallocArena` (i.e.
/// [`bun_alloc::ArenaVec`]) does not satisfy. `src` and `dst` may use
/// distinct allocators.
///
/// Ports the open-coded `reserve → ptr::copy(shift) → copy_nonoverlapping →
/// set_len` pattern that translated Zig's `bun.copy`/`@memcpy` splice for
/// non-`Copy` element types.
pub fn prepend_from<T, A: Allocator, B: Allocator>(
dst: &mut bun_alloc::core_alloc::AllocVec<T, A>,
src: &mut bun_alloc::core_alloc::AllocVec<T, B>,
) {
let src_len = src.len();
if src_len == 0 {
return;
}
let dst_len = dst.len();
dst.reserve(src_len);
// SAFETY: `reserve` guarantees capacity for `dst_len + src_len`. The shift
// memmove and the front copy together fully initialize `[0, dst_len+src_len)`.
// We commit `dst`'s new length only *after* `src` has been logically emptied
// so no element is ever owned by both vecs (no double-drop on unwind — and
// none of the ptr ops below can panic anyway).
unsafe {
let base = dst.as_mut_ptr();
// Shift existing `dst` elements right (overlapping → memmove).
core::ptr::copy(base, base.add(src_len), dst_len);
// `src` is a separate allocation → non-overlapping with `dst`'s buffer.
core::ptr::copy_nonoverlapping(src.as_ptr(), base, src_len);
// Elements were bitwise-moved out of `src`; relinquish ownership first…
src.set_len(0);
// …then claim it in `dst`.
dst.set_len(dst_len + src_len);
}
}