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
// Dual-mode (stable ⇄ nightly; channel probe in build.rs): the sole
// allocator-api site (`boxed_slices_as_borrowed`) rides the facade —
// nightly keeps core's `Box<[T], A>` byte-identical, stable uses the
// allocator_api2 mirror.
// bun_ptr is a T0 foundation crate that bun_threading and bun_collections
// depend on; importing either to satisfy disallowed-types would create a
// dependency cycle.
//! The `ptr` module contains smart pointer types that are used throughout Bun.
//!
//! Per PORTING.md §Pointers, most consumers of `bun.ptr.*` map directly to std
//! types (`Box`, `Rc`, `Arc`, `Cow`) and `bun_collections` (`TaggedPtr`,
//! `TaggedPtrUnion`). This crate hosts the intrusive/FFI-crossing variants.
extern crate alloc;
use Box as AllocBox;
use Box as AllocBox;
pub use Allocator;
pub use Allocator;
// Cow/CowSlice → std (PORTING.md says these ARE std::borrow::Cow)
pub use Cow;
pub type CowSlice<'a, T> = ;
pub type CowSliceZ<'a> = ;
pub type CowString<'a> = ;
// `bun.ptr.CowSlice(T)` / `CowSliceZ` — the lifetime-free struct port (owns or
// borrows a raw slice with `init_owned`/`borrow_subslice`/`length`). Distinct
// from the `std::borrow::Cow` aliases above; callers that need the Zig-shaped
// API (e.g. `pack_command::Pattern`) reach for `cow_slice::CowSlice<u8>`.
// owned/shared — OBSOLETE per PORTING.md §Pointers: callers
// use std `Box`/`Rc`/`Arc` directly. Draft modules kept for diff-pass only.
pub type Owned<T> = ;
pub type OwnedIn<T> = ;
pub type DynamicOwned<T> = ;
// FFI-crossing externally-ref-counted pointer (e.g., WTFStringImpl). Canonical
// impl moved down to `bun_core::external_shared` (cycle-break for the
// `bun_string → bun_core` merge); re-exported here unchanged.
pub use external_shared;
pub use ;
// `cast_fn_ptr` and `RawSlice` likewise moved to `bun_core`; re-export.
pub use ;
// Compat aliases — `tagged_pointer` exports short names; some downstream code
// uses the long ones.
pub use ;
pub use ;
// Derive macros — same names as the traits (separate namespace). The derives
// expand to `::bun_ptr::…` paths, so this crate is the canonical re-export
// point: `#[derive(bun_ptr::CellRefCounted)]`.
pub use ;
pub use ;
// Compat aliases for callers that use the pointer-typedef names.
pub type IntrusiveRc<T> = ;
pub type IntrusiveArc<T> = ;
pub use RawRefCount;
pub use WeakPtr;
// Intrusive parent-from-field recovery — canonical helpers live in `bun_core`
// (lowest tier, every crate can reach them); re-exported here so callers can
// spell `bun_ptr::container_of` / `bun_ptr::from_field_ptr!`.
pub use ;
// C-callback `void *user_data` → `&mut T` recovery — same tiering rationale
// as `container_of`; canonical impl lives in `bun_core`, re-exported here so
// runtime crates spell `bun_ptr::callback_ctx::<T>(ctx)`.
pub use callback_ctx;
// small, used by other crates
// ported from: src/ptr/ptr.zig
// ─────────────────────────────────────────────────────────────────────────────
// BackRef<T> / RawSlice<T> — runtime back-reference / borrowed-slice wrappers.
//
// Runtime structs frequently hold a non-owning pointer back to their owner
// (Zig: `*Parent`, `*const VirtualMachine`, `[]const u8`). The original port
// modeled these as raw `*mut T` / `*const [T]` and open-coded
// `unsafe { &*self.field }` at every read site. These two wrappers centralise
// that pattern under the
// `StoreRef`/`StoreSlice` contract from the parser, but for the *runtime*
// lifetime invariant: the pointee strictly outlives the holder by construction
// (owner creates child, child stores `BackRef` to owner; owner is destroyed
// only after the child). No arena involved — the pointee is heap- or
// stack-pinned for the holder's entire life.
//
// Unlike `StoreRef` (parser-arena, `u32` slice len), `RawSlice` keeps the full
// `usize` length so it is a drop-in replacement for any `*const [T]` field.
// ─────────────────────────────────────────────────────────────────────────────
/// Non-owning, non-null back-reference to an object that outlives `self`.
///
/// Mirrors Zig `*T` struct fields where the pointee is the owner/parent and is
/// guaranteed live for the holder's entire lifetime (owner-creates-child).
/// `Copy` + `Deref` so call sites read `self.owner.method()` instead of
/// `unsafe { &*self.owner }.method()`.
;
/// Detach a slice borrow from its borrowck lifetime.
///
/// This is the **local-variable** counterpart to [`RawSlice`]. Use it when you
/// need to read through a slice while a sibling field is reborrowed `&mut`
/// (the classic Zig `var buf = lockfile.buffers.string_bytes; … &mut lockfile`
/// pattern), and the backing storage is known not to move/realloc for the
/// scope of the returned reference. Unlike `RawSlice`, this is *not* meant for
/// struct fields — it exists so the borrowck-dodge stays a one-liner with the
/// `unsafe` centralised here, rather than laundering the slice through a
/// `RawSlice::new(..).slice()` round-trip that obscures intent.
///
/// # Safety
/// Caller guarantees the slice's backing allocation is not freed, moved, or
/// reallocated, and no exclusive `&mut` to the same elements is formed, for
/// the full lifetime `'a` chosen by the caller.
pub unsafe
/// Detach a `&T` borrow from its borrowck lifetime (general `?Sized` form of
/// [`detach_lifetime`]).
///
/// Replaces the open-coded `unsafe { &*std::ptr::from_ref::<T>(x) }` /
/// `unsafe { &*(&raw const x) }` lifetime-laundering idiom that the original
/// port scattered everywhere a Zig `*const T` was held across a sibling
/// `&mut self` reborrow (arena handles, SoA columns, self-referential views).
/// Centralising it here makes the call sites grep-able and the safety
/// obligation uniform.
///
/// # Safety
/// Caller guarantees the pointee is not freed, moved, or exclusively borrowed
/// for the full caller-chosen lifetime `'a`.
pub unsafe Sized>
/// Detach a `&mut T` borrow from its borrowck lifetime.
///
/// Mutable counterpart of [`detach_lifetime_ref`]. Replaces the open-coded
/// `unsafe { &mut *std::ptr::from_mut::<T>(x) }` pattern. Strictly more
/// dangerous than the shared form: callers must additionally guarantee
/// **uniqueness** for `'a` (no other `&`/`&mut` to the same `T` is live).
///
/// # Safety
/// Caller guarantees the pointee is live for `'a` and that no other borrow
/// (shared or exclusive) to it overlaps the returned `&'a mut T`.
pub unsafe Sized>
/// Marker trait for types whose `&mut self` methods launder `self` through
/// `core::hint::black_box` (PORT_NOTES_PLAN **R-2**) before dispatching a
/// re-entrant parent/user callback, then reborrow via [`LaunderedSelf::r`].
///
/// Zig has no `noalias` on `*Self`, so the original `.zig` just writes
/// `this.*` directly; this trait is the Rust-port-only artifact that makes the
/// equivalent reborrow sound without scattering `unsafe { &mut *this }` at
/// every field access.
///
/// # Safety (impl contract)
/// For every method on `Self` that calls [`r`](Self::r):
/// - `Self` is an inline/intrusive field of a heap object that is **never
/// freed** during the re-entrant callback (the laundered raw pointer aliases
/// a `&mut self` whose stack frame is still live);
/// - re-entry runs on the **single JS thread** (no concurrent `&mut Self`);
/// - each `&mut Self` produced by [`r`](Self::r) is short-lived and is the
/// sole live borrow at the point of use — never held across the next
/// parent/user dispatch.
pub unsafe
/// Shorter alias for [`detach_lifetime_ref`] — two workstreams converged on
/// slightly different names; both are kept so callers from either land cleanly.
pub use detach_lifetime_ref as detach_ref;
/// Reinterpret `&[Box<[T]>]` as `&[&[T]]` for read-only fan-out.
///
/// `Box<[T]>` and `&[T]` are both `(NonNull<T>, len: usize)` fat pointers with
/// identical layout (guaranteed by the unsized-pointer ABI), so a column of
/// owned boxed slices can be viewed as a column of borrows without copying.
/// Used by the bundler's SoA columns (`items_unique_key_for_additional_file`)
/// where the printer API wants `&[&[u8]]`.
///
/// The returned borrows are valid for the input borrow `'a` only — the boxes
/// are not moved or dropped while the view is live.
///
/// # Safety
/// Relies on `Box<[T]>` and `&[T]` having identical fat-pointer **field
/// order** (data-ptr then len). This is de-facto stable on every supported
/// rustc but is not a language guarantee — the const block below proves only
/// size/align. `unsafe` + `#[doc(hidden)]` so the layout assumption stays
/// visible at each call site rather than inviting new callers; do not use
/// outside the bundler SoA-column read-only fan-out it was written for.
pub unsafe
// ─────────────────────────────────────────────────────────────────────────────
// Interned — process-lifetime byte-slice proof type.
//
// The original port widened ~100 borrowed `&[u8]` to `&'static [u8]` via
// open-coded `unsafe { &*ptr::from_ref(s) }`. Audit splits them into:
//
// • Population A (~80) — bytes live in a process-lifetime store
// (`FilenameStore` / `DirnameStore` / `BSSStringList` singleton, a
// `Box::leak`, or a true `static` literal). The widen is sound, but the
// bare `&'static [u8]` carries no proof, so a refactor can silently feed
// it a stack slice.
// • Population B (~24) — bytes are owned by a value with a `Drop` that runs
// before process exit (UserOptions arena, FetchTasklet, JSC slice, SSL
// session). The widen is unsound the moment the value escapes the holder.
//
// `Interned` is the type-level proof that a `&'static [u8]` came from
// Population A. Safe constructors accept only genuinely-process-lifetime
// inputs (`from_static`, `leak`, `leak_vec`); the single `unsafe` escape hatch
// (`assume`) forces every Population-B caller to spell out — in its SAFETY
// comment — exactly which owner backs the bytes and when it drops, so the lie
// is grep-able rather than ambient.
//
// `repr(transparent)` over `&'static [u8]`: zero-cost, FFI-identical to the
// fields it replaces, `Option<Interned>` niche-packs, and `Send + Sync` is
// inherited via auto-traits (no `unsafe impl` needed).
//
// This does NOT cover `&'static mut [u8]` / `&'static mut T` forges (e.g.
// `FileReader::pending_view`, `Decompressor::seat` output, `CmdHandle::cmd_mut`)
// — those are tracked under the sibling `static-widen-mut` pattern and want a
// raw-pointer field or a future `RawSliceMut<T>`.
// ─────────────────────────────────────────────────────────────────────────────
/// A byte slice backed by **process-lifetime** storage.
///
/// Process-lifetime ≡ one of:
/// • interned in a `BSSStringList` singleton (`FilenameStore`, `DirnameStore`),
/// • a `Box::leak` / `Vec::leak` that is never reclaimed,
/// • a true `'static` item (string literal, `static` array).
///
/// `Interned` exists so that the ~80 open-coded `&[u8] → &'static [u8]` widens
/// become a safe value flowing from the store, and so that the ~24 sites whose
/// backing **does** drop can no longer pretend to be `'static` — they must
/// spell `unsafe { Interned::assume(..) }` and name the owner in the SAFETY
/// comment, or (correctly) switch to [`RawSlice<u8>`] / [`BackRef<T>`].
;
// ─────────────────────────────────────────────────────────────────────────────
// ThisPtr<T> — callback-dispatch self-pointer
//
// uSockets / C++ FFI dispatch hands every socket-event handler a raw
// `*mut Self` recovered from the userdata slot. The original port open-coded
// `unsafe { (*this).field }` / `unsafe { (&*this).ref_() }` /
// `scopeguard::guard(this, |p| unsafe { Self::deref(p) })` at ~90 call sites
// across the websocket-client family. `ThisPtr` centralises that pattern under
// ONE constructor SAFETY contract: wrap the raw pointer once at fn entry, then
// read fields via `Deref` and bracket the body with `ref_guard()` (RAII
// `ScopedRef`) instead of hand-paired `ref_()`/`deref()` at every early-exit.
//
// Unlike [`BackRef`] (owner-outlives-holder back-reference), a `ThisPtr` is for
// the *callee-is-the-allocation* case: the pointee is an intrusively-refcounted
// heap object that may be **freed during the call** (a reentrant `deref()`
// reaching zero). `ThisPtr` therefore:
// • is `Copy` and holds no ref of its own — it is purely a typed view of the
// incoming `*mut Self`;
// • only ever vends fresh short-lived `&T` (no `DerefMut`): handlers that
// re-enter via the same userdata pointer would alias a held `&mut T`.
// Mutation goes through `as_ptr()` with a per-site `unsafe { (*p).… }`.
// ─────────────────────────────────────────────────────────────────────────────
/// Non-owning, `Copy` self-pointer for uSockets / FFI callback dispatch.
///
/// See the module comment above for the full rationale. Construct once per
/// handler entry with [`ThisPtr::new`], then use `Deref` for field reads and
/// [`ThisPtr::ref_guard`] for the keep-alive bracket.
;
// SAFETY: `BackRef<T>` is morally `&T` (Deref/get) with an unsafe `get_mut`
// escape hatch whose exclusivity is the caller's per-site obligation. Match
// `&T` auto-trait bounds: `&T: Send ⇔ T: Sync`, `&T: Sync ⇔ T: Sync`. Holders
// that additionally call `get_mut` across threads must separately ensure
// `T: Send` at the call site (no different from `NonNull<T>` today).
unsafe
// SAFETY: `&BackRef<T>` only yields `&T` (via `get`/`Deref`); `&T: Sync` holds
// exactly when `T: Sync`, so sharing the back-reference across threads is sound.
unsafe
// ─────────────────────────────────────────────────────────────────────────────
// AsCtxPtr — `&self` → `*mut Self` for FFI / C-callback ctx slots.
//
// Dual of [`callback_ctx`]: this is the *producer* side that stuffs `self`
// into a `void *user_data` / `*mut T` ctx parameter; `callback_ctx` (or a
// plain `unsafe { &*p }`) is the *consumer* side that recovers it inside the
// trampoline.
//
// The returned pointer carries **shared (read-only) provenance** — it is
// derived from `&self`, so writing through it directly is UB. The `*mut`
// spelling exists purely to match C-shaped signatures (`void *`, uSockets
// ext slots, `ScopedRef` / `DerefOnDrop` ctx, vtable thunks, intrusive
// `RefCount::deref`). Consumers must deref as `&*p` and route mutation
// through `Cell` / `JsCell` / `UnsafeCell` interior-mutability fields.
//
// Blanket-implemented for all `T`: bring the trait into scope with
// `use bun_ptr::AsCtxPtr;` and the inherent-looking `self.as_ctx_ptr()`
// resolves on any type. Replaces 19 identical hand-rolled
// `fn as_ctx_ptr(&self) -> *mut Self { (self as *const Self).cast_mut() }`
// inherent methods scattered across runtime JS-class wrappers.
// ─────────────────────────────────────────────────────────────────────────────
/// `&self` → `*mut Self` with shared provenance, for C-callback / scopeguard
/// ctx slots. See module-level comment above for the safety contract.