summaryrefslogtreecommitdiffstats
path: root/servo/components/style/gecko_bindings/sugar
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-07 09:22:09 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-07 09:22:09 +0000
commit43a97878ce14b72f0981164f87f2e35e14151312 (patch)
tree620249daf56c0258faa40cbdcf9cfba06de2a846 /servo/components/style/gecko_bindings/sugar
parentInitial commit. (diff)
downloadfirefox-43a97878ce14b72f0981164f87f2e35e14151312.tar.xz
firefox-43a97878ce14b72f0981164f87f2e35e14151312.zip
Adding upstream version 110.0.1.upstream/110.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'servo/components/style/gecko_bindings/sugar')
-rw-r--r--servo/components/style/gecko_bindings/sugar/mod.rs13
-rw-r--r--servo/components/style/gecko_bindings/sugar/ns_com_ptr.rs25
-rw-r--r--servo/components/style/gecko_bindings/sugar/ns_compatibility.rs19
-rw-r--r--servo/components/style/gecko_bindings/sugar/ns_style_auto_array.rs84
-rw-r--r--servo/components/style/gecko_bindings/sugar/ns_t_array.rs144
-rw-r--r--servo/components/style/gecko_bindings/sugar/origin_flags.rs31
-rw-r--r--servo/components/style/gecko_bindings/sugar/ownership.rs348
-rw-r--r--servo/components/style/gecko_bindings/sugar/refptr.rs326
8 files changed, 990 insertions, 0 deletions
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<T> nsCOMPtr<T> {
+ /// Get this pointer as a raw pointer.
+ #[inline]
+ pub fn raw<U>(&self) -> *mut T {
+ self.mRawPtr
+ }
+}
+
+#[cfg(not(feature = "gecko_debug"))]
+impl nsCOMPtr {
+ /// Get this pointer as a raw pointer.
+ #[inline]
+ pub fn raw<T>(&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<nsCompatibility> 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<T> Index<usize> for nsStyleAutoArray<T> {
+ type Output = T;
+ fn index(&self, index: usize) -> &T {
+ match index {
+ 0 => &self.mFirstElement,
+ _ => &self.mOtherElements[index - 1],
+ }
+ }
+}
+
+impl<T> IndexMut<usize> for nsStyleAutoArray<T> {
+ fn index_mut(&mut self, index: usize) -> &mut T {
+ match index {
+ 0 => &mut self.mFirstElement,
+ _ => &mut self.mOtherElements[index - 1],
+ }
+ }
+}
+
+impl<T> nsStyleAutoArray<T> {
+ /// Mutably iterate over the array elements.
+ pub fn iter_mut(&mut self) -> Chain<Once<&mut T>, IterMut<T>> {
+ once(&mut self.mFirstElement).chain(self.mOtherElements.iter_mut())
+ }
+
+ /// Iterate over the array elements.
+ pub fn iter(&self) -> Chain<Once<&T>, Iter<T>> {
+ 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<StyleAnimation> {
+ /// 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<StyleAnimation> as *mut _,
+ len,
+ );
+ }
+ }
+}
+
+impl nsStyleAutoArray<StyleTransition> {
+ /// 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<StyleTransition> as *mut _,
+ len,
+ );
+ }
+ }
+}
+
+impl<'a, T> IntoIterator for &'a mut nsStyleAutoArray<T> {
+ type Item = &'a mut T;
+ type IntoIter = Chain<Once<&'a mut T>, 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<T> Deref for nsTArray<T> {
+ 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<T> DerefMut for nsTArray<T> {
+ 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<T> nsTArray<T> {
+ #[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<T> as *mut _,
+ cap,
+ mem::size_of::<T>(),
+ )
+ }
+ }
+ }
+
+ /// 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<T> as *mut _,
+ mem::size_of::<T>(),
+ mem::align_of::<T>(),
+ );
+ }
+ }
+
+ /// 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<I>(&mut self, iter: I)
+ where
+ T: Copy,
+ I: ExactSizeIterator + Iterator<Item = T>,
+ {
+ 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<T> Deref for CopyableTArray<T> {
+ type Target = nsTArray<T>;
+ fn deref(&self) -> &Self::Target {
+ &self._base
+ }
+}
+
+impl<T> DerefMut for CopyableTArray<T> {
+ fn deref_mut(&mut self) -> &mut nsTArray<T> {
+ &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<OriginFlags> for OriginSet {
+ fn from(flags: OriginFlags) -> Self {
+ Self::from_bits_truncate(flags.0)
+ }
+}
+
+impl From<OriginSet> 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<ServoType> -> &GeckoType
+ fn into_ffi(self: Box<Self>) -> Owned<Self::FFIType> {
+ unsafe { transmute(self) }
+ }
+
+ /// Drops an owned FFI pointer. This conceptually takes the
+ /// Owned<Self::FFIType>, 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<Self>.
+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<ServoType>
+ fn as_arc<'a>(ptr: &'a &Self::FFIType) -> &'a RawOffsetArc<Self> {
+ unsafe { transmute::<&&Self::FFIType, &RawOffsetArc<Self>>(ptr) }
+ }
+
+ #[inline]
+ /// Converts a borrowed Arc to a borrowed FFI reference.
+ ///
+ /// &Arc<ServoType> -> &GeckoType
+ fn arc_as_borrowed<'a>(arc: &'a RawOffsetArc<Self>) -> &'a &Self::FFIType {
+ unsafe { transmute::<&RawOffsetArc<Self>, &&Self::FFIType>(arc) }
+ }
+
+ #[inline]
+ /// Converts a borrowed nullable FFI reference to a borrowed Arc.
+ ///
+ /// &GeckoType -> &Arc<ServoType>
+ fn arc_from_borrowed<'a>(ptr: &'a Option<&Self::FFIType>) -> Option<&'a RawOffsetArc<Self>> {
+ 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<GeckoType> {
+ ptr: *const GeckoType,
+ _marker: PhantomData<GeckoType>,
+}
+
+impl<GeckoType> Strong<GeckoType> {
+ #[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<GeckoType> -> Arc<ServoType>
+ pub fn into_arc<ServoType>(self) -> RawOffsetArc<ServoType>
+ where
+ ServoType: HasArcFFI<FFIType = GeckoType>,
+ {
+ self.into_arc_opt().unwrap()
+ }
+
+ #[inline]
+ /// Given a strong FFI reference,
+ /// converts it into a servo-side Arc
+ /// Returns None on null.
+ ///
+ /// Strong<GeckoType> -> Arc<ServoType>
+ pub fn into_arc_opt<ServoType>(self) -> Option<RawOffsetArc<ServoType>>
+ where
+ ServoType: HasArcFFI<FFIType = GeckoType>,
+ {
+ 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<GeckoType> -> Arc<ServoType>
+ pub fn as_arc_opt<ServoType>(&self) -> Option<&RawOffsetArc<ServoType>>
+ where
+ ServoType: HasArcFFI<FFIType = GeckoType>,
+ {
+ 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::<GeckoType>()) }
+ }
+}
+
+/// A few helpers implemented on top of Arc<ServoType> 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<ServoType> -> Strong<GeckoType>
+ fn into_strong(self) -> Strong<<Self::Inner as HasFFI>::FFIType>;
+
+ /// Produces a borrowed FFI reference by borrowing an Arc.
+ ///
+ /// &Arc<ServoType> -> &GeckoType
+ ///
+ /// Then the `arc_as_borrowed` method can go away.
+ fn as_borrowed(&self) -> &<Self::Inner as HasFFI>::FFIType;
+}
+
+unsafe impl<T: HasArcFFI> FFIArcHelpers for RawOffsetArc<T> {
+ type Inner = T;
+
+ #[inline]
+ fn into_strong(self) -> Strong<T::FFIType> {
+ unsafe { transmute(self) }
+ }
+
+ #[inline]
+ fn as_borrowed(&self) -> &T::FFIType {
+ unsafe { &*(&**self as *const T as *const T::FFIType) }
+ }
+}
+
+unsafe impl<T: HasArcFFI> FFIArcHelpers for Arc<T> {
+ type Inner = T;
+
+ #[inline]
+ fn into_strong(self) -> Strong<T::FFIType> {
+ 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<GeckoType> {
+ ptr: *mut GeckoType,
+ _marker: PhantomData<GeckoType>,
+}
+
+impl<GeckoType> Owned<GeckoType> {
+ /// Converts this instance to a (non-null) instance of `OwnedOrNull`.
+ pub fn maybe(self) -> OwnedOrNull<GeckoType> {
+ unsafe { transmute(self) }
+ }
+}
+
+impl<GeckoType> Deref for Owned<GeckoType> {
+ type Target = GeckoType;
+ fn deref(&self) -> &GeckoType {
+ unsafe { &*self.ptr }
+ }
+}
+
+impl<GeckoType> DerefMut for Owned<GeckoType> {
+ 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<GeckoType> {
+ ptr: *mut GeckoType,
+ _marker: PhantomData<GeckoType>,
+}
+
+impl<GeckoType> OwnedOrNull<GeckoType> {
+ /// 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<T> Deref for CopyablePtr<T> {
+ type Target = T;
+ fn deref(&self) -> &Self::Target {
+ &self.mPtr
+ }
+}
+
+impl<T> DerefMut for CopyablePtr<T> {
+ 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<T>
+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<T: RefCounted> {
+ ptr: *mut T,
+ _marker: PhantomData<T>,
+}
+
+impl<T: RefCounted> fmt::Debug for RefPtr<T> {
+ 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<T>, with the additional guarantee that the box can be
+/// safely interpreted as a RefPtr<T> (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<T: RefCounted>(RefPtr<T>);
+
+// There is no safe conversion from &T to RefPtr<T> (like Gecko has)
+// because this lets you break UniqueRefPtr's guarantee
+
+impl<T: RefCounted> RefPtr<T> {
+ /// 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<T> {
+ 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<T: RefCounted> UniqueRefPtr<T> {
+ /// 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<T> {
+ self.0
+ }
+}
+
+impl<T: RefCounted> Deref for RefPtr<T> {
+ type Target = T;
+ fn deref(&self) -> &T {
+ debug_assert!(!self.ptr.is_null());
+ unsafe { &*self.ptr }
+ }
+}
+
+impl<T: RefCounted> Deref for UniqueRefPtr<T> {
+ type Target = T;
+ fn deref(&self) -> &T {
+ unsafe { &*self.0.ptr }
+ }
+}
+
+impl<T: RefCounted> DerefMut for UniqueRefPtr<T> {
+ fn deref_mut(&mut self) -> &mut T {
+ unsafe { &mut *self.0.ptr }
+ }
+}
+
+impl<T: RefCounted> structs::RefPtr<T> {
+ /// Produces a Rust-side RefPtr from an FFI RefPtr, bumping the refcount.
+ ///
+ /// Must be called on a valid, non-null structs::RefPtr<T>.
+ pub unsafe fn to_safe(&self) -> RefPtr<T> {
+ 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<T> {
+ debug_assert!(!self.mRawPtr.is_null());
+ RefPtr {
+ ptr: self.mRawPtr,
+ _marker: PhantomData,
+ }
+ }
+
+ /// Replace a structs::RefPtr<T> 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<T>, 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<T>` with a `RefPtr<T>`,
+ /// consuming the `RefPtr<T>`, and releasing the old
+ /// value in `self` if necessary.
+ ///
+ /// `self` must be valid, possibly null.
+ pub fn set_move(&mut self, other: RefPtr<T>) {
+ if !self.mRawPtr.is_null() {
+ unsafe {
+ (*self.mRawPtr).release();
+ }
+ }
+ *self = other.forget();
+ }
+}
+
+impl<T> structs::RefPtr<T> {
+ /// Sets the contents to an `Arc<T>`, releasing the old value in `self` if
+ /// necessary.
+ pub fn set_arc<U>(&mut self, other: Arc<U>)
+ where
+ U: HasArcFFI<FFIType = T>,
+ {
+ unsafe {
+ U::release_opt(self.mRawPtr.as_ref());
+ }
+ self.set_arc_leaky(other);
+ }
+
+ /// Sets the contents to an Arc<T>
+ /// will leak existing contents
+ pub fn set_arc_leaky<U>(&mut self, other: Arc<U>)
+ where
+ U: HasArcFFI<FFIType = T>,
+ {
+ *self = unsafe { mem::transmute(Arc::into_raw_offset(other)) };
+ }
+}
+
+impl<T: RefCounted> Drop for RefPtr<T> {
+ fn drop(&mut self) {
+ unsafe { self.release() }
+ }
+}
+
+impl<T: RefCounted> Clone for RefPtr<T> {
+ fn clone(&self) -> Self {
+ self.addref();
+ RefPtr {
+ ptr: self.ptr,
+ _marker: PhantomData,
+ }
+ }
+}
+
+impl<T: RefCounted> PartialEq for RefPtr<T> {
+ fn eq(&self, other: &Self) -> bool {
+ self.ptr == other.ptr
+ }
+}
+
+unsafe impl<T: ThreadSafeRefCounted> Send for RefPtr<T> {}
+unsafe impl<T: ThreadSafeRefCounted> Sync for RefPtr<T> {}
+
+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);