From nobody Fri Feb 13 17:29:18 2026 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id D9474E7D0AE for ; Thu, 21 Sep 2023 21:48:10 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S231849AbjIUVsO (ORCPT ); Thu, 21 Sep 2023 17:48:14 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:49978 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232350AbjIUVrx (ORCPT ); Thu, 21 Sep 2023 17:47:53 -0400 Received: from mail-pl1-x636.google.com (mail-pl1-x636.google.com [IPv6:2607:f8b0:4864:20::636]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 3CFD94A30D; Thu, 21 Sep 2023 14:35:03 -0700 (PDT) Received: by mail-pl1-x636.google.com with SMTP id d9443c01a7336-1c1ff5b741cso13285985ad.2; Thu, 21 Sep 2023 14:35:03 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1695332102; x=1695936902; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=WM0ZLVHvV+NZ5kwdSJi8dtI3pr22k4r3qhjNO/EWTSA=; b=CveTnsj9DgdX0IvVAd/Bb1+fejPx7IXqzj9t9OUJzsz7apkIEn1A4BUB2ww+apo0MP oHLk71z8LRrWMdN1BJ2X1LK4qhabeKSaDvePsZoESFnrUCV3uHWiNMNkHD+3nxXH+c9J HasxVhF3glnfYhNtUVkEhzXtLHGmnycrIX1iiZZG7LfveA9WjsuXCNSMuHGMBD5ghopk /jA7Dh+fWcBriymSsarTPZsDcKNAFPrSttmX1beIbSyjQzhDrj/Yn5UEeivbanMNYPJB L2holVT6P1kPak8uWYpn4c4bw9mKQU3jjXoycvrQVTGAPibb5Aa/i+gCJwrWr8sV3Jmy MhxQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1695332102; x=1695936902; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=WM0ZLVHvV+NZ5kwdSJi8dtI3pr22k4r3qhjNO/EWTSA=; b=DhC+F5MXg2Sp2boO3Ily1mRCm9gZFX8xbNOQ3eS9GbfC7kVGAxIsCdwJEizcVuz144 iAGBZolhUeKLKYmfUYk7IAQzUAsDacu1s6572Qtyx8/BHPHqzyCMLK69D37hHCHnhwsJ oU12YmZ30oCMUULRU3zA97J7+po2lF190EMwXX5CgNFieKx52bsMAeEfSawb37joTfSH Vze1EEDFM56xUy+TPIQiK6kuw/KJXIPwjXFqd8ltimCVNmhkjQ0rM2Eijor+LZJMGjLJ M+kfJZotyrlujnBXSzTJPmEYBfZtQItmD74+f0sYhp/HYOUR5jiO2R5/Pxdh+9HU5MCW nr6w== X-Gm-Message-State: AOJu0YzRccUwu3EpZSLqhnKZlGgklXaeC4ix4zjQvjB/pZQciiyb/X9M avtYXEigCjMRpfh/ooLFlvKPbebpGZI= X-Google-Smtp-Source: AGHT+IEZS349CrXt4OtEC0O5R1nIJv4bSmYxrx2/ZhMt4rmHMN0W0/euKFxMu5qjglzjQ+A7y2VJfQ== X-Received: by 2002:a17:903:24e:b0:1bc:6799:3f6c with SMTP id j14-20020a170903024e00b001bc67993f6cmr7768970plh.35.1695332102483; Thu, 21 Sep 2023 14:35:02 -0700 (PDT) Received: from wedsonaf-dev.home.lan ([189.124.190.154]) by smtp.googlemail.com with ESMTPSA id jc6-20020a17090325c600b001c567dcf22dsm2007981plb.281.2023.09.21.14.34.59 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 21 Sep 2023 14:35:02 -0700 (PDT) From: Wedson Almeida Filho To: rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , linux-kernel@vger.kernel.org, Wedson Almeida Filho Subject: [PATCH 1/2] rust: arc: rename `ArcInner` to `WithRef` Date: Thu, 21 Sep 2023 18:34:39 -0300 Message-Id: <20230921213440.202017-2-wedsonaf@gmail.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20230921213440.202017-1-wedsonaf@gmail.com> References: <20230921213440.202017-1-wedsonaf@gmail.com> MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org From: Wedson Almeida Filho This is in preparation for removing `ArcBorrow` and making `WithRef` public. This is a pure name change with no functional changes intended. Suggested-by: Bj=C3=B6rn Roy Baron Signed-off-by: Wedson Almeida Filho Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Finn Behrens Reviewed-by: Gary Guo Reviewed-by: Martin Rodriguez Reboredo --- rust/kernel/sync/arc.rs | 20 ++++++++++---------- rust/kernel/sync/arc/std_vendor.rs | 4 ++-- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 3d496391a9bd..86bff1e0002c 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -126,13 +126,13 @@ /// # Ok::<(), Error>(()) /// ``` pub struct Arc { - ptr: NonNull>, - _p: PhantomData>, + ptr: NonNull>, + _p: PhantomData>, } =20 #[pin_data] #[repr(C)] -struct ArcInner { +struct WithRef { refcount: Opaque, data: T, } @@ -164,7 +164,7 @@ impl Arc { /// Constructs a new reference counted instance of `T`. pub fn try_new(contents: T) -> Result { // INVARIANT: The refcount is initialised to a non-zero value. - let value =3D ArcInner { + let value =3D WithRef { // SAFETY: There are no safety requirements for this FFI call. refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }), data: contents, @@ -201,13 +201,13 @@ pub fn init(init: impl Init) -> error::Resul= t } =20 impl Arc { - /// Constructs a new [`Arc`] from an existing [`ArcInner`]. + /// Constructs a new [`Arc`] from an existing [`WithRef`]. /// /// # Safety /// /// The caller must ensure that `inner` points to a valid location and= has a non-zero reference /// count, one of which will be owned by the new [`Arc`] instance. - unsafe fn from_inner(inner: NonNull>) -> Self { + unsafe fn from_inner(inner: NonNull>) -> Self { // INVARIANT: By the safety requirements, the invariants hold. Arc { ptr: inner, @@ -243,7 +243,7 @@ fn into_foreign(self) -> *const core::ffi::c_void { unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> ArcBorrow<'a, T= > { // SAFETY: By the safety requirement of this function, we know tha= t `ptr` came from // a previous call to `Arc::into_foreign`. - let inner =3D NonNull::new(ptr as *mut ArcInner).unwrap(); + let inner =3D NonNull::new(ptr as *mut WithRef).unwrap(); =20 // SAFETY: The safety requirements of `from_foreign` ensure that t= he object remains alive // for the lifetime of the returned value. @@ -376,7 +376,7 @@ fn from(item: Pin>) -> Self { /// # Ok::<(), Error>(()) /// ``` pub struct ArcBorrow<'a, T: ?Sized + 'a> { - inner: NonNull>, + inner: NonNull>, _p: PhantomData<&'a ()>, } =20 @@ -406,7 +406,7 @@ impl ArcBorrow<'_, T> { /// Callers must ensure the following for the lifetime of the returned= [`ArcBorrow`] instance: /// 1. That `inner` remains valid; /// 2. That no mutable references to `inner` are created. - unsafe fn new(inner: NonNull>) -> Self { + unsafe fn new(inner: NonNull>) -> Self { // INVARIANT: The safety requirements guarantee the invariants. Self { inner, @@ -526,7 +526,7 @@ pub fn try_new(value: T) -> Result { /// Tries to allocate a new [`UniqueArc`] instance whose contents are = not initialised yet. pub fn try_new_uninit() -> Result>, AllocErro= r> { // INVARIANT: The refcount is initialised to a non-zero value. - let inner =3D Box::try_init::(try_init!(ArcInner { + let inner =3D Box::try_init::(try_init!(WithRef { // SAFETY: There are no safety requirements for this FFI call. refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }), data <- init::uninit::(), diff --git a/rust/kernel/sync/arc/std_vendor.rs b/rust/kernel/sync/arc/std_= vendor.rs index a66a0c2831b3..4b30e5597ba5 100644 --- a/rust/kernel/sync/arc/std_vendor.rs +++ b/rust/kernel/sync/arc/std_vendor.rs @@ -5,7 +5,7 @@ //! "Apache-2.0 OR MIT" and adapted for kernel use. For copyright details, //! see . =20 -use crate::sync::{arc::ArcInner, Arc}; +use crate::sync::{arc::WithRef, Arc}; use core::any::Any; =20 impl Arc { @@ -17,7 +17,7 @@ pub fn downcast(self) -> core::result::Result, = Self> if (*self).is::() { // SAFETY: We have just checked that the type is correct, so w= e can cast the pointer. unsafe { - let ptr =3D self.ptr.cast::>(); + let ptr =3D self.ptr.cast::>(); core::mem::forget(self); Ok(Arc::from_inner(ptr)) } --=20 2.34.1 From nobody Fri Feb 13 17:29:18 2026 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 873A0E7D0AB for ; Thu, 21 Sep 2023 22:09:04 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S230010AbjIUWJI (ORCPT ); Thu, 21 Sep 2023 18:09:08 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:43876 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232946AbjIUWIw (ORCPT ); Thu, 21 Sep 2023 18:08:52 -0400 Received: from mail-pl1-x62e.google.com (mail-pl1-x62e.google.com [IPv6:2607:f8b0:4864:20::62e]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id D2D4329794; Thu, 21 Sep 2023 14:35:06 -0700 (PDT) Received: by mail-pl1-x62e.google.com with SMTP id d9443c01a7336-1c5c91bece9so12423485ad.3; Thu, 21 Sep 2023 14:35:06 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1695332106; x=1695936906; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=KaMXIYRdgSMU0GyDTGJxyylDd+HthrxvkGhhTMkKEDY=; b=RDG7jR7VxvJKGkh7G4iEvNDHLvwwjkzxce57DPRV2DWNSIx64KW79inq/zs7Og3EfR Qe/43M3RCqbhuGPldCs5+gc3WzR+Fcr83FBHraAmnW8ROs4ZyWNOqs20BabOv88rPxlU GyYHtTt572n45l2HNnd35EP2oSVx359va8QZCHe6QtcPFlYxRM/aVp8LZvdBucx0xEmD QEy0O71YdvkfdrMzwjkf67gKd21yOf3Sbn9bEsib5e8VWzvmlHNcq+iU1pAuleQsXZEg 05Thg+dcTTTvlG3+pznr8RWghvIX4jAkXq/oq2j3mBbN0c9Y1jBH6BYzH0uKXfUyU3eb WazA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1695332106; x=1695936906; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=KaMXIYRdgSMU0GyDTGJxyylDd+HthrxvkGhhTMkKEDY=; b=wSOmwj4W5XtShFm0/NwuQQfha487A9OG6PchsQX5jFandGNgHTQLBAQL4Pa4UnwRB1 yX6Os9JxT3cl5nyIPNjzBIpctftrZceqSz13mP+ueEFLwmfMrq+pgomDC1ckwmZbbA5f jns3XZYyBr1zWUpH1pffln8iDjU35Ck4A7zKUue2Q27NczplgTj9Uiozb4NLo8xsLMtQ dN9Okqrd3GJAan1Jk3OAYKPbzzZwKa6IX9BJj5CX0Phbm4rI6pU8yDAtJhqWAnXRoOIH 1Yf2YKxfYu7Qt8ryw20n4mOau0DFx1/+OhrBXV5PLrcs20LOx2UWBapvNaP0io3a4vTx jZEw== X-Gm-Message-State: AOJu0Yz/08QUh9B/v8q1X+sQXT+GWkMBeuT3P3SwPLWCvbjw3XUEHo1s Eaqtv1LwCeo2N3fxSlNkWzEMhcz+ELI= X-Google-Smtp-Source: AGHT+IEM1wJisy9a51MpOgfudValE0o0NS1n5eEGCsuJHJwYmlSBoN/0Rn+QT28WWRxNTDMgK2GGmA== X-Received: by 2002:a17:902:eccb:b0:1c4:62a:e4a with SMTP id a11-20020a170902eccb00b001c4062a0e4amr7503915plh.64.1695332106072; Thu, 21 Sep 2023 14:35:06 -0700 (PDT) Received: from wedsonaf-dev.home.lan ([189.124.190.154]) by smtp.googlemail.com with ESMTPSA id jc6-20020a17090325c600b001c567dcf22dsm2007981plb.281.2023.09.21.14.35.02 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 21 Sep 2023 14:35:05 -0700 (PDT) From: Wedson Almeida Filho To: rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , linux-kernel@vger.kernel.org, Wedson Almeida Filho Subject: [PATCH 2/2] rust: arc: remove `ArcBorrow` in favour of `WithRef` Date: Thu, 21 Sep 2023 18:34:40 -0300 Message-Id: <20230921213440.202017-3-wedsonaf@gmail.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20230921213440.202017-1-wedsonaf@gmail.com> References: <20230921213440.202017-1-wedsonaf@gmail.com> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Type: text/plain; charset="utf-8" From: Wedson Almeida Filho With GATs, we don't need a separate type to represent a borrowed object with a refcount, we can just use Rust's regular shared borrowing. In this case, we use `&WithRef` instead of `ArcBorrow<'_, T>`. Co-developed-by: Boqun Feng Signed-off-by: Boqun Feng Signed-off-by: Wedson Almeida Filho Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Reviewed-by: Martin Rodriguez Reboredo --- rust/kernel/sync.rs | 2 +- rust/kernel/sync/arc.rs | 180 ++++++++++++++-------------------------- 2 files changed, 62 insertions(+), 120 deletions(-) diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs index d219ee518eff..083494884500 100644 --- a/rust/kernel/sync.rs +++ b/rust/kernel/sync.rs @@ -12,7 +12,7 @@ pub mod lock; mod locked_by; =20 -pub use arc::{Arc, ArcBorrow, UniqueArc}; +pub use arc::{Arc, UniqueArc, WithRef}; pub use condvar::CondVar; pub use lock::{mutex::Mutex, spinlock::SpinLock}; pub use locked_by::LockedBy; diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 86bff1e0002c..5948e42b9c8f 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -105,14 +105,14 @@ /// Coercion from `Arc` to `Arc`: /// /// ``` -/// use kernel::sync::{Arc, ArcBorrow}; +/// use kernel::sync::{Arc, WithRef}; /// /// trait MyTrait { /// // Trait has a function whose `self` type is `Arc`. /// fn example1(self: Arc) {} /// -/// // Trait has a function whose `self` type is `ArcBorrow<'_, Self>`. -/// fn example2(self: ArcBorrow<'_, Self>) {} +/// // Trait has a function whose `self` type is `&WithRef`. +/// fn example2(self: &WithRef) {} /// } /// /// struct Example; @@ -130,9 +130,48 @@ pub struct Arc { _p: PhantomData>, } =20 +/// An instance of `T` with an attached reference count. +/// +/// # Examples +/// +/// ``` +/// use kernel::sync::{Arc, WithRef}; +/// +/// struct Example; +/// +/// fn do_something(e: &WithRef) -> Arc { +/// e.into() +/// } +/// +/// let obj =3D Arc::try_new(Example)?; +/// let cloned =3D do_something(obj.as_with_ref()); +/// +/// // Assert that both `obj` and `cloned` point to the same underlying ob= ject. +/// assert!(core::ptr::eq(&*obj, &*cloned)); +/// ``` +/// +/// Using `WithRef` as the type of `self`: +/// +/// ``` +/// use kernel::sync::{Arc, WithRef}; +/// +/// struct Example { +/// _a: u32, +/// _b: u32, +/// } +/// +/// impl Example { +/// fn use_reference(self: &WithRef) { +/// // ... +/// } +/// } +/// +/// let obj =3D Arc::try_new(Example { _a: 10, _b: 20 })?; +/// obj.as_with_ref().use_reference(); +/// ``` #[pin_data] #[repr(C)] -struct WithRef { +pub struct WithRef { refcount: Opaque, data: T, } @@ -215,16 +254,16 @@ unsafe fn from_inner(inner: NonNull>) -> S= elf { } } =20 - /// Returns an [`ArcBorrow`] from the given [`Arc`]. + /// Returns a [`WithRef`] from the given [`Arc`]. /// - /// This is useful when the argument of a function call is an [`ArcBor= row`] (e.g., in a method - /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`= ] is free when optimised. + /// This is useful when the argument of a function call is a [`WithRef= `] (e.g., in a method + /// receiver), but we have an [`Arc`] instead. Getting a [`WithRef`] i= s free when optimised. #[inline] - pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> { + pub fn as_with_ref(&self) -> &WithRef { // SAFETY: The constraint that the lifetime of the shared referenc= e must outlive that of - // the returned `ArcBorrow` ensures that the object remains alive = and that no mutable + // the returned `WithRef` ensures that the object remains alive an= d that no mutable // reference can be created. - unsafe { ArcBorrow::new(self.ptr) } + unsafe { self.ptr.as_ref() } } =20 /// Compare whether two [`Arc`] pointers reference the same underlying= object. @@ -234,20 +273,17 @@ pub fn ptr_eq(this: &Self, other: &Self) -> bool { } =20 impl ForeignOwnable for Arc { - type Borrowed<'a> =3D ArcBorrow<'a, T>; + type Borrowed<'a> =3D &'a WithRef; =20 fn into_foreign(self) -> *const core::ffi::c_void { ManuallyDrop::new(self).ptr.as_ptr() as _ } =20 - unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> ArcBorrow<'a, T= > { + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a WithRef { // SAFETY: By the safety requirement of this function, we know tha= t `ptr` came from - // a previous call to `Arc::into_foreign`. - let inner =3D NonNull::new(ptr as *mut WithRef).unwrap(); - - // SAFETY: The safety requirements of `from_foreign` ensure that t= he object remains alive - // for the lifetime of the returned value. - unsafe { ArcBorrow::new(inner) } + // a previous call to `Arc::into_foreign`. The safety requirements= of `from_foreign` ensure + // that the object remains alive for the lifetime of the returned = value. + unsafe { &*(ptr.cast::>()) } } =20 unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { @@ -320,119 +356,25 @@ fn from(item: Pin>) -> Self { } } =20 -/// A borrowed reference to an [`Arc`] instance. -/// -/// For cases when one doesn't ever need to increment the refcount on the = allocation, it is simpler -/// to use just `&T`, which we can trivially get from an `Arc` instance. -/// -/// However, when one may need to increment the refcount, it is preferable= to use an `ArcBorrow` -/// over `&Arc` because the latter results in a double-indirection: a p= ointer (shared reference) -/// to a pointer (`Arc`) to the object (`T`). An [`ArcBorrow`] eliminat= es this double -/// indirection while still allowing one to increment the refcount and get= ting an `Arc` when/if -/// needed. -/// -/// # Invariants -/// -/// There are no mutable references to the underlying [`Arc`], and it rema= ins valid for the -/// lifetime of the [`ArcBorrow`] instance. -/// -/// # Example -/// -/// ``` -/// use kernel::sync::{Arc, ArcBorrow}; -/// -/// struct Example; -/// -/// fn do_something(e: ArcBorrow<'_, Example>) -> Arc { -/// e.into() -/// } -/// -/// let obj =3D Arc::try_new(Example)?; -/// let cloned =3D do_something(obj.as_arc_borrow()); -/// -/// // Assert that both `obj` and `cloned` point to the same underlying ob= ject. -/// assert!(core::ptr::eq(&*obj, &*cloned)); -/// # Ok::<(), Error>(()) -/// ``` -/// -/// Using `ArcBorrow` as the type of `self`: -/// -/// ``` -/// use kernel::sync::{Arc, ArcBorrow}; -/// -/// struct Example { -/// a: u32, -/// b: u32, -/// } -/// -/// impl Example { -/// fn use_reference(self: ArcBorrow<'_, Self>) { -/// // ... -/// } -/// } -/// -/// let obj =3D Arc::try_new(Example { a: 10, b: 20 })?; -/// obj.as_arc_borrow().use_reference(); -/// # Ok::<(), Error>(()) -/// ``` -pub struct ArcBorrow<'a, T: ?Sized + 'a> { - inner: NonNull>, - _p: PhantomData<&'a ()>, -} - -// This is to allow [`ArcBorrow`] (and variants) to be used as the type of= `self`. -impl core::ops::Receiver for ArcBorrow<'_, T> {} - -// This is to allow `ArcBorrow` to be dispatched on when `ArcBorrow`= can be coerced into -// `ArcBorrow`. -impl, U: ?Sized> core::ops::DispatchFromDyn> - for ArcBorrow<'_, T> -{ -} - -impl Clone for ArcBorrow<'_, T> { - fn clone(&self) -> Self { - *self - } -} - -impl Copy for ArcBorrow<'_, T> {} - -impl ArcBorrow<'_, T> { - /// Creates a new [`ArcBorrow`] instance. - /// - /// # Safety - /// - /// Callers must ensure the following for the lifetime of the returned= [`ArcBorrow`] instance: - /// 1. That `inner` remains valid; - /// 2. That no mutable references to `inner` are created. - unsafe fn new(inner: NonNull>) -> Self { - // INVARIANT: The safety requirements guarantee the invariants. - Self { - inner, - _p: PhantomData, - } - } -} +// This is to allow [`WithRef`] (and variants) to be used as the type of `= self`. +impl core::ops::Receiver for WithRef {} =20 -impl From> for Arc { - fn from(b: ArcBorrow<'_, T>) -> Self { +impl From<&WithRef> for Arc { + fn from(b: &WithRef) -> Self { // SAFETY: The existence of `b` guarantees that the refcount is no= n-zero. `ManuallyDrop` // guarantees that `drop` isn't called, so it's ok that the tempor= ary `Arc` doesn't own the // increment. - ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) }) + ManuallyDrop::new(unsafe { Arc::from_inner(b.into()) }) .deref() .clone() } } =20 -impl Deref for ArcBorrow<'_, T> { +impl Deref for WithRef { type Target =3D T; =20 fn deref(&self) -> &Self::Target { - // SAFETY: By the type invariant, the underlying object is still a= live with no mutable - // references to it, so it is safe to create a shared reference. - unsafe { &self.inner.as_ref().data } + &self.data } } =20 --=20 2.34.1