bun_ptr 0.1.5

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
//! "Copy on write" slice. There are many instances when it is desired to re-use
//! a slice, but doing so would make it unknown if that slice should be freed.
//! This structure, in release builds, is the same size as `&[T]`, but
//! stores one bit for if deinitialization should free the underlying memory.
//!
//! ```ignore
//! let str = CowSlice::<u8>::init_owned(Box::<[u8]>::from(b"hello!".as_slice()));
//! let borrow = str.borrow();
//! assert!(borrow.slice().as_ptr() == str.slice().as_ptr());
//! drop(borrow); // knows it is borrowed, no free
//! drop(str);    // calls free
//! ```
//!
//! In a debug build, there are aggressive assertions to ensure unintentional
//! frees do not happen. But in a release build, the developer is expected to
//! keep slice owners alive beyond the lifetimes of the borrowed instances.
//!
//! CowSlice does not support slices longer than `2^(usize::BITS - 1)`.

#[cfg(debug_assertions)]
use core::ptr::NonNull;

use bun_alloc::AllocError;

/// "Copy on write" slice. See module docs.
pub type CowSlice<T> = CowSliceZ<T, false>;

/// "Copy on write" slice with optional sentinel termination. See module docs.
///
/// `Z = true` means the backing storage has a sentinel element at `[len]`
/// (the sentinel value is assumed to be the zero value of `T`).
// TODO(port): Zig's `comptime sentinel: ?T` allowed an arbitrary sentinel value;
// Rust const generics cannot express `Option<T>` for generic `T`, so this port
// uses a `bool` and assumes sentinel == 0 when `Z`. Revisit if a non-zero
// sentinel is ever needed.
pub struct CowSliceZ<T: 'static, const Z: bool> {
    /// Pointer to the underlying data. Do not access this directly.
    ///
    /// NOTE: `ptr` is logically const if data is borrowed.
    ptr: *mut T,
    flags: Flags,
    #[cfg(debug_assertions)]
    debug: Option<NonNull<DebugData>>,
}

/// `packed struct(usize) { len: u(BITS-1), is_owned: bool }`
#[repr(transparent)]
#[derive(Clone, Copy)]
struct Flags(usize);

impl Flags {
    const IS_OWNED_BIT: usize = 1 << (usize::BITS - 1);
    const LEN_MASK: usize = !Self::IS_OWNED_BIT;

    #[inline]
    const fn new(len: usize, is_owned: bool) -> Self {
        debug_assert!(len <= Self::LEN_MASK);
        Self((len & Self::LEN_MASK) | if is_owned { Self::IS_OWNED_BIT } else { 0 })
    }

    #[inline]
    const fn len(self) -> usize {
        self.0 & Self::LEN_MASK
    }

    #[inline]
    const fn is_owned(self) -> bool {
        self.0 & Self::IS_OWNED_BIT != 0
    }

    #[inline]
    fn set_len(&mut self, len: usize) {
        debug_assert!(len <= Self::LEN_MASK);
        self.0 = (self.0 & Self::IS_OWNED_BIT) | (len & Self::LEN_MASK);
    }

    #[inline]
    fn set_is_owned(&mut self, v: bool) {
        if v {
            self.0 |= Self::IS_OWNED_BIT;
        } else {
            self.0 &= Self::LEN_MASK;
        }
    }
}

impl<T: 'static, const Z: bool> CowSliceZ<T, Z> {
    // T: 'static needed for `EMPTY` (init_static takes &'static [T]). All
    // concrete uses (u8, u16, Index, ...) satisfy this; relax if a borrowed-T
    // case ever appears.
    pub const EMPTY: Self = Self::init_static(&[]);

    /// Debug-only accessor for the heap-allocated borrow-tracking data.
    ///
    /// Single `unsafe` deref site for the set-once `Option<NonNull<DebugData>>`
    /// field; `borrow` / `into_owned` / `Drop` go through this instead of
    /// repeating the raw deref at each call site.
    #[cfg(debug_assertions)]
    #[inline]
    fn debug_data(&self) -> Option<&DebugData> {
        // SAFETY: `self.debug` is `Some` only when populated by `init_owned` /
        // `into_owned` with a fresh `heap::alloc`ed box. Owned cows free it
        // exclusively in `Drop`; borrowed cows share the owner's box, which by
        // API contract outlives every borrow. The returned `&DebugData` is tied
        // to `&self` and so cannot dangle past the `CowSliceZ` itself.
        self.debug.map(|d| unsafe { d.as_ref() })
    }

    // TODO(port): Zig exposed `pub const Slice` / `SliceMut` associated type
    // aliases that switched on `sentinel` (`[:z]const T` vs `[]const T`). Rust
    // has no inherent associated type aliases; callers use `&[T]` / `&mut [T]`
    // directly. For `Z = true` the NUL is at `slice()[len]` in backing storage.

    /// Create a new Cow that owns its allocation.
    ///
    /// `data` is transferred into the returned string, and must be freed with
    /// `Drop` when the string and its borrows are done being used.
    pub fn init_owned(data: Box<[T]>) -> Self {
        // PORT NOTE: Zig asserted ownership at runtime via a debug allocator
        // wrapper. In Rust the `Box<[T]>` type already proves unique ownership.
        let len = data.len();
        let ptr = bun_core::heap::into_raw(data).cast::<T>();
        Self {
            ptr,
            flags: Flags::new(len, true),
            #[cfg(debug_assertions)]
            debug: Some(DebugData::new_boxed()),
        }
    }

    /// Create a new Cow that copies `data` into a new allocation.
    pub fn init_dupe(data: &[T]) -> Result<Self, AllocError>
    where
        T: Clone + Default,
    {
        // TODO(port): `allocator.dupeZ(T, data)` for `Z = true` — must allocate
        // len+1 with a trailing zero sentinel. `Vec::into_boxed_slice` shrinks
        // capacity to len, so the sentinel cannot live in spare capacity; the
        // Box must hold len+1 and `Flags::len`/`Drop`/`take_slice` must be
        // Z-aware (free len+1, expose len). Stubbed to plain dupe for now —
        // sentinel is NOT preserved.
        let bytes: Box<[T]> = Box::<[T]>::from(data);
        Ok(Self::init_owned(bytes))
    }

    /// Create a Cow that wraps a static slice.
    ///
    /// `Drop` is safe to call, but will have no effect.
    pub const fn init_static(data: &'static [T]) -> Self {
        Self {
            // SAFETY: const semantics are enforced by is_owned flag
            ptr: data.as_ptr().cast_mut(),
            flags: Flags::new(data.len(), false),
            #[cfg(debug_assertions)]
            debug: None,
        }
    }

    /// Returns `true` if this string owns its data.
    #[inline]
    pub fn is_owned(&self) -> bool {
        self.flags.is_owned()
    }

    /// Borrow this Cow's slice.
    pub fn slice(&self) -> &[T] {
        // SAFETY: `ptr` is valid for `len` elements for the lifetime of `self`.
        unsafe { core::slice::from_raw_parts(self.ptr, self.flags.len()) }
    }

    #[inline]
    pub fn length(&self) -> usize {
        self.flags.len()
    }

    /// Mutably borrow this `Cow`'s slice.
    ///
    /// Borrowed `Cow`s will be automatically converted to owned, incurring
    /// an allocation.
    pub fn slice_mut(&mut self) -> Result<&mut [T], AllocError>
    where
        T: Clone + Default,
    {
        if !self.is_owned() {
            self.into_owned()?;
        }
        // SAFETY: owned ⇒ `ptr` is uniquely owned and valid for `len` elements.
        Ok(unsafe { core::slice::from_raw_parts_mut(self.ptr, self.flags.len()) })
    }

    /// Mutably borrow this `Cow`'s slice, assuming it already owns its data.
    /// Calling this on a borrowed `Cow` invokes safety-checked Illegal Behavior.
    pub fn slice_mut_unsafe(&mut self) -> &mut [T] {
        debug_assert!(
            self.is_owned(),
            "CowSlice.slice_mut_unsafe cannot be called on Cows that borrow their data."
        );
        // SAFETY: caller contract — `self` is owned.
        unsafe { core::slice::from_raw_parts_mut(self.ptr, self.flags.len()) }
    }

    /// Take ownership over this string's allocation. `self` is left in a
    /// valid, empty state.
    ///
    /// Caller owns the returned memory and must deinitialize it when done.
    /// `self` may be re-used. An allocation will be incurred if and only if
    /// `self` is not owned.
    pub fn take_slice(&mut self) -> Result<Box<[T]>, AllocError>
    where
        T: Clone + Default,
    {
        if !self.is_owned() {
            self.into_owned()?;
        }
        let ptr = self.ptr;
        let len = self.flags.len();
        #[cfg(debug_assertions)]
        if self.is_owned() {
            if let Some(d) = self.debug.take() {
                // SAFETY: `d` was created via `heap::alloc` in `init_owned`/`into_owned`.
                drop(unsafe { bun_core::heap::take(d.as_ptr()) });
            }
        }
        // Zig: `defer str.* = Self.empty` — a *bitwise* overwrite. In Rust,
        // `*self = Self::EMPTY` would run `Drop` on the old value first and
        // free the very `ptr[..len]` allocation we are about to hand back.
        // `ManuallyDrop::new(mem::replace(..))` resets `self` without dropping.
        let _ = core::mem::ManuallyDrop::new(core::mem::replace(self, Self::EMPTY));
        // SAFETY: owned ⇒ `ptr[..len]` was produced by `heap::alloc`.
        Ok(unsafe { bun_core::heap::take(core::ptr::slice_from_raw_parts_mut(ptr, len)) })
    }

    /// Returns a new string that borrows this string's data.
    ///
    /// The borrowed string should be dropped so that debug assertions
    /// that perform `borrows` checks are performed.
    pub fn borrow(&self) -> Self {
        #[cfg(debug_assertions)]
        if let Some(debug) = self.debug_data() {
            let mut borrows = debug.mutex.lock();
            *borrows += 1;
        }
        Self {
            ptr: self.ptr,
            flags: Flags::new(self.flags.len(), false),
            #[cfg(debug_assertions)]
            debug: self.debug,
        }
    }

    /// Returns a new string that borrows a subslice of this string.
    ///
    /// This is the Cow-equivalent of `&str[start..end]`.
    ///
    /// When `end` is `None`, the subslice will end at the end of the string.
    /// `end` must be less than or equal to `self.len`, and greater than or
    /// equal to `start`. The borrowed string should be dropped so that debug
    /// assertions get performed.
    pub fn borrow_subslice(&self, start: usize, end: Option<usize>) -> Self {
        let end_ = end.unwrap_or(self.flags.len());
        // TODO(port): Zig's sentinel-aware `str.ptr[start..end_ :s]` asserted
        // the sentinel is present at `end_`. No equivalent check here.
        let mut result = self.borrow();
        // SAFETY: const semantics are enforced by is_owned flag; `start <= end_ <= len`.
        result.ptr = unsafe { self.ptr.add(start) };
        result.flags.set_len(end_ - start);
        result
    }

    /// Make this Cow `owned` by duplicating its borrowed data. Does nothing
    /// if the Cow is already owned.
    pub fn to_owned(&mut self) -> Result<(), AllocError>
    where
        T: Clone + Default,
    {
        if !self.is_owned() {
            self.into_owned()?;
        }
        Ok(())
    }

    /// Make this Cow `owned` by duplicating its borrowed data. Panics if
    /// the Cow is already owned.
    #[inline(always)]
    fn into_owned(&mut self) -> Result<(), AllocError>
    where
        T: Clone + Default,
    {
        debug_assert!(!self.is_owned());

        // TODO(port): `allocator.dupeZ` for `Z = true` — see `init_dupe`.
        // Sentinel is NOT preserved in this stub.
        let bytes: Box<[T]> = Box::<[T]>::from(self.slice());
        self.ptr = bun_core::heap::into_raw(bytes).cast::<T>();
        // flags.len already correct (unchanged)
        self.flags.set_is_owned(true);

        #[cfg(debug_assertions)]
        {
            if let Some(dbg) = self.debug_data() {
                let mut borrows = dbg.mutex.lock();
                debug_assert!(*borrows > 0);
                *borrows -= 1;
                drop(borrows);
                self.debug = None;
            }
            self.debug = Some(DebugData::new_boxed());
        }

        Ok(())
    }
}

impl<T: 'static, const Z: bool> Drop for CowSliceZ<T, Z> {
    /// Free this `Cow`'s allocation if it is owned.
    ///
    /// In debug builds, dropping borrowed strings performs debug
    /// checks. In release builds it is a no-op.
    fn drop(&mut self) {
        #[cfg(debug_assertions)]
        if let Some(dbg) = self.debug_data() {
            // PORT NOTE: Zig asserted `debug.allocator.vtable == allocator.vtable`
            // here. With a single global allocator that check is moot.
            if self.is_owned() {
                let borrows = dbg.mutex.lock();
                // active borrows become invalid data
                debug_assert!(
                    *borrows == 0,
                    "Cannot drop a CowSlice with active borrows. Current borrow count: {}",
                    *borrows
                );
                drop(borrows);
                // SAFETY: owned ⇒ we created this via `heap::alloc`.
                drop(unsafe { bun_core::heap::take(self.debug.unwrap().as_ptr()) });
            } else {
                let mut borrows = dbg.mutex.lock();
                *borrows -= 1; // double deinit of a borrowed string would underflow
            }
        }
        if self.flags.is_owned() {
            // SAFETY: owned ⇒ `ptr[..len]` came from `heap::alloc`.
            drop(unsafe {
                bun_core::heap::take(core::ptr::slice_from_raw_parts_mut(
                    self.ptr,
                    self.flags.len(),
                ))
            });
        }
    }
}

impl<const Z: bool> core::fmt::Display for CowSliceZ<u8, Z> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        // PORT NOTE: Zig `writer.writeAll(str.slice())` wrote raw bytes.
        // `BStr` gives lossy Display over `[u8]` without UTF-8 validation.
        core::fmt::Display::fmt(bstr::BStr::new(self.slice()), f)
    }
}

#[cfg(debug_assertions)]
struct DebugData {
    /// Guards `borrows` (number of active borrows).
    // PORT NOTE: Zig used `bun.Mutex` with `borrows` as a separate field;
    // folded into the mutex payload here. `bun_core::Mutex` (poison-free
    // `std::sync` wrapper) is used because `bun_ptr` sits below `bun_threading`.
    mutex: bun_core::Mutex<usize>,
}

#[cfg(debug_assertions)]
impl DebugData {
    fn new_boxed() -> NonNull<Self> {
        bun_core::heap::into_raw_nn(Box::new(Self {
            mutex: bun_core::Mutex::new(0),
        }))
    }
}

// `comptime` size assertion: CowSlice should be the same size as a native slice
// (modulo the debug pointer).
#[cfg(not(debug_assertions))]
const _: () = assert!(
    core::mem::size_of::<CowSlice<u8>>() == core::mem::size_of::<&[u8]>(),
    "CowSlice should be the same size as a native slice"
);
#[cfg(debug_assertions)]
const _: () = assert!(
    core::mem::size_of::<CowSlice<u8>>() - core::mem::size_of::<Option<NonNull<DebugData>>>()
        == core::mem::size_of::<&[u8]>(),
    "CowSlice should be the same size as a native slice"
);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cow_slice() {
        let mut str = CowSlice::<u8>::init_static(b"hello");
        assert!(!str.is_owned());
        assert_eq!(str.slice(), b"hello");

        let borrow = str.borrow();
        assert!(!borrow.is_owned());
        assert_eq!(borrow.slice(), b"hello");

        str.to_owned().unwrap();
        assert!(str.is_owned());
        assert_eq!(str.slice(), b"hello");

        drop(str);

        // borrow is unaffected by str being dropped
        assert_eq!(borrow.slice(), b"hello");
    }
}

// ported from: src/ptr/CowSlice.zig