From 43a97878ce14b72f0981164f87f2e35e14151312 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 11:22:09 +0200 Subject: Adding upstream version 110.0.1. Signed-off-by: Daniel Baumann --- servo/components/style/gecko_bindings/sugar/mod.rs | 13 + .../style/gecko_bindings/sugar/ns_com_ptr.rs | 25 ++ .../style/gecko_bindings/sugar/ns_compatibility.rs | 19 ++ .../gecko_bindings/sugar/ns_style_auto_array.rs | 84 +++++ .../style/gecko_bindings/sugar/ns_t_array.rs | 144 +++++++++ .../style/gecko_bindings/sugar/origin_flags.rs | 31 ++ .../style/gecko_bindings/sugar/ownership.rs | 348 +++++++++++++++++++++ .../style/gecko_bindings/sugar/refptr.rs | 326 +++++++++++++++++++ 8 files changed, 990 insertions(+) create mode 100644 servo/components/style/gecko_bindings/sugar/mod.rs create mode 100644 servo/components/style/gecko_bindings/sugar/ns_com_ptr.rs create mode 100644 servo/components/style/gecko_bindings/sugar/ns_compatibility.rs create mode 100644 servo/components/style/gecko_bindings/sugar/ns_style_auto_array.rs create mode 100644 servo/components/style/gecko_bindings/sugar/ns_t_array.rs create mode 100644 servo/components/style/gecko_bindings/sugar/origin_flags.rs create mode 100644 servo/components/style/gecko_bindings/sugar/ownership.rs create mode 100644 servo/components/style/gecko_bindings/sugar/refptr.rs (limited to 'servo/components/style/gecko_bindings/sugar') diff --git a/servo/components/style/gecko_bindings/sugar/mod.rs b/servo/components/style/gecko_bindings/sugar/mod.rs new file mode 100644 index 0000000000..00faf63ba6 --- /dev/null +++ b/servo/components/style/gecko_bindings/sugar/mod.rs @@ -0,0 +1,13 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! Rust sugar and convenience methods for Gecko types. + +mod ns_com_ptr; +mod ns_compatibility; +mod ns_style_auto_array; +mod ns_t_array; +pub mod origin_flags; +pub mod ownership; +pub mod refptr; diff --git a/servo/components/style/gecko_bindings/sugar/ns_com_ptr.rs b/servo/components/style/gecko_bindings/sugar/ns_com_ptr.rs new file mode 100644 index 0000000000..10f7604647 --- /dev/null +++ b/servo/components/style/gecko_bindings/sugar/ns_com_ptr.rs @@ -0,0 +1,25 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! Little helpers for `nsCOMPtr`. + +use crate::gecko_bindings::structs::nsCOMPtr; + +#[cfg(feature = "gecko_debug")] +impl nsCOMPtr { + /// Get this pointer as a raw pointer. + #[inline] + pub fn raw(&self) -> *mut T { + self.mRawPtr + } +} + +#[cfg(not(feature = "gecko_debug"))] +impl nsCOMPtr { + /// Get this pointer as a raw pointer. + #[inline] + pub fn raw(&self) -> *mut T { + self._base.mRawPtr as *mut _ + } +} diff --git a/servo/components/style/gecko_bindings/sugar/ns_compatibility.rs b/servo/components/style/gecko_bindings/sugar/ns_compatibility.rs new file mode 100644 index 0000000000..f4b81e9f79 --- /dev/null +++ b/servo/components/style/gecko_bindings/sugar/ns_compatibility.rs @@ -0,0 +1,19 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! Little helper for `nsCompatibility`. + +use crate::context::QuirksMode; +use crate::gecko_bindings::structs::nsCompatibility; + +impl From for QuirksMode { + #[inline] + fn from(mode: nsCompatibility) -> QuirksMode { + match mode { + nsCompatibility::eCompatibility_FullStandards => QuirksMode::NoQuirks, + nsCompatibility::eCompatibility_AlmostStandards => QuirksMode::LimitedQuirks, + nsCompatibility::eCompatibility_NavQuirks => QuirksMode::Quirks, + } + } +} diff --git a/servo/components/style/gecko_bindings/sugar/ns_style_auto_array.rs b/servo/components/style/gecko_bindings/sugar/ns_style_auto_array.rs new file mode 100644 index 0000000000..97992b3f76 --- /dev/null +++ b/servo/components/style/gecko_bindings/sugar/ns_style_auto_array.rs @@ -0,0 +1,84 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! Rust helpers for Gecko's `nsStyleAutoArray`. + +use crate::gecko_bindings::bindings::Gecko_EnsureStyleAnimationArrayLength; +use crate::gecko_bindings::bindings::Gecko_EnsureStyleTransitionArrayLength; +use crate::gecko_bindings::structs::nsStyleAutoArray; +use crate::gecko_bindings::structs::{StyleAnimation, StyleTransition}; +use std::iter::{once, Chain, IntoIterator, Once}; +use std::ops::{Index, IndexMut}; +use std::slice::{Iter, IterMut}; + +impl Index for nsStyleAutoArray { + type Output = T; + fn index(&self, index: usize) -> &T { + match index { + 0 => &self.mFirstElement, + _ => &self.mOtherElements[index - 1], + } + } +} + +impl IndexMut for nsStyleAutoArray { + fn index_mut(&mut self, index: usize) -> &mut T { + match index { + 0 => &mut self.mFirstElement, + _ => &mut self.mOtherElements[index - 1], + } + } +} + +impl nsStyleAutoArray { + /// Mutably iterate over the array elements. + pub fn iter_mut(&mut self) -> Chain, IterMut> { + once(&mut self.mFirstElement).chain(self.mOtherElements.iter_mut()) + } + + /// Iterate over the array elements. + pub fn iter(&self) -> Chain, Iter> { + once(&self.mFirstElement).chain(self.mOtherElements.iter()) + } + + /// Returns the length of the array. + /// + /// Note that often structs containing autoarrays will have additional + /// member fields that contain the length, which must be kept in sync. + pub fn len(&self) -> usize { + 1 + self.mOtherElements.len() + } +} + +impl nsStyleAutoArray { + /// Ensures that the array has length at least the given length. + pub fn ensure_len(&mut self, len: usize) { + unsafe { + Gecko_EnsureStyleAnimationArrayLength( + self as *mut nsStyleAutoArray as *mut _, + len, + ); + } + } +} + +impl nsStyleAutoArray { + /// Ensures that the array has length at least the given length. + pub fn ensure_len(&mut self, len: usize) { + unsafe { + Gecko_EnsureStyleTransitionArrayLength( + self as *mut nsStyleAutoArray as *mut _, + len, + ); + } + } +} + +impl<'a, T> IntoIterator for &'a mut nsStyleAutoArray { + type Item = &'a mut T; + type IntoIter = Chain, IterMut<'a, T>>; + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} diff --git a/servo/components/style/gecko_bindings/sugar/ns_t_array.rs b/servo/components/style/gecko_bindings/sugar/ns_t_array.rs new file mode 100644 index 0000000000..d10ed420dd --- /dev/null +++ b/servo/components/style/gecko_bindings/sugar/ns_t_array.rs @@ -0,0 +1,144 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! Rust helpers for Gecko's nsTArray. + +use crate::gecko_bindings::bindings; +use crate::gecko_bindings::structs::{nsTArray, nsTArrayHeader, CopyableTArray}; +use std::mem; +use std::ops::{Deref, DerefMut}; +use std::slice; + +impl Deref for nsTArray { + type Target = [T]; + + #[inline] + fn deref<'a>(&'a self) -> &'a [T] { + unsafe { slice::from_raw_parts(self.slice_begin(), self.header().mLength as usize) } + } +} + +impl DerefMut for nsTArray { + fn deref_mut<'a>(&'a mut self) -> &'a mut [T] { + unsafe { slice::from_raw_parts_mut(self.slice_begin(), self.header().mLength as usize) } + } +} + +impl nsTArray { + #[inline] + fn header<'a>(&'a self) -> &'a nsTArrayHeader { + debug_assert!(!self.mBuffer.is_null()); + unsafe { mem::transmute(self.mBuffer) } + } + + // unsafe, since header may be in shared static or something + unsafe fn header_mut<'a>(&'a mut self) -> &'a mut nsTArrayHeader { + debug_assert!(!self.mBuffer.is_null()); + + mem::transmute(self.mBuffer) + } + + #[inline] + unsafe fn slice_begin(&self) -> *mut T { + debug_assert!(!self.mBuffer.is_null()); + (self.mBuffer as *const nsTArrayHeader).offset(1) as *mut _ + } + + /// Ensures the array has enough capacity at least to hold `cap` elements. + /// + /// NOTE: This doesn't call the constructor on the values! + pub fn ensure_capacity(&mut self, cap: usize) { + if cap >= self.len() { + unsafe { + bindings::Gecko_EnsureTArrayCapacity( + self as *mut nsTArray as *mut _, + cap, + mem::size_of::(), + ) + } + } + } + + /// Clears the array storage without calling the destructor on the values. + #[inline] + pub unsafe fn clear(&mut self) { + if self.len() != 0 { + bindings::Gecko_ClearPODTArray( + self as *mut nsTArray as *mut _, + mem::size_of::(), + mem::align_of::(), + ); + } + } + + /// Clears a POD array. This is safe since copy types are memcopyable. + #[inline] + pub fn clear_pod(&mut self) + where + T: Copy, + { + unsafe { self.clear() } + } + + /// Resize and set the length of the array to `len`. + /// + /// unsafe because this may leave the array with uninitialized elements. + /// + /// This will not call constructors. If you need that, either manually add + /// bindings or run the typed `EnsureCapacity` call on the gecko side. + pub unsafe fn set_len(&mut self, len: u32) { + // this can leak + debug_assert!(len >= self.len() as u32); + if self.len() == len as usize { + return; + } + self.ensure_capacity(len as usize); + self.header_mut().mLength = len; + } + + /// Resizes an array containing only POD elements + /// + /// unsafe because this may leave the array with uninitialized elements. + /// + /// This will not leak since it only works on POD types (and thus doesn't assert) + pub unsafe fn set_len_pod(&mut self, len: u32) + where + T: Copy, + { + if self.len() == len as usize { + return; + } + self.ensure_capacity(len as usize); + let header = self.header_mut(); + header.mLength = len; + } + + /// Collects the given iterator into this array. + /// + /// Not unsafe because we won't leave uninitialized elements in the array. + pub fn assign_from_iter_pod(&mut self, iter: I) + where + T: Copy, + I: ExactSizeIterator + Iterator, + { + debug_assert!(iter.len() <= 0xFFFFFFFF); + unsafe { + self.set_len_pod(iter.len() as u32); + } + self.iter_mut().zip(iter).for_each(|(r, v)| *r = v); + } +} + +impl Deref for CopyableTArray { + type Target = nsTArray; + fn deref(&self) -> &Self::Target { + &self._base + } +} + +impl DerefMut for CopyableTArray { + fn deref_mut(&mut self) -> &mut nsTArray { + &mut self._base + } +} diff --git a/servo/components/style/gecko_bindings/sugar/origin_flags.rs b/servo/components/style/gecko_bindings/sugar/origin_flags.rs new file mode 100644 index 0000000000..e0f0981c5d --- /dev/null +++ b/servo/components/style/gecko_bindings/sugar/origin_flags.rs @@ -0,0 +1,31 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! Helper to iterate over `OriginFlags` bits. + +use crate::gecko_bindings::structs::OriginFlags; +use crate::stylesheets::OriginSet; + +/// Checks that the values for OriginFlags are the ones we expect. +pub fn assert_flags_match() { + use crate::stylesheets::origin::*; + debug_assert_eq!( + OriginFlags::UserAgent.0, + OriginSet::ORIGIN_USER_AGENT.bits() + ); + debug_assert_eq!(OriginFlags::Author.0, OriginSet::ORIGIN_AUTHOR.bits()); + debug_assert_eq!(OriginFlags::User.0, OriginSet::ORIGIN_USER.bits()); +} + +impl From for OriginSet { + fn from(flags: OriginFlags) -> Self { + Self::from_bits_truncate(flags.0) + } +} + +impl From for OriginFlags { + fn from(set: OriginSet) -> Self { + OriginFlags(set.bits()) + } +} diff --git a/servo/components/style/gecko_bindings/sugar/ownership.rs b/servo/components/style/gecko_bindings/sugar/ownership.rs new file mode 100644 index 0000000000..249134169f --- /dev/null +++ b/servo/components/style/gecko_bindings/sugar/ownership.rs @@ -0,0 +1,348 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! Helpers for different FFI pointer kinds that Gecko's FFI layer uses. + +use crate::gecko_bindings::structs::root::mozilla::detail::CopyablePtr; +use servo_arc::{Arc, RawOffsetArc}; +use std::marker::PhantomData; +use std::mem::{forget, transmute}; +use std::ops::{Deref, DerefMut}; +use std::ptr; + +/// Indicates that a given Servo type has a corresponding Gecko FFI type. +pub unsafe trait HasFFI: Sized + 'static { + /// The corresponding Gecko type that this rust type represents. + /// + /// See the examples in `components/style/gecko/conversions.rs`. + type FFIType: Sized; +} + +/// Indicates that a given Servo type has the same layout as the corresponding +/// `HasFFI::FFIType` type. +pub unsafe trait HasSimpleFFI: HasFFI { + #[inline] + /// Given a Servo-side reference, converts it to an FFI-safe reference which + /// can be passed to Gecko. + /// + /// &ServoType -> &GeckoType + fn as_ffi(&self) -> &Self::FFIType { + unsafe { transmute(self) } + } + #[inline] + /// Given a Servo-side mutable reference, converts it to an FFI-safe mutable + /// reference which can be passed to Gecko. + /// + /// &mut ServoType -> &mut GeckoType + fn as_ffi_mut(&mut self) -> &mut Self::FFIType { + unsafe { transmute(self) } + } + #[inline] + /// Given an FFI-safe reference obtained from Gecko converts it to a + /// Servo-side reference. + /// + /// &GeckoType -> &ServoType + fn from_ffi(ffi: &Self::FFIType) -> &Self { + unsafe { transmute(ffi) } + } + #[inline] + /// Given an FFI-safe mutable reference obtained from Gecko converts it to a + /// Servo-side mutable reference. + /// + /// &mut GeckoType -> &mut ServoType + fn from_ffi_mut(ffi: &mut Self::FFIType) -> &mut Self { + unsafe { transmute(ffi) } + } +} + +/// Indicates that the given Servo type is passed over FFI +/// as a Box +pub unsafe trait HasBoxFFI: HasSimpleFFI { + #[inline] + /// Converts a borrowed Arc to a borrowed FFI reference. + /// + /// &Arc -> &GeckoType + fn into_ffi(self: Box) -> Owned { + unsafe { transmute(self) } + } + + /// Drops an owned FFI pointer. This conceptually takes the + /// Owned, except it's a bit of a paint to do that without + /// much benefit. + #[inline] + unsafe fn drop_ffi(ptr: *mut Self::FFIType) { + let _ = Box::from_raw(ptr as *mut Self); + } +} + +/// Helper trait for conversions between FFI Strong/Borrowed types and Arcs +/// +/// Should be implemented by types which are passed over FFI as Arcs via Strong +/// and Borrowed. +/// +/// In this case, the FFIType is the rough equivalent of ArcInner. +pub unsafe trait HasArcFFI: HasFFI { + // these methods can't be on Borrowed because it leads to an unspecified + // impl parameter + /// Artificially increments the refcount of a (possibly null) borrowed Arc + /// over FFI. + unsafe fn addref_opt(ptr: Option<&Self::FFIType>) { + forget(Self::arc_from_borrowed(&ptr).clone()) + } + + /// Given a (possibly null) borrowed FFI reference, decrements the refcount. + /// Unsafe since it doesn't consume the backing Arc. Run it only when you + /// know that a strong reference to the backing Arc is disappearing + /// (usually on the C++ side) without running the Arc destructor. + unsafe fn release_opt(ptr: Option<&Self::FFIType>) { + if let Some(arc) = Self::arc_from_borrowed(&ptr) { + let _: RawOffsetArc<_> = ptr::read(arc as *const RawOffsetArc<_>); + } + } + + /// Artificially increments the refcount of a borrowed Arc over FFI. + unsafe fn addref(ptr: &Self::FFIType) { + forget(Self::as_arc(&ptr).clone()) + } + + /// Given a non-null borrowed FFI reference, decrements the refcount. + /// Unsafe since it doesn't consume the backing Arc. Run it only when you + /// know that a strong reference to the backing Arc is disappearing + /// (usually on the C++ side) without running the Arc destructor. + unsafe fn release(ptr: &Self::FFIType) { + let _: RawOffsetArc<_> = ptr::read(Self::as_arc(&ptr) as *const RawOffsetArc<_>); + } + #[inline] + /// Converts a borrowed FFI reference to a borrowed Arc. + /// + /// &GeckoType -> &Arc + fn as_arc<'a>(ptr: &'a &Self::FFIType) -> &'a RawOffsetArc { + unsafe { transmute::<&&Self::FFIType, &RawOffsetArc>(ptr) } + } + + #[inline] + /// Converts a borrowed Arc to a borrowed FFI reference. + /// + /// &Arc -> &GeckoType + fn arc_as_borrowed<'a>(arc: &'a RawOffsetArc) -> &'a &Self::FFIType { + unsafe { transmute::<&RawOffsetArc, &&Self::FFIType>(arc) } + } + + #[inline] + /// Converts a borrowed nullable FFI reference to a borrowed Arc. + /// + /// &GeckoType -> &Arc + fn arc_from_borrowed<'a>(ptr: &'a Option<&Self::FFIType>) -> Option<&'a RawOffsetArc> { + unsafe { + if let Some(ref reference) = *ptr { + Some(transmute::<&&Self::FFIType, &RawOffsetArc<_>>(reference)) + } else { + None + } + } + } +} + +/// Gecko-FFI-safe Arc (T is an ArcInner). +/// +/// This can be null. +/// +/// Leaks on drop. Please don't drop this. +#[repr(C)] +pub struct Strong { + ptr: *const GeckoType, + _marker: PhantomData, +} + +impl Strong { + #[inline] + /// Returns whether this reference is null. + pub fn is_null(&self) -> bool { + self.ptr.is_null() + } + + #[inline] + /// Given a non-null strong FFI reference, converts it into a servo-side + /// Arc. + /// + /// Panics on null. + /// + /// Strong -> Arc + pub fn into_arc(self) -> RawOffsetArc + where + ServoType: HasArcFFI, + { + self.into_arc_opt().unwrap() + } + + #[inline] + /// Given a strong FFI reference, + /// converts it into a servo-side Arc + /// Returns None on null. + /// + /// Strong -> Arc + pub fn into_arc_opt(self) -> Option> + where + ServoType: HasArcFFI, + { + if self.is_null() { + None + } else { + unsafe { Some(transmute(self)) } + } + } + + #[inline] + /// Given a reference to a strong FFI reference, converts it to a reference + /// to a servo-side Arc. + /// + /// Returns None on null. + /// + /// Strong -> Arc + pub fn as_arc_opt(&self) -> Option<&RawOffsetArc> + where + ServoType: HasArcFFI, + { + if self.is_null() { + None + } else { + unsafe { Some(transmute(self)) } + } + } + + #[inline] + /// Produces a null strong FFI reference. + pub fn null() -> Self { + unsafe { transmute(ptr::null::()) } + } +} + +/// A few helpers implemented on top of Arc to make it more +/// comfortable to use and write safe code with. +pub unsafe trait FFIArcHelpers { + /// The Rust FFI type that we're implementing methods for. + type Inner: HasArcFFI; + + /// Converts an Arc into a strong FFI reference. + /// + /// Arc -> Strong + fn into_strong(self) -> Strong<::FFIType>; + + /// Produces a borrowed FFI reference by borrowing an Arc. + /// + /// &Arc -> &GeckoType + /// + /// Then the `arc_as_borrowed` method can go away. + fn as_borrowed(&self) -> &::FFIType; +} + +unsafe impl FFIArcHelpers for RawOffsetArc { + type Inner = T; + + #[inline] + fn into_strong(self) -> Strong { + unsafe { transmute(self) } + } + + #[inline] + fn as_borrowed(&self) -> &T::FFIType { + unsafe { &*(&**self as *const T as *const T::FFIType) } + } +} + +unsafe impl FFIArcHelpers for Arc { + type Inner = T; + + #[inline] + fn into_strong(self) -> Strong { + Arc::into_raw_offset(self).into_strong() + } + + #[inline] + fn as_borrowed(&self) -> &T::FFIType { + unsafe { &*(&**self as *const T as *const T::FFIType) } + } +} + +#[repr(C)] +#[derive(Debug)] +/// Gecko-FFI-safe owned pointer. +/// +/// Cannot be null, and leaks on drop, so needs to be converted into a rust-side +/// `Box` before. +pub struct Owned { + ptr: *mut GeckoType, + _marker: PhantomData, +} + +impl Owned { + /// Converts this instance to a (non-null) instance of `OwnedOrNull`. + pub fn maybe(self) -> OwnedOrNull { + unsafe { transmute(self) } + } +} + +impl Deref for Owned { + type Target = GeckoType; + fn deref(&self) -> &GeckoType { + unsafe { &*self.ptr } + } +} + +impl DerefMut for Owned { + fn deref_mut(&mut self) -> &mut GeckoType { + unsafe { &mut *self.ptr } + } +} + +#[repr(C)] +/// Gecko-FFI-safe owned pointer. +/// +/// Can be null, and just as `Owned` leaks on `Drop`. +pub struct OwnedOrNull { + ptr: *mut GeckoType, + _marker: PhantomData, +} + +impl OwnedOrNull { + /// Returns a null pointer. + #[inline] + pub fn null() -> Self { + Self { + ptr: ptr::null_mut(), + _marker: PhantomData, + } + } + + /// Returns whether this pointer is null. + #[inline] + pub fn is_null(&self) -> bool { + self.ptr.is_null() + } + + /// Gets a immutable reference to the underlying Gecko type, or `None` if + /// null. + pub fn borrow(&self) -> Option<&GeckoType> { + unsafe { transmute(self) } + } + + /// Gets a mutable reference to the underlying Gecko type, or `None` if + /// null. + pub fn borrow_mut(&self) -> Option<&mut GeckoType> { + unsafe { transmute(self) } + } +} + +impl Deref for CopyablePtr { + type Target = T; + fn deref(&self) -> &Self::Target { + &self.mPtr + } +} + +impl DerefMut for CopyablePtr { + fn deref_mut<'a>(&'a mut self) -> &'a mut T { + &mut self.mPtr + } +} diff --git a/servo/components/style/gecko_bindings/sugar/refptr.rs b/servo/components/style/gecko_bindings/sugar/refptr.rs new file mode 100644 index 0000000000..d8c0cea0f2 --- /dev/null +++ b/servo/components/style/gecko_bindings/sugar/refptr.rs @@ -0,0 +1,326 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! A rust helper to ease the use of Gecko's refcounted types. + +use crate::gecko_bindings::sugar::ownership::HasArcFFI; +use crate::gecko_bindings::{bindings, structs}; +use crate::Atom; +use servo_arc::Arc; +use std::marker::PhantomData; +use std::ops::{Deref, DerefMut}; +use std::{fmt, mem, ptr}; + +/// Trait for all objects that have Addref() and Release +/// methods and can be placed inside RefPtr +pub unsafe trait RefCounted { + /// Bump the reference count. + fn addref(&self); + /// Decrease the reference count. + unsafe fn release(&self); +} + +/// Trait for types which can be shared across threads in RefPtr. +pub unsafe trait ThreadSafeRefCounted: RefCounted {} + +/// A custom RefPtr implementation to take into account Drop semantics and +/// a bit less-painful memory management. +pub struct RefPtr { + ptr: *mut T, + _marker: PhantomData, +} + +impl fmt::Debug for RefPtr { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("RefPtr { ")?; + self.ptr.fmt(f)?; + f.write_str("}") + } +} + +/// A RefPtr that we know is uniquely owned. +/// +/// This is basically Box, with the additional guarantee that the box can be +/// safely interpreted as a RefPtr (with refcount 1) +/// +/// This is useful when you wish to create a refptr and mutate it temporarily, +/// while it is still uniquely owned. +pub struct UniqueRefPtr(RefPtr); + +// There is no safe conversion from &T to RefPtr (like Gecko has) +// because this lets you break UniqueRefPtr's guarantee + +impl RefPtr { + /// Create a new RefPtr from an already addrefed pointer obtained from FFI. + /// + /// The pointer must be valid, non-null and have been addrefed. + pub unsafe fn from_addrefed(ptr: *mut T) -> Self { + debug_assert!(!ptr.is_null()); + RefPtr { + ptr: ptr, + _marker: PhantomData, + } + } + + /// Returns whether the current pointer is null. + pub fn is_null(&self) -> bool { + self.ptr.is_null() + } + + /// Returns a null pointer. + pub fn null() -> Self { + Self { + ptr: ptr::null_mut(), + _marker: PhantomData, + } + } + + /// Create a new RefPtr from a pointer obtained from FFI. + /// + /// This method calls addref() internally + pub unsafe fn new(ptr: *mut T) -> Self { + let ret = RefPtr { + ptr, + _marker: PhantomData, + }; + ret.addref(); + ret + } + + /// Produces an FFI-compatible RefPtr that can be stored in style structs. + /// + /// structs::RefPtr does not have a destructor, so this may leak + pub fn forget(self) -> structs::RefPtr { + let ret = structs::RefPtr { + mRawPtr: self.ptr, + _phantom_0: PhantomData, + }; + mem::forget(self); + ret + } + + /// Returns the raw inner pointer to be fed back into FFI. + pub fn get(&self) -> *mut T { + self.ptr + } + + /// Addref the inner data, obviously leaky on its own. + pub fn addref(&self) { + if !self.ptr.is_null() { + unsafe { + (*self.ptr).addref(); + } + } + } + + /// Release the inner data. + /// + /// Call only when the data actually needs releasing. + pub unsafe fn release(&self) { + if !self.ptr.is_null() { + (*self.ptr).release(); + } + } +} + +impl UniqueRefPtr { + /// Create a unique refptr from an already addrefed pointer obtained from + /// FFI. + /// + /// The refcount must be one. + /// + /// The pointer must be valid and non null + pub unsafe fn from_addrefed(ptr: *mut T) -> Self { + UniqueRefPtr(RefPtr::from_addrefed(ptr)) + } + + /// Convert to a RefPtr so that it can be used. + pub fn get(self) -> RefPtr { + self.0 + } +} + +impl Deref for RefPtr { + type Target = T; + fn deref(&self) -> &T { + debug_assert!(!self.ptr.is_null()); + unsafe { &*self.ptr } + } +} + +impl Deref for UniqueRefPtr { + type Target = T; + fn deref(&self) -> &T { + unsafe { &*self.0.ptr } + } +} + +impl DerefMut for UniqueRefPtr { + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *self.0.ptr } + } +} + +impl structs::RefPtr { + /// Produces a Rust-side RefPtr from an FFI RefPtr, bumping the refcount. + /// + /// Must be called on a valid, non-null structs::RefPtr. + pub unsafe fn to_safe(&self) -> RefPtr { + let r = RefPtr { + ptr: self.mRawPtr, + _marker: PhantomData, + }; + r.addref(); + r + } + /// Produces a Rust-side RefPtr, consuming the existing one (and not bumping + /// the refcount). + pub unsafe fn into_safe(self) -> RefPtr { + debug_assert!(!self.mRawPtr.is_null()); + RefPtr { + ptr: self.mRawPtr, + _marker: PhantomData, + } + } + + /// Replace a structs::RefPtr with a different one, appropriately + /// addref/releasing. + /// + /// Both `self` and `other` must be valid, but can be null. + /// + /// Safe when called on an aliased pointer because the refcount in that case + /// needs to be at least two. + pub unsafe fn set(&mut self, other: &Self) { + self.clear(); + if !other.mRawPtr.is_null() { + *self = other.to_safe().forget(); + } + } + + /// Clear an instance of the structs::RefPtr, by releasing + /// it and setting its contents to null. + /// + /// `self` must be valid, but can be null. + pub unsafe fn clear(&mut self) { + if !self.mRawPtr.is_null() { + (*self.mRawPtr).release(); + self.mRawPtr = ptr::null_mut(); + } + } + + /// Replace a `structs::RefPtr` with a `RefPtr`, + /// consuming the `RefPtr`, and releasing the old + /// value in `self` if necessary. + /// + /// `self` must be valid, possibly null. + pub fn set_move(&mut self, other: RefPtr) { + if !self.mRawPtr.is_null() { + unsafe { + (*self.mRawPtr).release(); + } + } + *self = other.forget(); + } +} + +impl structs::RefPtr { + /// Sets the contents to an `Arc`, releasing the old value in `self` if + /// necessary. + pub fn set_arc(&mut self, other: Arc) + where + U: HasArcFFI, + { + unsafe { + U::release_opt(self.mRawPtr.as_ref()); + } + self.set_arc_leaky(other); + } + + /// Sets the contents to an Arc + /// will leak existing contents + pub fn set_arc_leaky(&mut self, other: Arc) + where + U: HasArcFFI, + { + *self = unsafe { mem::transmute(Arc::into_raw_offset(other)) }; + } +} + +impl Drop for RefPtr { + fn drop(&mut self) { + unsafe { self.release() } + } +} + +impl Clone for RefPtr { + fn clone(&self) -> Self { + self.addref(); + RefPtr { + ptr: self.ptr, + _marker: PhantomData, + } + } +} + +impl PartialEq for RefPtr { + fn eq(&self, other: &Self) -> bool { + self.ptr == other.ptr + } +} + +unsafe impl Send for RefPtr {} +unsafe impl Sync for RefPtr {} + +macro_rules! impl_refcount { + ($t:ty, $addref:path, $release:path) => { + unsafe impl RefCounted for $t { + #[inline] + fn addref(&self) { + unsafe { $addref(self as *const _ as *mut _) } + } + + #[inline] + unsafe fn release(&self) { + $release(self as *const _ as *mut _) + } + } + }; +} + +// Companion of NS_DECL_THREADSAFE_FFI_REFCOUNTING. +// +// Gets you a free RefCounted impl implemented via FFI. +macro_rules! impl_threadsafe_refcount { + ($t:ty, $addref:path, $release:path) => { + impl_refcount!($t, $addref, $release); + unsafe impl ThreadSafeRefCounted for $t {} + }; +} + +impl_threadsafe_refcount!( + structs::mozilla::URLExtraData, + bindings::Gecko_AddRefURLExtraDataArbitraryThread, + bindings::Gecko_ReleaseURLExtraDataArbitraryThread +); +impl_threadsafe_refcount!( + structs::nsIURI, + bindings::Gecko_AddRefnsIURIArbitraryThread, + bindings::Gecko_ReleasensIURIArbitraryThread +); +impl_threadsafe_refcount!( + structs::SheetLoadDataHolder, + bindings::Gecko_AddRefSheetLoadDataHolderArbitraryThread, + bindings::Gecko_ReleaseSheetLoadDataHolderArbitraryThread +); + +#[inline] +unsafe fn addref_atom(atom: *mut structs::nsAtom) { + mem::forget(Atom::from_raw(atom)); +} + +#[inline] +unsafe fn release_atom(atom: *mut structs::nsAtom) { + let _ = Atom::from_addrefed(atom); +} +impl_threadsafe_refcount!(structs::nsAtom, addref_atom, release_atom); -- cgit v1.2.3