bun_collections 0.1.2

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
Documentation
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
use core::cell::RefCell;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::ptr;

use bun_core::Error;

// ──────────────────────────────────────────────────────────────────────────
// SinglyLinkedList
// ──────────────────────────────────────────────────────────────────────────
//
// PORT NOTE: Zig's `SinglyLinkedList(comptime T: type, comptime Parent: type)`
// threads `Parent` only so that `Node.release()` can call `Parent.release(node)`.
// In Rust the only `Parent` is `ObjectPool`, so `Node::release` is provided as
// an inherent method on `ObjectPool` instead and the `Parent` type param is
// dropped here. Diff readers: `node.release()` call sites become
// `ObjectPool::<..>::release(node)`.

/// Node inside the linked list wrapping the actual data.
#[repr(C)]
pub struct Node<T> {
    // INTRUSIVE: pool.zig:7 — next link in singly-linked free list
    pub next: *mut Node<T>,
    // PORT NOTE: Zig stored `std.mem.Allocator param` here so `destroyNode`
    // could free via the originating allocator. In Rust the global mimalloc
    // allocator owns every `Box<Node<T>>`, so the field is dropped and
    // `destroy_node` uses `heap::take`.
    //
    // PORT NOTE: `MaybeUninit<T>` not `T` — Zig's `else undefined` (pool.zig:203)
    // is well-defined-until-read, but Rust's `assume_init()` on uninit bytes is
    // immediate UB for any `T` with validity invariants. Callers that use
    // `INIT == None` write `data` before reading, so we keep the bytes
    // uninitialized and only `assume_init_*` at access sites.
    pub data: MaybeUninit<T>,
}

// PORT NOTE: `pub const Data = T;` (inherent assoc type) is nightly-only;
// callers can write `T` directly.

impl<T> Node<T> {
    /// Read `(*p).next` for a known-non-null, live node pointer. Centralises
    /// the `unsafe { (*p).next }` walk that appears throughout this module's
    /// list traversals. Caller contract: `p` points at a live `Node<T>` (never
    /// null — debug-asserted).
    #[inline(always)]
    fn next_of(p: *const Node<T>) -> *mut Node<T> {
        debug_assert!(!p.is_null());
        // SAFETY: every call site passes a node either just popped from the
        // free list, just compared non-null in the surrounding `while`/`if`,
        // or `&self`/`self.first` after an explicit null check.
        unsafe { (*p).next }
    }

    /// Access the pooled value.
    ///
    /// # Safety
    /// `data` must be initialized: either the pool was instantiated with
    /// `T::INIT == Some(_)`, or the caller wrote to `data` after `get()`,
    /// or the node was created via `push(value)`.
    #[inline]
    pub unsafe fn data_ref(&self) -> &T {
        // SAFETY: caller guarantees `data` is initialized.
        unsafe { self.data.assume_init_ref() }
    }

    /// See [`Node::data_ref`] for safety requirements.
    #[inline]
    pub unsafe fn data_mut(&mut self) -> &mut T {
        // SAFETY: caller guarantees `data` is initialized.
        unsafe { self.data.assume_init_mut() }
    }

    /// Insert a new node after the current one.
    ///
    /// Arguments:
    ///     new_node: Pointer to the new node to insert.
    pub fn insert_after(&mut self, new_node: &mut Node<T>) {
        new_node.next = self.next;
        self.next = std::ptr::from_mut::<Node<T>>(new_node);
    }

    /// Remove a node from the list.
    ///
    /// Arguments:
    ///     node: Pointer to the node to be removed.
    /// Returns:
    ///     node removed
    pub fn remove_next(&mut self) -> Option<*mut Node<T>> {
        let next_node = if self.next.is_null() {
            return None;
        } else {
            self.next
        };
        self.next = Node::next_of(next_node);
        Some(next_node)
    }

    /// Iterate over the singly-linked list from this node, until the final node is found.
    /// This operation is O(N).
    pub fn find_last(&mut self) -> *mut Node<T> {
        let mut it: *mut Node<T> = std::ptr::from_mut::<Node<T>>(self);
        loop {
            let next = Node::next_of(it);
            if next.is_null() {
                return it;
            }
            it = next;
        }
    }

    /// Iterate over each next node, returning the count of all nodes except the starting one.
    /// This operation is O(N).
    pub fn count_children(&self) -> usize {
        let mut count: usize = 0;
        let mut it: *const Node<T> = self.next;
        while !it.is_null() {
            count += 1;
            it = Node::next_of(it);
        }
        count
    }

    // PORT NOTE: `pub inline fn release(node: *Node) void { Parent.release(node) }`
    // is expressed as `ObjectPool::<T, ..>::release(node)` at call sites; see
    // module-level note above.
}

pub struct SinglyLinkedList<T> {
    // INTRUSIVE: pool.zig:59 — list head; popFirst hands node to caller
    pub first: *mut Node<T>,
}

impl<T> Default for SinglyLinkedList<T> {
    fn default() -> Self {
        Self {
            first: ptr::null_mut(),
        }
    }
}

impl<T> Drop for SinglyLinkedList<T> {
    fn drop(&mut self) {
        // The free list owns its nodes (each `release()` hands ownership back).
        // Without this, the TLS-backed pool's `DataStruct` strands every cached
        // node when the thread exits.
        let mut next = core::mem::replace(&mut self.first, ptr::null_mut());
        while !next.is_null() {
            let node = next;
            next = Node::next_of(node);
            // SAFETY: free-list nodes always carry initialized `data`
            // (`release()` only stores nodes that were used) and are
            // exclusively owned by the list.
            unsafe {
                (*node).data.assume_init_drop();
                drop(bun_core::heap::take(node));
            }
        }
    }
}

impl<T> SinglyLinkedList<T> {
    /// Insert a new node at the head.
    ///
    /// `new_node` must be live and exclusively owned by the caller until popped.
    pub fn prepend(&mut self, new_node: &mut Node<T>) {
        new_node.next = self.first;
        self.first = new_node;
    }

    /// Remove a node from the list. `node` must currently be in this list.
    pub fn remove(&mut self, node: &Node<T>) {
        let node = std::ptr::from_ref(node).cast_mut();
        if self.first == node {
            self.first = Node::next_of(node);
        } else {
            // SAFETY: self.first is non-null (else the `==` above would have
            // matched the null `node`, which callers never pass)
            let mut current_elm = self.first;
            // SAFETY: walk live list nodes; Zig's `.?` would panic on null —
            // mirror that with an unchecked deref.
            unsafe {
                while (*current_elm).next != node {
                    current_elm = (*current_elm).next;
                }
                (*current_elm).next = (*node).next;
            }
        }
    }

    /// Remove and return the first node in the list.
    ///
    /// Returns:
    ///     A pointer to the first node in the list.
    pub fn pop_first(&mut self) -> Option<*mut Node<T>> {
        let first = if self.first.is_null() {
            return None;
        } else {
            self.first
        };
        self.first = Node::next_of(first);
        Some(first)
    }

    /// Iterate over all nodes, returning the count.
    /// This operation is O(N).
    pub fn len(&self) -> usize {
        if !self.first.is_null() {
            // SAFETY: first is non-null and live
            1 + unsafe { (*self.first).count_children() }
        } else {
            0
        }
    }
}

// ──────────────────────────────────────────────────────────────────────────
// ObjectPool
// ──────────────────────────────────────────────────────────────────────────

const LOG_ALLOCATIONS: bool = false;

/// Behavior hooks the Zig version expressed via `comptime Init: ?fn(...)` and
/// `std.meta.hasFn(Type, "reset")`. Per PORTING.md §Comptime reflection,
/// optional-decl checks become a trait with default methods.
pub trait ObjectPoolType: Sized {
    /// Mirrors `comptime Init: ?fn(allocator) anyerror!Type`. `None` ⇒ the
    /// Zig path that left `data` as `undefined`.
    const INIT: Option<fn() -> Result<Self, Error>> = None;

    /// Mirrors `if (std.meta.hasFn(Type, "reset")) node.data.reset()`.
    /// Default is a no-op; types that had `.reset()` in Zig override this.
    #[inline]
    fn reset(&mut self) {}
}

/// Per-pool mutable state. Zig's `DataStruct`.
pub struct DataStruct<T> {
    pub list: SinglyLinkedList<T>,
    pub loaded: bool,
    // PORT NOTE: Zig used `MaxCountInt = std.math.IntFittingRange(0, max_count)`.
    // Rust const generics cannot pick an integer type from a const value; use
    // `usize` and accept the few extra bytes.
    // PERF(port): was IntFittingRange — narrow if it shows up on a hot path.
    pub count: usize,
}

impl<T> Default for DataStruct<T> {
    fn default() -> Self {
        Self {
            // PORT NOTE: Zig had `list: LinkedList = undefined` — we zero it.
            list: SinglyLinkedList::default(),
            loaded: false,
            count: 0,
        }
    }
}

/// Object pool with a singly-linked free list.
///
/// `THREADSAFE == true`  ⇒ storage is thread-local (one free list per thread).
/// `THREADSAFE == false` ⇒ storage is a single process-wide static.
///
/// `S` supplies the per-monomorphization static storage; see `object_pool!`.
pub struct ObjectPool<
    T: ObjectPoolType,
    const THREADSAFE: bool,
    const MAX_COUNT: usize,
    S = UnwiredStorage,
>(core::marker::PhantomData<(T, S)>);

// PORT NOTE: `pub const List = SinglyLinkedList(T)` / `pub const Node = Node(T)`
// inherent assoc types are nightly-only; callers write `SinglyLinkedList<T>` /
// `Node<T>` directly.

/// Per-monomorphization storage hook. Generic statics are not expressible in
/// Rust, so each `(T, THREADSAFE, MAX_COUNT)` instantiation must provide its
/// own `thread_local!` / `static` via this trait — typically generated by
/// `object_pool!`.
pub trait PoolStorage<T>: 'static {
    /// Run `f` with a borrow of this monomorphization's `DataStruct`.
    fn with<R>(f: impl FnOnce(&RefCell<DataStruct<T>>) -> R) -> R;
}

/// Fallback storage that panics on first use. Lets `ObjectPool<T, ..>` name a
/// concrete type before its storage is wired (matches the prior `data()`
/// `unreachable!`).
pub struct UnwiredStorage;
impl<T: 'static> PoolStorage<T> for UnwiredStorage {
    fn with<R>(_f: impl FnOnce(&RefCell<DataStruct<T>>) -> R) -> R {
        unreachable!(
            "ObjectPool<{}> storage not wired — declare with `object_pool!`",
            core::any::type_name::<T>()
        )
    }
}

/// Trait alias so callers can name `<Pool as ObjectPoolTrait>::Node` without
/// knowing the concrete generics.
pub trait ObjectPoolTrait {
    type Item;
    type Node;
}

impl<T: ObjectPoolType, const TS: bool, const MAX: usize, S> ObjectPoolTrait
    for ObjectPool<T, TS, MAX, S>
{
    type Item = T;
    type Node = Node<T>;
}

/// RAII handle for a pooled `T`. Derefs to the inner value; on `Drop`, the
/// node is returned to its pool. Replaces the Zig `get()` + `defer release()`
/// pair.
pub struct PoolGuard<'a, T: ObjectPoolType + 'static> {
    node: *mut Node<T>,
    release: unsafe fn(&mut Node<T>),
    _marker: PhantomData<&'a mut T>,
}

impl<'a, T: ObjectPoolType> core::ops::Deref for PoolGuard<'a, T> {
    type Target = T;
    #[inline]
    fn deref(&self) -> &T {
        // SAFETY: `node` is exclusively owned for the guard's lifetime and its
        // `data` was initialized by the pool's `get()` path before being handed
        // out (either via `T::INIT` or by reuse of a previously-written node).
        unsafe { (*self.node).data.assume_init_ref() }
    }
}

impl<'a, T: ObjectPoolType> core::ops::DerefMut for PoolGuard<'a, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut T {
        // SAFETY: see `Deref` impl.
        unsafe { (*self.node).data.assume_init_mut() }
    }
}

impl<'a, T: ObjectPoolType> Drop for PoolGuard<'a, T> {
    fn drop(&mut self) {
        // SAFETY: `self.node` was obtained from `ObjectPool::get_node` and is
        // exclusively owned by this guard for its lifetime; ownership returns
        // to the pool's free list. `data` is initialized: either `T::INIT` is
        // `Some` (so `get_node` wrote it), or the guard's `DerefMut` already
        // proved initialization to the borrow checker before any read.
        unsafe { (self.release)(&mut *self.node) };
    }
}

impl<'a, T: ObjectPoolType> PoolGuard<'a, T> {
    /// Raw pointer to the underlying node (for callers that need to stash it
    /// across an FFI boundary). The guard still owns the node.
    #[inline]
    pub fn node_ptr(&self) -> *mut Node<T> {
        self.node
    }
}

impl<T: ObjectPoolType + 'static, const THREADSAFE: bool, const MAX_COUNT: usize, S>
    ObjectPool<T, THREADSAFE, MAX_COUNT, S>
where
    S: PoolStorage<T>,
{
    // We want this to be global
    // but we don't want to create 3 global variables per pool
    // instead, we create one global variable per pool
    //
    // PORT NOTE: Rust cannot place a `static` / `thread_local!` inside a
    // generic `impl`; storage is supplied via the `S: PoolStorage<T>` type
    // parameter (see `object_pool!` for the usual declaration).
    #[inline]
    pub(crate) fn data<R>(f: impl FnOnce(&RefCell<DataStruct<T>>) -> R) -> R {
        S::with(f)
    }

    pub fn full() -> bool {
        if MAX_COUNT == 0 {
            return false;
        }
        Self::data(|cell| {
            let d = cell.borrow();
            d.loaded && d.count >= MAX_COUNT
        })
    }

    pub fn push(pooled: T) {
        if cfg!(debug_assertions) {
            // PORT NOTE: Zig gated on `env.allow_assert`; that is
            // `Environment.isDebug` ⇒ `cfg!(debug_assertions)`.
            debug_assert!(!Self::full());
        }

        let new_node = bun_core::heap::into_raw(Box::new(Node::<T> {
            next: ptr::null_mut(),
            data: MaybeUninit::new(pooled),
        }));
        // SAFETY: `new_node` is a freshly heap-allocated `Node<T>` we exclusively
        // own, and `data` was initialized to `pooled` just above.
        unsafe { Self::release(&mut *new_node) };
    }

    pub fn get_if_exists() -> Option<*mut Node<T>> {
        Self::data(|cell| {
            let mut d = cell.borrow_mut();
            if !d.loaded {
                return None;
            }

            let node = d.list.pop_first()?;
            // SAFETY: node was just popped from the free list and is exclusively owned;
            // free-list nodes always carry initialized `data` (they reach the list
            // via `push` or `release` of a previously-used node).
            unsafe { (*node).data.assume_init_mut().reset() };
            if MAX_COUNT > 0 {
                d.count = d.count.saturating_sub(1);
            }

            Some(node)
        })
    }

    pub fn first() -> *mut T {
        // SAFETY: `get_node()` always returns a valid, exclusively-owned node
        unsafe { (*Self::get_node()).data.as_mut_ptr() }
    }

    /// Zig `get()` — pop a node from the free list or allocate a fresh one.
    ///
    /// When `T::INIT == None` and a fresh node is allocated, the returned
    /// node's `data` is **uninitialized**; the caller must write a valid `T`
    /// to it before reading it or passing the node to [`Self::release`].
    pub fn get_node() -> *mut Node<T> {
        let reused = Self::data(|cell| {
            let mut d = cell.borrow_mut();
            if d.loaded {
                if let Some(node) = d.list.pop_first() {
                    // SAFETY: node just popped from free list, exclusively owned;
                    // free-list nodes always carry initialized `data`.
                    unsafe { (*node).data.assume_init_mut().reset() };
                    if MAX_COUNT > 0 {
                        d.count = d.count.saturating_sub(1);
                    }
                    return Some(node);
                }
            }
            None
        });
        if let Some(node) = reused {
            return node;
        }

        if LOG_ALLOCATIONS {
            // PORT NOTE: Zig wrote to stderr via std.fs; banned here. Route
            // through `bun_core::Output` if this is ever flipped on.
            // TODO(port): log "Allocate {type_name} - {size} bytes"
        }

        // Matches Zig's `data = if (Init) |i| i(..) else undefined` (pool.zig:203).
        // For `INIT == None` the bytes stay uninitialized; the caller MUST write
        // `data` before any read (and before `release()`, since `destroy_node`
        // assumes it is initialized when dropping).
        let data = match T::INIT {
            Some(init_) => MaybeUninit::new(init_().expect("unreachable")),
            None => MaybeUninit::uninit(),
        };
        bun_core::heap::into_raw(Box::new(Node::<T> {
            next: ptr::null_mut(),
            data,
        }))
    }

    /// RAII front-door: pop or allocate a node and wrap it in a `PoolGuard`
    /// that returns it to this pool on `Drop`.
    pub fn get() -> PoolGuard<'static, T> {
        PoolGuard {
            node: Self::get_node(),
            release: Self::release,
            _marker: PhantomData,
        }
    }

    /// `value` must point to the `data` field of a live `Node<T>` previously
    /// handed out by this pool (e.g. via `first()`).
    pub fn release_value(value: &mut T) {
        // SAFETY: `value` points to the `data` field of a live `Node<T>`.
        let node = unsafe { bun_core::from_field_ptr!(Node<T>, data, value) };
        // SAFETY: `node` is the parent of the `data` field, exclusively owned.
        // `data` is initialized: the caller handed us `&mut T`, which is only
        // possible to form (without UB on the caller's side) if `data` holds a
        // valid `T`.
        unsafe { Self::release(&mut *node) };
    }

    /// Return a node to the pool's free list (or free it if the pool is full).
    ///
    /// # Safety
    ///
    /// `node` must be a live, exclusively-owned `Node<T>` previously handed out
    /// by this pool (e.g. via `get` / `get_node` / `first`), and `node.data`
    /// must be initialized. The free list assumes every stored node carries a
    /// valid `T` so it can `assume_init_mut().reset()` on reuse and
    /// `assume_init_drop()` on teardown — releasing a node that was obtained
    /// from `get_node()` with `T::INIT == None` and never written is UB.
    /// Ownership transfers back to the pool's free list.
    pub unsafe fn release(node: &mut Node<T>) {
        let node_ptr: *mut Node<T> = node;
        let overflowed = Self::data(|cell| {
            let mut d = cell.borrow_mut();
            if MAX_COUNT > 0 && d.count >= MAX_COUNT {
                if LOG_ALLOCATIONS {
                    // TODO(port): log "Free {type_name} - {size} bytes"
                }
                return true;
            }

            if MAX_COUNT > 0 {
                d.count = d.count.saturating_add(1);
            }

            if d.loaded {
                d.list.prepend(node);
            } else {
                d.list = SinglyLinkedList { first: node_ptr };
                d.loaded = true;
            }
            false
        });
        if overflowed {
            Self::destroy_node(node_ptr);
        }
    }

    pub fn delete_all() {
        let mut next = Self::data(|cell| {
            let mut dat = cell.borrow_mut();
            if !dat.loaded {
                return ptr::null_mut();
            }
            dat.loaded = false;
            dat.count = 0;
            let head = dat.list.first;
            dat.list.first = ptr::null_mut();
            head
        });
        while !next.is_null() {
            let node = next;
            next = Node::next_of(node);
            Self::destroy_node(node);
        }
    }

    fn destroy_node(node: *mut Node<T>) {
        // TODO(port): Zig special-cased `Type != bun.Vec<u8>` here to skip
        // `bun.memory.deinit(&node.data)` for `Vec<u8>` (a known leak the Zig
        // comment calls out). In Rust, dropping `T` is the moral equivalent of
        // `bun.memory.deinit`. If `Vec<u8>` (the `Vec<u8>` port) must keep
        // leaking for compat, gate its `Drop` there — not here.
        //
        // SAFETY: `node` was created via `heap::alloc` in `push`/`get` and
        // is exclusively owned by the caller. `data` is initialized: `destroy_node`
        // is only reached from `release()` (caller had a usable node, so `data`
        // was written) or `delete_all()` (free-list nodes, always initialized).
        unsafe {
            (*node).data.assume_init_drop();
            drop(bun_core::heap::take(node));
        }
    }
}

// ──────────────────────────────────────────────────────────────────────────
// object_pool! — declare per-instantiation storage
// ──────────────────────────────────────────────────────────────────────────

/// Declare an `ObjectPool` alias plus its backing static/thread-local storage.
///
/// ```ignore
/// // thread-local free list, capped at 32 nodes
/// object_pool!(pub StringVoidMapPool: StringVoidMap, threadsafe, 32);
/// // process-wide free list, uncapped
/// object_pool!(BufferPool: Vec<u8>, global, 0);
/// ```
///
/// Expands to a private storage struct implementing `PoolStorage<T>` and a
/// `pub type $Name = ObjectPool<$T, .., $Storage>` alias. `threadsafe` ⇒
/// `thread_local!` (one free list per thread); `global` ⇒ a single
/// process-wide `RefCell` (caller is responsible for not touching it from
/// multiple threads — matches the Zig `threadsafe = false` mode).
#[macro_export]
macro_rules! object_pool {
    ($vis:vis $name:ident : $ty:ty, threadsafe, $max:expr) => {
        $crate::object_pool!(@storage_tls $name, $ty);
        $vis type $name = $crate::pool::ObjectPool<
            $ty, true, { $max }, $crate::__paste_storage!($name)
        >;
    };
    ($vis:vis $name:ident : $ty:ty, global, $max:expr) => {
        $crate::object_pool!(@storage_global $name, $ty);
        $vis type $name = $crate::pool::ObjectPool<
            $ty, false, { $max }, $crate::__paste_storage!($name)
        >;
    };
    (@storage_tls $name:ident, $ty:ty) => {
        $crate::__object_pool_storage! { $name, $ty, tls }
    };
    (@storage_global $name:ident, $ty:ty) => {
        $crate::__object_pool_storage! { $name, $ty, global }
    };
}

/// Internal: expand the storage struct + `PoolStorage` impl. Separate macro so
/// the storage type name can be derived from `$name` without `paste!`.
#[doc(hidden)]
#[macro_export]
macro_rules! __object_pool_storage {
    ($name:ident, $ty:ty, tls) => {
        #[allow(non_camel_case_types)]
        #[doc(hidden)]
        pub struct __ObjectPoolStorage;
        ::std::thread_local! {
            static __OBJECT_POOL_DATA: ::core::cell::RefCell<
                $crate::pool::DataStruct<$ty>
            > = ::core::cell::RefCell::new($crate::pool::DataStruct::default());
        }
        impl $crate::pool::PoolStorage<$ty> for __ObjectPoolStorage {
            fn with<R>(
                f: impl FnOnce(&::core::cell::RefCell<$crate::pool::DataStruct<$ty>>) -> R,
            ) -> R {
                __OBJECT_POOL_DATA.with(|cell| f(cell))
            }
        }
    };
    ($name:ident, $ty:ty, global) => {
        #[allow(non_camel_case_types)]
        #[doc(hidden)]
        pub struct __ObjectPoolStorage;
        impl $crate::pool::PoolStorage<$ty> for __ObjectPoolStorage {
            fn with<R>(
                f: impl FnOnce(&::core::cell::RefCell<$crate::pool::DataStruct<$ty>>) -> R,
            ) -> R {
                // PORT NOTE: Zig's `threadsafe = false` used a plain global
                // `var data`; Rust forbids non-`Sync` statics, so this still
                // expands to a thread-local. Single-threaded callers see the
                // same one cell; cross-thread callers get per-thread pools
                // (a slight behaviour difference, but safe).
                ::std::thread_local! {
                    static __OBJECT_POOL_DATA: ::core::cell::RefCell<
                        $crate::pool::DataStruct<$ty>
                    > = ::core::cell::RefCell::new($crate::pool::DataStruct::default());
                }
                __OBJECT_POOL_DATA.with(|cell| f(cell))
            }
        }
    };
}

/// Internal: name of the storage struct generated by `__object_pool_storage!`.
/// Kept simple (no `paste!` dep) by using a fixed name; callers must therefore
/// declare at most one pool per containing module. If that proves too
/// restrictive, swap this for `paste::paste!`.
#[doc(hidden)]
#[macro_export]
macro_rules! __paste_storage {
    ($name:ident) => {
        __ObjectPoolStorage
    };
}

// ──────────────────────────────────────────────────────────────────────────
// `ObjectPoolType` impls for `bun_core` types live here (trait owner) to
// avoid a `bun_core → bun_collections` dep cycle now that `MutableString`
// is in `bun_core` (post `bun_string` merge).
// ──────────────────────────────────────────────────────────────────────────

/// Zig: `Npm.Registry.BodyPool = ObjectPool(MutableString, MutableString.init2048, true, 8)`
/// (src/install/npm.zig). Init = `init2048`; reuse = `.reset()`.
impl ObjectPoolType for bun_core::MutableString {
    const INIT: Option<fn() -> Result<Self, Error>> =
        Some(|| bun_core::MutableString::init2048().map_err(Into::into));
    #[inline]
    fn reset(&mut self) {
        bun_core::MutableString::reset(self);
    }
}

// ported from: src/collections/pool.zig