Skip to content

Commit

Permalink
Implement common traits for Layer, and add new method
Browse files Browse the repository at this point in the history
Debug, Clone, PartialEq, Eq, Hash, Default, Send and Sync.
  • Loading branch information
madsmtm committed Sep 4, 2024
1 parent d3f10bd commit 1e29935
Showing 1 changed file with 51 additions and 1 deletion.
52 changes: 51 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide), doc(cfg_hide(doc)))]
#![deny(unsafe_op_in_unsafe_fn)]

use core::ffi::c_void;
use core::hash;
use core::panic::{RefUnwindSafe, UnwindSafe};
use objc2::rc::Retained;
use objc2_quartz_core::CAMetalLayer;
use std::ffi::c_void;

#[cfg(any(target_os = "macos", doc))]
pub mod appkit;
Expand All @@ -14,12 +16,60 @@ pub mod appkit;
pub mod uikit;

/// A wrapper around [`CAMetalLayer`].
#[doc(alias = "CAMetalLayer")]
#[derive(Debug, Clone)]
pub struct Layer {
layer: Retained<CAMetalLayer>,
pre_existing: bool,
}

impl PartialEq for Layer {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.layer == other.layer
}
}

impl Eq for Layer {}

impl hash::Hash for Layer {
#[inline]
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.layer.hash(state);
}
}

impl Default for Layer {
#[inline]
fn default() -> Self {
Self::new()
}
}

// SAFETY: `CAMetalLayer` is thread safe, like most things in Core Animation, see:
// https://developer.apple.com/documentation/quartzcore/catransaction/1448267-lock?language=objc
// https://stackoverflow.com/questions/76250226/how-to-render-content-of-calayer-on-a-background-thread
//
// TODO(madsmtm): Move this to `objc2-quartz-core`.
unsafe impl Send for Layer {}
unsafe impl Sync for Layer {}

// Layer methods may panic, but that won't leave the layer in an invalid state.
//
// TODO(madsmtm): Move this to `objc2-quartz-core`.
impl UnwindSafe for Layer {}
impl RefUnwindSafe for Layer {}

impl Layer {
/// Create a new layer.
#[inline]
pub fn new() -> Self {
Self {
layer: unsafe { CAMetalLayer::new() },
pre_existing: false,
}
}

/// Get a pointer to the underlying [`CAMetalLayer`]. The pointer is valid
/// for at least as long as the [`Layer`] is valid, but can be extended by
/// retaining it.
Expand Down

0 comments on commit 1e29935

Please sign in to comment.