Skip to main content

servo_arc/
lib.rs

1// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! Fork of Arc for Servo. This has the following advantages over std::sync::Arc:
12//!
13//! * We don't waste storage on the weak reference count.
14//! * We don't do extra RMU operations to handle the possibility of weak references.
15//! * We can experiment with arena allocation (todo).
16//! * We can add methods to support our custom use cases [1].
17//! * We have support for dynamically-sized types (see from_header_and_iter).
18//! * We have support for thin arcs to unsized types (see ThinArc).
19//! * We have support for references to static data, which don't do any
20//!   refcounting.
21//!
22//! [1]: https://bugzilla.mozilla.org/show_bug.cgi?id=1360883
23
24// The semantics of `Arc` are already documented in the Rust docs, so we don't
25// duplicate those here.
26#![allow(missing_docs)]
27
28#[cfg(feature = "servo")]
29use serde::{Deserialize, Serialize};
30use stable_deref_trait::{CloneStableDeref, StableDeref};
31use std::alloc::{self, Layout};
32use std::borrow;
33use std::cmp::Ordering;
34use std::fmt;
35use std::hash::{Hash, Hasher};
36use std::marker::PhantomData;
37use std::mem::{self, align_of, size_of};
38use std::ops::{Deref, DerefMut};
39use std::os::raw::c_void;
40use std::process;
41use std::ptr;
42use std::sync::atomic;
43use std::sync::atomic::Ordering::{Acquire, Relaxed, Release};
44
45/// A soft limit on the amount of references that may be made to an `Arc`.
46///
47/// Going above this limit will abort your program (although not
48/// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references.
49const MAX_REFCOUNT: usize = isize::MAX as usize;
50
51/// Special refcount value that means the data is not reference counted,
52/// and that the `Arc` is really acting as a read-only static reference.
53const STATIC_REFCOUNT: usize = usize::MAX;
54
55/// An atomically reference counted shared pointer
56///
57/// See the documentation for [`Arc`] in the standard library. Unlike the
58/// standard library `Arc`, this `Arc` does not support weak reference counting.
59///
60/// See the discussion in https://github.com/rust-lang/rust/pull/60594 for the
61/// usage of PhantomData.
62///
63/// [`Arc`]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html
64///
65/// cbindgen:derive-eq=false
66/// cbindgen:derive-neq=false
67#[repr(C)]
68pub struct Arc<T: ?Sized> {
69    p: ptr::NonNull<ArcInner<T>>,
70    phantom: PhantomData<T>,
71}
72
73/// An `Arc` that is known to be uniquely owned
74///
75/// When `Arc`s are constructed, they are known to be
76/// uniquely owned. In such a case it is safe to mutate
77/// the contents of the `Arc`. Normally, one would just handle
78/// this by mutating the data on the stack before allocating the
79/// `Arc`, however it's possible the data is large or unsized
80/// and you need to heap-allocate it earlier in such a way
81/// that it can be freely converted into a regular `Arc` once you're
82/// done.
83///
84/// `UniqueArc` exists for this purpose, when constructed it performs
85/// the same allocations necessary for an `Arc`, however it allows mutable access.
86/// Once the mutation is finished, you can call `.shareable()` and get a regular `Arc`
87/// out of it.
88///
89/// Ignore the doctest below there's no way to skip building with refcount
90/// logging during doc tests (see rust-lang/rust#45599).
91///
92/// ```rust,ignore
93/// # use servo_arc::UniqueArc;
94/// let data = [1, 2, 3, 4, 5];
95/// let mut x = UniqueArc::new(data);
96/// x[4] = 7; // mutate!
97/// let y = x.shareable(); // y is an Arc<T>
98/// ```
99pub struct UniqueArc<T: ?Sized>(Arc<T>);
100
101impl<T> UniqueArc<T> {
102    #[inline]
103    /// Construct a new UniqueArc
104    pub fn new(data: T) -> Self {
105        UniqueArc(Arc::new(data))
106    }
107
108    /// Construct an uninitialized arc
109    #[inline]
110    pub fn new_uninit() -> UniqueArc<mem::MaybeUninit<T>> {
111        unsafe {
112            let layout = Layout::new::<ArcInner<mem::MaybeUninit<T>>>();
113            let ptr = alloc::alloc(layout);
114            let mut p = ptr::NonNull::new(ptr)
115                .unwrap_or_else(|| alloc::handle_alloc_error(layout))
116                .cast::<ArcInner<mem::MaybeUninit<T>>>();
117            ptr::write(&mut p.as_mut().count, atomic::AtomicUsize::new(1));
118            #[cfg(feature = "track_alloc_size")]
119            ptr::write(&mut p.as_mut().alloc_size, layout.size());
120
121            #[cfg(feature = "gecko_refcount_logging")]
122            {
123                NS_LogCtor(p.as_ptr() as *mut _, b"ServoArc\0".as_ptr() as *const _, 8)
124            }
125
126            UniqueArc(Arc {
127                p,
128                phantom: PhantomData,
129            })
130        }
131    }
132
133    #[inline]
134    /// Convert to a shareable Arc<T> once we're done mutating it
135    pub fn shareable(self) -> Arc<T> {
136        self.0
137    }
138}
139
140impl<T> UniqueArc<mem::MaybeUninit<T>> {
141    /// Convert to an initialized Arc.
142    #[inline]
143    pub unsafe fn assume_init(this: Self) -> UniqueArc<T> {
144        UniqueArc(Arc {
145            p: mem::ManuallyDrop::new(this).0.p.cast(),
146            phantom: PhantomData,
147        })
148    }
149}
150
151impl<T> Deref for UniqueArc<T> {
152    type Target = T;
153    fn deref(&self) -> &T {
154        &*self.0
155    }
156}
157
158impl<T> DerefMut for UniqueArc<T> {
159    fn deref_mut(&mut self) -> &mut T {
160        // We know this to be uniquely owned
161        unsafe { &mut (*self.0.ptr()).data }
162    }
163}
164
165unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
166unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
167
168/// The object allocated by an Arc<T>
169///
170/// See https://github.com/mozilla/cbindgen/issues/937 for the derive-{eq,neq}=false. But we don't
171/// use those anyways so we can just disable them.
172/// cbindgen:derive-eq=false
173/// cbindgen:derive-neq=false
174#[repr(C)]
175struct ArcInner<T: ?Sized> {
176    count: atomic::AtomicUsize,
177    // NOTE(emilio): This needs to be here so that HeaderSlice<> is deallocated properly if the
178    // allocator relies on getting the right Layout. We don't need to track the right alignment,
179    // since we know that statically.
180    //
181    // This member could be completely avoided once min_specialization feature is stable (by
182    // implementing a trait for HeaderSlice that gives you the right layout). For now, servo-only
183    // since Gecko doesn't need it (its allocator doesn't need the size for the alignments we care
184    // about). See https://github.com/rust-lang/rust/issues/31844.
185    #[cfg(feature = "track_alloc_size")]
186    alloc_size: usize,
187    data: T,
188}
189
190unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
191unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
192
193/// Computes the offset of the data field within ArcInner.
194fn data_offset<T>() -> usize {
195    let size = size_of::<ArcInner<()>>();
196    let align = align_of::<T>();
197    // https://github.com/rust-lang/rust/blob/1.36.0/src/libcore/alloc.rs#L187-L207
198    size.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1)
199}
200
201impl<T> Arc<T> {
202    /// Construct an `Arc<T>`
203    #[inline]
204    pub fn new(data: T) -> Self {
205        let layout = Layout::new::<ArcInner<T>>();
206        let p = unsafe {
207            let ptr = ptr::NonNull::new(alloc::alloc(layout))
208                .unwrap_or_else(|| alloc::handle_alloc_error(layout))
209                .cast::<ArcInner<T>>();
210            ptr::write(
211                ptr.as_ptr(),
212                ArcInner {
213                    count: atomic::AtomicUsize::new(1),
214                    #[cfg(feature = "track_alloc_size")]
215                    alloc_size: layout.size(),
216                    data,
217                },
218            );
219            ptr
220        };
221
222        #[cfg(feature = "gecko_refcount_logging")]
223        unsafe {
224            // FIXME(emilio): Would be so amazing to have
225            // std::intrinsics::type_name() around, so that we could also report
226            // a real size.
227            NS_LogCtor(p.as_ptr() as *mut _, b"ServoArc\0".as_ptr() as *const _, 8);
228        }
229
230        Arc {
231            p,
232            phantom: PhantomData,
233        }
234    }
235
236    /// Construct an intentionally-leaked arc.
237    #[inline]
238    pub fn new_leaked(data: T) -> Self {
239        let arc = Self::new(data);
240        arc.mark_as_intentionally_leaked();
241        arc
242    }
243
244    /// Convert the Arc<T> to a raw pointer, suitable for use across FFI
245    ///
246    /// Note: This returns a pointer to the data T, which is offset in the allocation.
247    #[inline]
248    pub fn into_raw(this: Self) -> *const T {
249        let ptr = unsafe { &((*this.ptr()).data) as *const _ };
250        mem::forget(this);
251        ptr
252    }
253
254    /// Reconstruct the Arc<T> from a raw pointer obtained from into_raw()
255    ///
256    /// Note: This raw pointer will be offset in the allocation and must be preceded
257    /// by the atomic count.
258    #[inline]
259    pub unsafe fn from_raw(ptr: *const T) -> Self {
260        // To find the corresponding pointer to the `ArcInner` we need
261        // to subtract the offset of the `data` field from the pointer.
262        let ptr = unsafe { (ptr as *const u8).sub(data_offset::<T>()) };
263        Arc {
264            p: unsafe { ptr::NonNull::new_unchecked(ptr as *mut ArcInner<T>) },
265            phantom: PhantomData,
266        }
267    }
268
269    /// Like from_raw, but returns an addrefed arc instead.
270    #[inline]
271    pub unsafe fn from_raw_addrefed(ptr: *const T) -> Self {
272        let arc = unsafe { Self::from_raw(ptr) };
273        mem::forget(arc.clone());
274        arc
275    }
276
277    /// Create a new static Arc<T> (one that won't reference count the object)
278    /// and place it in the allocation provided by the specified `alloc`
279    /// function.
280    ///
281    /// `alloc` must return a pointer into a static allocation suitable for
282    /// storing data with the `Layout` passed into it. The pointer returned by
283    /// `alloc` will not be freed.
284    #[inline]
285    pub unsafe fn new_static<F>(alloc: F, data: T) -> Arc<T>
286    where
287        F: FnOnce(Layout) -> *mut u8,
288    {
289        let layout = Layout::new::<ArcInner<T>>();
290        let ptr = alloc(layout) as *mut ArcInner<T>;
291
292        let x = ArcInner {
293            count: atomic::AtomicUsize::new(STATIC_REFCOUNT),
294            #[cfg(feature = "track_alloc_size")]
295            alloc_size: layout.size(),
296            data,
297        };
298
299        unsafe {
300            ptr::write(ptr, x);
301        }
302
303        Arc {
304            p: unsafe { ptr::NonNull::new_unchecked(ptr) },
305            phantom: PhantomData,
306        }
307    }
308
309    /// Produce a pointer to the data that can be converted back
310    /// to an Arc. This is basically an `&Arc<T>`, without the extra indirection.
311    /// It has the benefits of an `&T` but also knows about the underlying refcount
312    /// and can be converted into more `Arc<T>`s if necessary.
313    #[inline]
314    pub fn borrow_arc<'a>(&'a self) -> ArcBorrow<'a, T> {
315        ArcBorrow(&**self)
316    }
317
318    /// Returns the address on the heap of the Arc itself -- not the T within it -- for memory
319    /// reporting.
320    ///
321    /// If this is a static reference, this returns null.
322    pub fn heap_ptr(&self) -> *const c_void {
323        if self.inner().count.load(Relaxed) == STATIC_REFCOUNT {
324            ptr::null()
325        } else {
326            self.p.as_ptr() as *const ArcInner<T> as *const c_void
327        }
328    }
329}
330
331impl<T: ?Sized> Arc<T> {
332    #[inline]
333    fn inner(&self) -> &ArcInner<T> {
334        // This unsafety is ok because while this arc is alive we're guaranteed
335        // that the inner pointer is valid. Furthermore, we know that the
336        // `ArcInner` structure itself is `Sync` because the inner data is
337        // `Sync` as well, so we're ok loaning out an immutable pointer to these
338        // contents.
339        unsafe { &*self.ptr() }
340    }
341
342    #[inline(always)]
343    fn record_drop(&self) {
344        #[cfg(feature = "gecko_refcount_logging")]
345        unsafe {
346            NS_LogDtor(self.ptr() as *mut _, b"ServoArc\0".as_ptr() as *const _, 8);
347        }
348    }
349
350    /// Marks this `Arc` as intentionally leaked for the purposes of refcount
351    /// logging.
352    ///
353    /// It's a logic error to call this more than once, but it's not unsafe, as
354    /// it'd just report negative leaks.
355    ///
356    /// The allocation is expected to live for the rest of the process, so this
357    /// also marks it static: clone()/drop() then skip the atomic refcount
358    /// updates.
359    #[inline(always)]
360    pub fn mark_as_intentionally_leaked(&self) {
361        self.record_drop();
362        self.inner().count.store(STATIC_REFCOUNT, Relaxed);
363    }
364
365    // Non-inlined part of `drop`. Just invokes the destructor and calls the
366    // refcount logging machinery if enabled.
367    #[inline(never)]
368    unsafe fn drop_slow(&mut self) {
369        self.record_drop();
370        let inner = self.ptr();
371
372        unsafe {
373            let layout = Layout::for_value(&*inner);
374            #[cfg(feature = "track_alloc_size")]
375            let layout = Layout::from_size_align_unchecked((*inner).alloc_size, layout.align());
376
377            std::ptr::drop_in_place(inner);
378            alloc::dealloc(inner as *mut _, layout);
379        }
380    }
381
382    /// Test pointer equality between the two Arcs, i.e. they must be the _same_
383    /// allocation
384    #[inline]
385    pub fn ptr_eq(this: &Self, other: &Self) -> bool {
386        this.raw_ptr() == other.raw_ptr()
387    }
388
389    fn ptr(&self) -> *mut ArcInner<T> {
390        self.p.as_ptr()
391    }
392
393    /// Returns a raw ptr to the underlying allocation.
394    pub fn raw_ptr(&self) -> ptr::NonNull<()> {
395        self.p.cast()
396    }
397}
398
399#[cfg(feature = "gecko_refcount_logging")]
400unsafe extern "C" {
401    fn NS_LogCtor(
402        aPtr: *mut std::os::raw::c_void,
403        aTypeName: *const std::os::raw::c_char,
404        aSize: u32,
405    );
406    fn NS_LogDtor(
407        aPtr: *mut std::os::raw::c_void,
408        aTypeName: *const std::os::raw::c_char,
409        aSize: u32,
410    );
411}
412
413impl<T: ?Sized> Clone for Arc<T> {
414    #[inline]
415    fn clone(&self) -> Self {
416        // NOTE(emilio): If you change anything here, make sure that the
417        // implementation in layout/style/ServoStyleConstsInlines.h matches!
418        //
419        // Using a relaxed ordering to check for STATIC_REFCOUNT is safe, since
420        // `count` never changes between STATIC_REFCOUNT and other values.
421        if self.inner().count.load(Relaxed) != STATIC_REFCOUNT {
422            // Using a relaxed ordering is alright here, as knowledge of the
423            // original reference prevents other threads from erroneously deleting
424            // the object.
425            //
426            // As explained in the [Boost documentation][1], Increasing the
427            // reference counter can always be done with memory_order_relaxed: New
428            // references to an object can only be formed from an existing
429            // reference, and passing an existing reference from one thread to
430            // another must already provide any required synchronization.
431            //
432            // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
433            let old_size = self.inner().count.fetch_add(1, Relaxed);
434
435            // However we need to guard against massive refcounts in case someone
436            // is `mem::forget`ing Arcs. If we don't do this the count can overflow
437            // and users will use-after free. We racily saturate to `isize::MAX` on
438            // the assumption that there aren't ~2 billion threads incrementing
439            // the reference count at once. This branch will never be taken in
440            // any realistic program.
441            //
442            // We abort because such a program is incredibly degenerate, and we
443            // don't care to support it.
444            if old_size > MAX_REFCOUNT {
445                process::abort();
446            }
447        }
448
449        unsafe {
450            Arc {
451                p: ptr::NonNull::new_unchecked(self.ptr()),
452                phantom: PhantomData,
453            }
454        }
455    }
456}
457
458impl<T: ?Sized> Deref for Arc<T> {
459    type Target = T;
460
461    #[inline]
462    fn deref(&self) -> &T {
463        &self.inner().data
464    }
465}
466
467impl<T: Clone> Arc<T> {
468    /// Makes a mutable reference to the `Arc`, cloning if necessary
469    ///
470    /// This is functionally equivalent to [`Arc::make_mut`][mm] from the standard library.
471    ///
472    /// If this `Arc` is uniquely owned, `make_mut()` will provide a mutable
473    /// reference to the contents. If not, `make_mut()` will create a _new_ `Arc`
474    /// with a copy of the contents, update `this` to point to it, and provide
475    /// a mutable reference to its contents.
476    ///
477    /// This is useful for implementing copy-on-write schemes where you wish to
478    /// avoid copying things if your `Arc` is not shared.
479    ///
480    /// [mm]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.make_mut
481    #[inline]
482    pub fn make_mut(this: &mut Self) -> &mut T {
483        if !this.is_unique() {
484            // Another pointer exists; clone
485            *this = Arc::new((**this).clone());
486        }
487
488        unsafe {
489            // This unsafety is ok because we're guaranteed that the pointer
490            // returned is the *only* pointer that will ever be returned to T. Our
491            // reference count is guaranteed to be 1 at this point, and we required
492            // the Arc itself to be `mut`, so we're returning the only possible
493            // reference to the inner data.
494            &mut (*this.ptr()).data
495        }
496    }
497}
498
499impl<T: ?Sized> Arc<T> {
500    /// Provides mutable access to the contents _if_ the `Arc` is uniquely owned.
501    #[inline]
502    pub fn get_mut(this: &mut Self) -> Option<&mut T> {
503        if this.is_unique() {
504            unsafe {
505                // See make_mut() for documentation of the threadsafety here.
506                Some(&mut (*this.ptr()).data)
507            }
508        } else {
509            None
510        }
511    }
512
513    /// Whether or not the `Arc` is a static reference.
514    #[inline]
515    pub fn is_static(&self) -> bool {
516        // Using a relaxed ordering to check for STATIC_REFCOUNT is safe, since
517        // `count` never changes between STATIC_REFCOUNT and other values.
518        self.inner().count.load(Relaxed) == STATIC_REFCOUNT
519    }
520
521    /// Whether or not the `Arc` is uniquely owned (is the refcount 1?) and not
522    /// a static reference.
523    #[inline]
524    pub fn is_unique(&self) -> bool {
525        // See the extensive discussion in [1] for why this needs to be Acquire.
526        //
527        // [1] https://github.com/servo/servo/issues/21186
528        self.inner().count.load(Acquire) == 1
529    }
530}
531
532impl<T: ?Sized> Drop for Arc<T> {
533    #[inline]
534    fn drop(&mut self) {
535        // NOTE(emilio): If you change anything here, make sure that the
536        // implementation in layout/style/ServoStyleConstsInlines.h matches!
537        if self.is_static() {
538            return;
539        }
540
541        // Because `fetch_sub` is already atomic, we do not need to synchronize
542        // with other threads unless we are going to delete the object.
543        if self.inner().count.fetch_sub(1, Release) != 1 {
544            return;
545        }
546
547        // FIXME(bholley): Use the updated comment when [2] is merged.
548        //
549        // This load is needed to prevent reordering of use of the data and
550        // deletion of the data.  Because it is marked `Release`, the decreasing
551        // of the reference count synchronizes with this `Acquire` load. This
552        // means that use of the data happens before decreasing the reference
553        // count, which happens before this load, which happens before the
554        // deletion of the data.
555        //
556        // As explained in the [Boost documentation][1],
557        //
558        // > It is important to enforce any possible access to the object in one
559        // > thread (through an existing reference) to *happen before* deleting
560        // > the object in a different thread. This is achieved by a "release"
561        // > operation after dropping a reference (any access to the object
562        // > through this reference must obviously happened before), and an
563        // > "acquire" operation before deleting the object.
564        //
565        // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
566        // [2]: https://github.com/rust-lang/rust/pull/41714
567        self.inner().count.load(Acquire);
568
569        unsafe {
570            self.drop_slow();
571        }
572    }
573}
574
575impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
576    fn eq(&self, other: &Arc<T>) -> bool {
577        Self::ptr_eq(self, other) || *(*self) == *(*other)
578    }
579
580    fn ne(&self, other: &Arc<T>) -> bool {
581        !Self::ptr_eq(self, other) && *(*self) != *(*other)
582    }
583}
584
585impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
586    fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
587        (**self).partial_cmp(&**other)
588    }
589
590    fn lt(&self, other: &Arc<T>) -> bool {
591        *(*self) < *(*other)
592    }
593
594    fn le(&self, other: &Arc<T>) -> bool {
595        *(*self) <= *(*other)
596    }
597
598    fn gt(&self, other: &Arc<T>) -> bool {
599        *(*self) > *(*other)
600    }
601
602    fn ge(&self, other: &Arc<T>) -> bool {
603        *(*self) >= *(*other)
604    }
605}
606impl<T: ?Sized + Ord> Ord for Arc<T> {
607    fn cmp(&self, other: &Arc<T>) -> Ordering {
608        (**self).cmp(&**other)
609    }
610}
611impl<T: ?Sized + Eq> Eq for Arc<T> {}
612
613impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
614    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
615        fmt::Display::fmt(&**self, f)
616    }
617}
618
619impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
620    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
621        fmt::Debug::fmt(&**self, f)
622    }
623}
624
625impl<T: ?Sized> fmt::Pointer for Arc<T> {
626    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
627        fmt::Pointer::fmt(&self.ptr(), f)
628    }
629}
630
631impl<T: Default> Default for Arc<T> {
632    fn default() -> Arc<T> {
633        Arc::new(Default::default())
634    }
635}
636
637impl<T: ?Sized + Hash> Hash for Arc<T> {
638    fn hash<H: Hasher>(&self, state: &mut H) {
639        (**self).hash(state)
640    }
641}
642
643impl<T> From<T> for Arc<T> {
644    #[inline]
645    fn from(t: T) -> Self {
646        Arc::new(t)
647    }
648}
649
650impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
651    #[inline]
652    fn borrow(&self) -> &T {
653        &**self
654    }
655}
656
657impl<T: ?Sized> AsRef<T> for Arc<T> {
658    #[inline]
659    fn as_ref(&self) -> &T {
660        &**self
661    }
662}
663
664unsafe impl<T: ?Sized> StableDeref for Arc<T> {}
665unsafe impl<T: ?Sized> CloneStableDeref for Arc<T> {}
666
667#[cfg(feature = "servo")]
668impl<'de, T: Deserialize<'de>> Deserialize<'de> for Arc<T> {
669    fn deserialize<D>(deserializer: D) -> Result<Arc<T>, D::Error>
670    where
671        D: ::serde::de::Deserializer<'de>,
672    {
673        T::deserialize(deserializer).map(Arc::new)
674    }
675}
676
677#[cfg(feature = "servo")]
678impl<T: Serialize> Serialize for Arc<T> {
679    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
680    where
681        S: ::serde::ser::Serializer,
682    {
683        (**self).serialize(serializer)
684    }
685}
686
687/// Structure to allow Arc-managing some fixed-sized data and a variably-sized
688/// slice in a single allocation.
689///
690/// cbindgen:derive-eq=false
691/// cbindgen:derive-neq=false
692#[derive(Eq)]
693#[repr(C)]
694pub struct HeaderSlice<H, T> {
695    /// The fixed-sized data.
696    pub header: H,
697
698    /// The length of the slice at our end.
699    len: usize,
700
701    /// The dynamically-sized data.
702    data: [T; 0],
703}
704
705impl<H: PartialEq, T: PartialEq> PartialEq for HeaderSlice<H, T> {
706    fn eq(&self, other: &Self) -> bool {
707        self.header == other.header && self.slice() == other.slice()
708    }
709}
710
711impl<H, T> Drop for HeaderSlice<H, T> {
712    fn drop(&mut self) {
713        unsafe {
714            let mut ptr = self.data_mut();
715            for _ in 0..self.len {
716                std::ptr::drop_in_place(ptr);
717                ptr = ptr.offset(1);
718            }
719        }
720    }
721}
722
723impl<H: fmt::Debug, T: fmt::Debug> fmt::Debug for HeaderSlice<H, T> {
724    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
725        f.debug_struct("HeaderSlice")
726            .field("header", &self.header)
727            .field("slice", &self.slice())
728            .finish()
729    }
730}
731
732impl<H, T> HeaderSlice<H, T> {
733    /// Returns the dynamically sized slice in this HeaderSlice.
734    #[inline(always)]
735    pub fn slice(&self) -> &[T] {
736        unsafe { std::slice::from_raw_parts(self.data(), self.len) }
737    }
738
739    #[inline(always)]
740    fn data(&self) -> *const T {
741        std::ptr::addr_of!(self.data) as *const _
742    }
743
744    #[inline(always)]
745    fn data_mut(&mut self) -> *mut T {
746        std::ptr::addr_of_mut!(self.data) as *mut _
747    }
748
749    /// Returns the dynamically sized slice in this HeaderSlice.
750    #[inline(always)]
751    pub fn slice_mut(&mut self) -> &mut [T] {
752        unsafe { std::slice::from_raw_parts_mut(self.data_mut(), self.len) }
753    }
754
755    /// Returns the len of the slice.
756    #[inline(always)]
757    pub fn len(&self) -> usize {
758        self.len
759    }
760}
761
762impl<H, T> Arc<HeaderSlice<H, T>> {
763    /// Creates an Arc for a HeaderSlice using the given header struct and
764    /// iterator to generate the slice.
765    ///
766    /// `is_static` indicates whether to create a static Arc.
767    ///
768    /// `alloc` is used to get a pointer to the memory into which the
769    /// dynamically sized ArcInner<HeaderSlice<H, T>> value will be
770    /// written.  If `is_static` is true, then `alloc` must return a
771    /// pointer into some static memory allocation.  If it is false,
772    /// then `alloc` must return an allocation that can be dellocated
773    /// by calling Box::from_raw::<ArcInner<HeaderSlice<H, T>>> on it.
774    #[inline]
775    pub fn from_header_and_iter_alloc<F, I>(
776        alloc: F,
777        header: H,
778        mut items: I,
779        num_items: usize,
780        is_static: bool,
781    ) -> Self
782    where
783        F: FnOnce(Layout) -> *mut u8,
784        I: Iterator<Item = T>,
785    {
786        assert_ne!(size_of::<T>(), 0, "Need to think about ZST");
787
788        let layout = Layout::new::<ArcInner<HeaderSlice<H, T>>>();
789        debug_assert!(layout.align() >= align_of::<T>());
790        debug_assert!(layout.align() >= align_of::<usize>());
791        let array_layout = Layout::array::<T>(num_items).expect("Overflow");
792        let (layout, _offset) = layout.extend(array_layout).expect("Overflow");
793        let p = unsafe {
794            // Allocate the buffer.
795            let buffer = alloc(layout);
796            let mut p = ptr::NonNull::new(buffer)
797                .unwrap_or_else(|| alloc::handle_alloc_error(layout))
798                .cast::<ArcInner<HeaderSlice<H, T>>>();
799
800            // Write the data.
801            //
802            // Note that any panics here (i.e. from the iterator) are safe, since
803            // we'll just leak the uninitialized memory.
804            let count = if is_static {
805                atomic::AtomicUsize::new(STATIC_REFCOUNT)
806            } else {
807                atomic::AtomicUsize::new(1)
808            };
809            ptr::write(&mut p.as_mut().count, count);
810            #[cfg(feature = "track_alloc_size")]
811            ptr::write(&mut p.as_mut().alloc_size, layout.size());
812            ptr::write(&mut p.as_mut().data.header, header);
813            ptr::write(&mut p.as_mut().data.len, num_items);
814            if num_items != 0 {
815                let mut current = std::ptr::addr_of_mut!(p.as_mut().data.data) as *mut T;
816                for _ in 0..num_items {
817                    ptr::write(
818                        current,
819                        items
820                            .next()
821                            .expect("ExactSizeIterator over-reported length"),
822                    );
823                    current = current.offset(1);
824                }
825                // We should have consumed the buffer exactly, maybe accounting
826                // for some padding from the alignment.
827                debug_assert!(
828                    (buffer.add(layout.size()) as usize - current as *mut u8 as usize)
829                        < layout.align()
830                );
831            }
832            assert!(
833                items.next().is_none(),
834                "ExactSizeIterator under-reported length"
835            );
836            p
837        };
838        #[cfg(feature = "gecko_refcount_logging")]
839        unsafe {
840            if !is_static {
841                // FIXME(emilio): Would be so amazing to have
842                // std::intrinsics::type_name() around.
843                NS_LogCtor(p.as_ptr() as *mut _, b"ServoArc\0".as_ptr() as *const _, 8)
844            }
845        }
846
847        // Return the fat Arc.
848        assert_eq!(
849            size_of::<Self>(),
850            size_of::<usize>(),
851            "The Arc should be thin"
852        );
853
854        Arc {
855            p,
856            phantom: PhantomData,
857        }
858    }
859
860    /// Creates an Arc for a HeaderSlice using the given header struct and iterator to generate the
861    /// slice. Panics if num_items doesn't match the number of items.
862    #[inline]
863    pub fn from_header_and_iter_with_size<I>(header: H, items: I, num_items: usize) -> Self
864    where
865        I: Iterator<Item = T>,
866    {
867        Arc::from_header_and_iter_alloc(
868            |layout| unsafe { alloc::alloc(layout) },
869            header,
870            items,
871            num_items,
872            /* is_static = */ false,
873        )
874    }
875
876    /// Creates an Arc for a HeaderSlice using the given header struct and
877    /// iterator to generate the slice. The resulting Arc will be fat.
878    #[inline]
879    pub fn from_header_and_iter<I>(header: H, items: I) -> Self
880    where
881        I: Iterator<Item = T> + ExactSizeIterator,
882    {
883        let len = items.len();
884        Self::from_header_and_iter_with_size(header, items, len)
885    }
886}
887
888/// This is functionally equivalent to Arc<(H, [T])>
889///
890/// When you create an `Arc` containing a dynamically sized type like a slice, the `Arc` is
891/// represented on the stack as a "fat pointer", where the length of the slice is stored alongside
892/// the `Arc`'s pointer. In some situations you may wish to have a thin pointer instead, perhaps
893/// for FFI compatibility or space efficiency. `ThinArc` solves this by storing the length in the
894/// allocation itself, via `HeaderSlice`.
895pub type ThinArc<H, T> = Arc<HeaderSlice<H, T>>;
896
897/// See `ArcUnion`. This is a version that works for `ThinArc`s.
898pub type ThinArcUnion<H1, T1, H2, T2> = ArcUnion<HeaderSlice<H1, T1>, HeaderSlice<H2, T2>>;
899
900impl<H, T> UniqueArc<HeaderSlice<H, T>> {
901    #[inline]
902    pub fn from_header_and_iter<I>(header: H, items: I) -> Self
903    where
904        I: Iterator<Item = T> + ExactSizeIterator,
905    {
906        Self(Arc::from_header_and_iter(header, items))
907    }
908
909    #[inline]
910    pub fn from_header_and_iter_with_size<I>(header: H, items: I, num_items: usize) -> Self
911    where
912        I: Iterator<Item = T>,
913    {
914        Self(Arc::from_header_and_iter_with_size(
915            header, items, num_items,
916        ))
917    }
918
919    /// Returns a mutable reference to the header.
920    pub fn header_mut(&mut self) -> &mut H {
921        // We know this to be uniquely owned
922        unsafe { &mut (*self.0.ptr()).data.header }
923    }
924
925    /// Returns a mutable reference to the slice.
926    pub fn data_mut(&mut self) -> &mut [T] {
927        // We know this to be uniquely owned
928        unsafe { (*self.0.ptr()).data.slice_mut() }
929    }
930}
931
932/// A "borrowed `Arc`". This is a pointer to
933/// a T that is known to have been allocated within an
934/// `Arc`.
935///
936/// This is equivalent in guarantees to `&Arc<T>`, however it is
937/// a bit more flexible. To obtain an `&Arc<T>` you must have
938/// an `Arc<T>` instance somewhere pinned down until we're done with it.
939/// It's also a direct pointer to `T`, so using this involves less pointer-chasing
940///
941/// However, C++ code may hand us refcounted things as pointers to T directly,
942/// so we have to conjure up a temporary `Arc` on the stack each time.
943///
944/// `ArcBorrow` lets us deal with borrows of known-refcounted objects
945/// without needing to worry about where the `Arc<T>` is.
946#[derive(Debug, Eq, PartialEq)]
947pub struct ArcBorrow<'a, T: 'a>(&'a T);
948
949impl<'a, T> Copy for ArcBorrow<'a, T> {}
950impl<'a, T> Clone for ArcBorrow<'a, T> {
951    #[inline]
952    fn clone(&self) -> Self {
953        *self
954    }
955}
956
957impl<'a, T> ArcBorrow<'a, T> {
958    /// Clone this as an `Arc<T>`. This bumps the refcount.
959    #[inline]
960    pub fn clone_arc(&self) -> Arc<T> {
961        let arc = unsafe { Arc::from_raw(self.0) };
962        // addref it!
963        mem::forget(arc.clone());
964        arc
965    }
966
967    /// For constructing from a reference known to be Arc-backed,
968    /// e.g. if we obtain such a reference over FFI
969    #[inline]
970    pub unsafe fn from_ref(r: &'a T) -> Self {
971        ArcBorrow(r)
972    }
973
974    /// Compare two `ArcBorrow`s via pointer equality. Will only return
975    /// true if they come from the same allocation
976    pub fn ptr_eq(this: &Self, other: &Self) -> bool {
977        this.0 as *const T == other.0 as *const T
978    }
979
980    /// Temporarily converts |self| into a bonafide Arc and exposes it to the
981    /// provided callback. The refcount is not modified.
982    #[inline]
983    pub fn with_arc<F, U>(&self, f: F) -> U
984    where
985        F: FnOnce(&Arc<T>) -> U,
986        T: 'static,
987    {
988        // Synthesize transient Arc, which never touches the refcount.
989        let transient = unsafe { mem::ManuallyDrop::new(Arc::from_raw(self.0)) };
990
991        // Expose the transient Arc to the callback, which may clone it if it wants.
992        let result = f(&transient);
993
994        // Forward the result.
995        result
996    }
997
998    /// Similar to deref, but uses the lifetime |a| rather than the lifetime of
999    /// self, which is incompatible with the signature of the Deref trait.
1000    #[inline]
1001    pub fn get(&self) -> &'a T {
1002        self.0
1003    }
1004}
1005
1006impl<'a, T> Deref for ArcBorrow<'a, T> {
1007    type Target = T;
1008
1009    #[inline]
1010    fn deref(&self) -> &T {
1011        self.0
1012    }
1013}
1014
1015/// A tagged union that can represent `Arc<A>` or `Arc<B>` while only consuming a
1016/// single word. The type is also `NonNull`, and thus can be stored in an Option
1017/// without increasing size.
1018///
1019/// This is functionally equivalent to
1020/// `enum ArcUnion<A, B> { First(Arc<A>), Second(Arc<B>)` but only takes up
1021/// up a single word of stack space.
1022///
1023/// This could probably be extended to support four types if necessary.
1024pub struct ArcUnion<A, B> {
1025    p: ptr::NonNull<()>,
1026    phantom_a: PhantomData<A>,
1027    phantom_b: PhantomData<B>,
1028}
1029
1030unsafe impl<A: Sync + Send, B: Send + Sync> Send for ArcUnion<A, B> {}
1031unsafe impl<A: Sync + Send, B: Send + Sync> Sync for ArcUnion<A, B> {}
1032
1033impl<A: PartialEq, B: PartialEq> PartialEq for ArcUnion<A, B> {
1034    fn eq(&self, other: &Self) -> bool {
1035        use crate::ArcUnionBorrow::*;
1036        match (self.borrow(), other.borrow()) {
1037            (First(x), First(y)) => x == y,
1038            (Second(x), Second(y)) => x == y,
1039            (_, _) => false,
1040        }
1041    }
1042}
1043
1044impl<A: Eq, B: Eq> Eq for ArcUnion<A, B> {}
1045
1046/// This represents a borrow of an `ArcUnion`.
1047#[derive(Debug)]
1048pub enum ArcUnionBorrow<'a, A: 'a, B: 'a> {
1049    First(ArcBorrow<'a, A>),
1050    Second(ArcBorrow<'a, B>),
1051}
1052
1053impl<A, B> ArcUnion<A, B> {
1054    unsafe fn new(ptr: *mut ()) -> Self {
1055        ArcUnion {
1056            p: unsafe { ptr::NonNull::new_unchecked(ptr) },
1057            phantom_a: PhantomData,
1058            phantom_b: PhantomData,
1059        }
1060    }
1061
1062    /// Returns true if the two values are pointer-equal.
1063    #[inline]
1064    pub fn ptr_eq(this: &Self, other: &Self) -> bool {
1065        this.p == other.p
1066    }
1067
1068    #[inline]
1069    pub fn ptr(&self) -> ptr::NonNull<()> {
1070        self.p
1071    }
1072
1073    /// Returns an enum representing a borrow of either A or B.
1074    #[inline]
1075    pub fn borrow(&self) -> ArcUnionBorrow<'_, A, B> {
1076        if self.is_first() {
1077            let ptr = self.p.as_ptr() as *const ArcInner<A>;
1078            let borrow = unsafe { ArcBorrow::from_ref(&(*ptr).data) };
1079            ArcUnionBorrow::First(borrow)
1080        } else {
1081            let ptr = ((self.p.as_ptr() as usize) & !0x1) as *const ArcInner<B>;
1082            let borrow = unsafe { ArcBorrow::from_ref(&(*ptr).data) };
1083            ArcUnionBorrow::Second(borrow)
1084        }
1085    }
1086
1087    /// Creates an `ArcUnion` from an instance of the first type.
1088    pub fn from_first(other: Arc<A>) -> Self {
1089        let union = unsafe { Self::new(other.ptr() as *mut _) };
1090        mem::forget(other);
1091        union
1092    }
1093
1094    /// Creates an `ArcUnion` from an instance of the second type.
1095    pub fn from_second(other: Arc<B>) -> Self {
1096        let union = unsafe { Self::new(((other.ptr() as usize) | 0x1) as *mut _) };
1097        mem::forget(other);
1098        union
1099    }
1100
1101    /// Returns true if this `ArcUnion` contains the first type.
1102    pub fn is_first(&self) -> bool {
1103        self.p.as_ptr() as usize & 0x1 == 0
1104    }
1105
1106    /// Returns true if this `ArcUnion` contains the second type.
1107    pub fn is_second(&self) -> bool {
1108        !self.is_first()
1109    }
1110
1111    /// Returns a borrow of the first type if applicable, otherwise `None`.
1112    pub fn as_first(&self) -> Option<ArcBorrow<'_, A>> {
1113        match self.borrow() {
1114            ArcUnionBorrow::First(x) => Some(x),
1115            ArcUnionBorrow::Second(_) => None,
1116        }
1117    }
1118
1119    /// Returns a borrow of the second type if applicable, otherwise None.
1120    pub fn as_second(&self) -> Option<ArcBorrow<'_, B>> {
1121        match self.borrow() {
1122            ArcUnionBorrow::First(_) => None,
1123            ArcUnionBorrow::Second(x) => Some(x),
1124        }
1125    }
1126}
1127
1128impl<A, B> Clone for ArcUnion<A, B> {
1129    fn clone(&self) -> Self {
1130        match self.borrow() {
1131            ArcUnionBorrow::First(x) => ArcUnion::from_first(x.clone_arc()),
1132            ArcUnionBorrow::Second(x) => ArcUnion::from_second(x.clone_arc()),
1133        }
1134    }
1135}
1136
1137impl<A, B> Drop for ArcUnion<A, B> {
1138    fn drop(&mut self) {
1139        match self.borrow() {
1140            ArcUnionBorrow::First(x) => unsafe {
1141                let _ = Arc::from_raw(&*x);
1142            },
1143            ArcUnionBorrow::Second(x) => unsafe {
1144                let _ = Arc::from_raw(&*x);
1145            },
1146        }
1147    }
1148}
1149
1150impl<A: fmt::Debug, B: fmt::Debug> fmt::Debug for ArcUnion<A, B> {
1151    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1152        fmt::Debug::fmt(&self.borrow(), f)
1153    }
1154}
1155
1156#[cfg(test)]
1157mod tests {
1158    use super::{Arc, ThinArc};
1159    use std::clone::Clone;
1160    use std::ops::Drop;
1161    use std::sync::atomic;
1162    use std::sync::atomic::Ordering::{Acquire, SeqCst};
1163
1164    #[derive(PartialEq)]
1165    struct Canary(*mut atomic::AtomicUsize);
1166
1167    impl Drop for Canary {
1168        fn drop(&mut self) {
1169            unsafe {
1170                (*self.0).fetch_add(1, SeqCst);
1171            }
1172        }
1173    }
1174
1175    #[test]
1176    fn empty_thin() {
1177        let x = Arc::from_header_and_iter(100u32, std::iter::empty::<i32>());
1178        assert_eq!(x.header, 100);
1179        assert!(x.slice().is_empty());
1180    }
1181
1182    #[test]
1183    fn thin_assert_padding() {
1184        #[derive(Clone, Default)]
1185        #[repr(C)]
1186        struct Padded {
1187            i: u16,
1188        }
1189
1190        // The header will have more alignment than `Padded`
1191        let items = vec![Padded { i: 0xdead }, Padded { i: 0xbeef }];
1192        let a = ThinArc::from_header_and_iter(0i32, items.into_iter());
1193        assert_eq!(a.len(), 2);
1194        assert_eq!(a.slice()[0].i, 0xdead);
1195        assert_eq!(a.slice()[1].i, 0xbeef);
1196    }
1197
1198    #[test]
1199    fn slices_and_thin() {
1200        let mut canary = atomic::AtomicUsize::new(0);
1201        let c = Canary(&mut canary as *mut atomic::AtomicUsize);
1202        let v = vec![5, 6];
1203        {
1204            let x = Arc::from_header_and_iter(c, v.into_iter());
1205            let _ = x.clone();
1206            let _ = x == x;
1207        }
1208        assert_eq!(canary.load(Acquire), 1);
1209    }
1210}