Authentication-Results: smtp.subspace.kernel.org; arc=pass header.oldest-pass=0 smtp.remote-ip=52.101.101.111 ARC-Seal: i=2; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=pass; t=1796229786; b=pgcdOUoSoCsmABtOt3roQ3j6ztK6o07SuRHMkS3IUCcuaGuhvsJxRNKbrLrSPvAhy2Ui 0n0ZvfuXfY88tjzrrx5OSe5LCQzRjF6QCw2qqlb5fsH6jfH+ZRfKe/JMIjk2Z8yp1cUIP Mir6L95PKUuhSqQaxzE+Gn9eUaJ3mIrZgOriTVX/tjaIdG3MBDfbF3JZd7khnnEqYAIgT kSAXygNVSGWidcC+bSQ3g/27VGieO0A2f8WXGX+2qLBJRmHicOP654zwz6kLdBkck+6yj 5QUSTkr9mMZ4npTRfEEGRpR9iwXXjDkcT6UjZ2hqUxb3LW7y+O0B1ObQRV4SFhuLxDQ== ARC-Message-Signature: i=2; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796229786; h=DMARC-Filter:DKIM-Signature:Received:Received:From:Date:Subject: Content-Type:Content-Transfer-Encoding:Message-Id:X-B4-Tracking: X-Change-ID:To:Cc:X-Mailer:X-Developer-Signature:X-Developer-Key: X-ClientProxiedBy:MIME-Version:X-MS-PublicTrafficType: X-MS-TrafficTypeDiagnostic:X-MS-Office365-Filtering-Correlation-Id: X-MS-Exchange-SenderADCheck:X-MS-Exchange-AntiSpam-Relay: X-Microsoft-Antispam:X-Microsoft-Antispam-Message-Info: X-Forefront-Antispam-Report: X-MS-Exchange-AntiSpam-MessageData-ChunkCount: X-MS-Exchange-AntiSpam-MessageData-0:X-OriginatorOrg: X-MS-Exchange-CrossTenant-Network-Message-Id: X-MS-Exchange-CrossTenant-AuthSource:X-MS-Exchange-CrossTenant-AuthAs: X-MS-Exchange-CrossTenant-OriginalArrivalTime: X-MS-Exchange-CrossTenant-FromEntityHeader: X-MS-Exchange-CrossTenant-Id:X-MS-Exchange-CrossTenant-MailboxType: X-MS-Exchange-CrossTenant-UserPrincipalName: X-MS-Exchange-Transport-CrossTenantHeadersStamped; bh=YSrJ8lLP2xVt0jZ44zUF5JSj693/2WLoRD6fVLhtw1Q=; b=E4Uthe1+kDqcE50lVsLgdEfdE86p0EfmcRWN2US29eYOzDzubOsW2CH5jyiEw9v48t2J uiCtL+Gm5CrCxJ4MqUKvwcNpicnhQJMxS2+afObOohp0C7HsijcslIwrnePQCNuNvjqr1 dN50FnH7OhHyTkFfeY9Z/TYzr2ID92e7K8BkNchci/YF1/+TPU3rqK9n72AReS5HzOtWg L0/peHanRiwTrf+dHuLnsH8o74LAWGe4Tcz5qQWrcw4qY9y1UbXXRVtSOlD1loVF9xPLm uWGJ6SXcbgIUVP7SclY23nrtm3fPAfFsv5HX9EmnGqSXUunTVOD8RlSQ1WyGrzJV5HA== ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass header.d=garyguo.net header.i=@garyguo.net header.a=rsa-sha256 header.s=selector1 header.b=MifiCXjh; arc=pass header.oldest-pass=0 smtp.remote-ip=52.101.101.111 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022111.outbound.protection.outlook.com [52.101.101.111]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange ECDHE (secp384r1) server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 281A3606A31A; Wed, 2 Dec 2026 16:43:05 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 281A3606A31A Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key, unprotected) header.d=garyguo.net header.i=@garyguo.net header.a=rsa-sha256 header.s=selector1 header.b=MifiCXjh ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=lemP1fU7AJ8SOPR7d6Nzc6RwUbi+Btysu+Mylan81bx/CJu0zV6YgMRBmb4z1xI8h+4DPQNgNrxbRj48xWpNQBSKk931L4ZOXysB+JDIDgVWN1CBhuoGtNxs4pb9uj3PPHYhpbmRU5Z1+LYH3Nu/+NGACSYLCdFhZpR2jTX6Z7j+4Qd42jvvC8kzyr/5SGFouFL4sgC8crvXRTJdPMsVe/IBwog1l7bp1nUSZ0CRZLkHqXUWZbLpMS+FNS1l2qfDS4D9M0pdvgpCRsrLEmotVzub61yxTjL/585PbFvUb99ThOWDa33K9KgtvN2IFn5AftL4TYQXEuEDoKGIbX2wSw== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector10001; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=YSrJ8lLP2xVt0jZ44zUF5JSj693/2WLoRD6fVLhtw1Q=; b=KesFiqVPW72May6qyeik9b+4rnylbt3sR4jPq9F6KTVnPO2zlvSJSVnP1AgbL0nkJZUKluWi/R1kxMEaFlcCHO5zpQdfce6zvuUGCQMtz6a52PgThMq9/Sv+bXQXM4Hui3PXtA81goXgX1/X+8kZ1NsDVRTCmzrJ4w65mn6vdz73TRPtulq6fxSiHfk+CfJUMxcY/hEDY+JtqYmPdp6luKZyOtF9QI550rJ8KKBZkIz81/WleXErxSRq8MNrZaESXtm0FiGAsGB7i7Lu1Mk160CjIdzN4gYeXSuRkF2HOgV18odHb8Fx0WYOWQ2NrsXlu1D8TpVzBg0vnwCoBnsA7g== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=YSrJ8lLP2xVt0jZ44zUF5JSj693/2WLoRD6fVLhtw1Q=; b=MifiCXjhj63JX6qTHAgIWerj2nP6nueyv0onG0l2KWpXEZPmOzf3gNamE17QXpFErkAgybxYwBRBabqx4X6gu8f4zV0tTgJFK6xwzOdyBKxFB0fGpAn0DVBVFzm75+2dy8uy/N3mljBmkUUkOWcJY8Iuuyl/jPLOKsChTQw/O3Q= Authentication-Results: mx.microsoft.com 1; dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CWLP265MB6051.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:1cb::9) by LO8P265MB089518.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:800::19) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.688.11; Wed, 2 Dec 2026 16:43:01 +0000 Received: from CWLP265MB6051.GBRP265.PROD.OUTLOOK.COM ([fe80::55f6:f98b:7fad:c6e3]) by CWLP265MB6051.GBRP265.PROD.OUTLOOK.COM ([fe80::55f6:f98b:7fad:c6e3%2]) with mapi id 15.21.0688.009; Wed, 2 Dec 2026 16:43:01 +0000 From: Gary Guo Date: Wed, 02 Dec 2026 16:42:53 +0000 Subject: [PATCH v2] rust: pin-init: document self-referential feature Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit Message-Id: <20261202-dev-pin-init-doc-v2-1-987d6f92adca@garyguo.net> X-B4-Tracking: v=1; b=H4sIAAAAAAAC/32OQQ6CMBREr0K69iutRIor72FYlPYL30VL2tJAC HeXYuLS5ZvMvMzKAnrCwO7FyjwmCuTsDuJUMD0o2yOQ2ZmJUtw4FxUYTDCSBbIUwTgNupJS1o3 ium7YPhs9vmg+lM/2y2Hq3qhj9uRGpwJC55XVQ46iR7z8lBbnmEsDhej8chxLPMv+fEgcOBhTq isa1ZRcPnrll35yZ4uRtdu2fQCUDk+X6QAAAA== X-Change-ID: 20261124-dev-pin-init-doc-c488879a1c79 To: Benno Lossin , Miguel Ojeda , Boqun Feng , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Daniel Almeida , Tamir Duberstein , Alexandre Courbot , =?utf-8?q?Onur_=C3=96zkan?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Gary Guo X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1796229781; l=10019; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=/DNxS0e7dk1/PDjI8sd7pSVc3dT52ocWvSPkmp0xMaw=; b=PSYlSxbR2YC6Wj0i3Fjvv2qp7SBjoly0A3heVB1QLAoUUzcqGMnD7nopw8MrfHz4ZA/HCLLxV YjH3+LVBIT5BcX5gbVZkQN2PQPYtj5jcVNoGuU2swaSaHYMz5U0Hdb7 X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO4P123CA0548.GBRP123.PROD.OUTLOOK.COM (2603:10a6:600:319::11) To CWLP265MB6051.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:1cb::9) X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: CWLP265MB6051:EE_|LO8P265MB089518:EE_ X-MS-Office365-Filtering-Correlation-Id: 621396cd-9278-4e23-badb-08df5093544a X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|10070799003|376014|7416014|1800799024|366016|23010399003|5023799004|6133799003|261009223027099003|18002099003|3023799007|921020|260925021911599003|260925022911599003|260925021311599003|56012099006|10067099003|261102123227099003|261021121427099003|261021123027099003|261022075727099003|261022113327099003|261026121527099003; X-Microsoft-Antispam-Message-Info: D/9/kwERWjSZk9vSSjEzV8siE35HaYK+3/I8AVswCXYXzq81X7qxE1B6bbO8Ggt41X2iiS0ZXnzGvExVklMBTNSLuEUuU3iNzVH80cI6SutPrUraP6TEltg1/8uv7uTonSwl+YdCSTp+2eSBzlk5RHau1dsmEPOphyJoIJtaOm6Hs6I31ApRiRs7ZrVXzbPqC3i80GIhSVrFMFqvHObzkGoTZ488SKvd2gxucW2yzmQtpqmeaw4QjhHreBpnI+bGJRAWc2tBSmentimn9EiJjhye6Q1rcISU1YZdPS5oCcFyTR0G25fTs2651/zNCetOR1o91oPzdcTyALrbsndcLipYQxm3XBI7FTLksyjKXWE//2v+TwVWB2fvJXzWhWr/2N409YGeqmZN9bCTr6T8vl12VZI67+QjAPCiX3jkPtKtr2XL3MnHEV5x5pWesCosexLxE2Inv96Y2Rpx0VTsTNMNs30CX+/2qDXbKyAAc2UJP+VdxkAE19EwyXcKrM+X4vPEOZAOUqFl+wFpTlOIzuCYXvGAMLUXd0ZzxGXaqdPvBMTkwC7qYS4DExOhnGdIFeZulmKZhzCR6iyCFfpD+lMTH6fH3BVZztsNLFxuW3JeRtiDhOq0k49odYV2tpAtrlY7SHsagoCW/jPou40UWp8254SJB6wVHcd3BNaUWNA= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CWLP265MB6051.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(10070799003)(376014)(7416014)(1800799024)(366016)(23010399003)(5023799004)(6133799003)(261009223027099003)(18002099003)(3023799007)(921020)(260925021911599003)(260925022911599003)(260925021311599003)(56012099006)(10067099003)(261102123227099003)(261021121427099003)(261021123027099003)(261022075727099003)(261022113327099003)(261026121527099003);DIR:OUT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?dlpSL2JtdThOMy9Nc0dkVEZEd3lWVXZPdTdLdDd1eTMwdHZWdi9wUzVQZUw0?= =?utf-8?B?bWNhUDR0MzB0UXQ3WHZidnl5V0kvOTM4aEVYRWM3cU8rT2hqL01sd2xORjFJ?= =?utf-8?B?dlFhZ3E2Y21qZk9uV0xvbWV5NzUzT0ZXdGZWcEs4UUhsM3A3VnFBd2JicVZz?= =?utf-8?B?RkQ2d1hWaGQrMTNSajZqOGhYdVpHaGxZWXplZytrUjgvZ1BObkNjdDI2WlFi?= =?utf-8?B?M25GT1BKMWRLNkE2STc0RmZlY09sSGYrTUlEQkF4MEl5QXNmMmlCenRHUjFa?= =?utf-8?B?YkZyTTJ1RHVDaXlNOVNiNGRoS2VaRXdCV3YzQWVOWUVnaWZ3aitoOGk1ckhp?= =?utf-8?B?eDA3UVdoT3pJdCtkMTZzNmhLRkRKbnFkSDV2Qjgyc1JGZURxbHFFNFg3eDdm?= =?utf-8?B?QUsrMkFpQmw5U0FMNHIyUDhkSE1aYnppZjhENkpIU2xXRmxDcFc5YmJDTmZX?= =?utf-8?B?VHhNZFN4QzVKZTIvK2VVZGlmOSt0cjVXZHZjd05OdmM4VHhIV3hjWFNNQUJ6?= =?utf-8?B?K3JySmRNejNWZXdWSkVrYUFpSVEzTjUvelhQRGZ4YVluOUZwUFpxZz09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: 621396cd-9278-4e23-badb-08df5093544a X-MS-Exchange-CrossTenant-AuthSource: CWLP265MB6051.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 02 Dec 2026 16:43:01.5706 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: eh0MjTVskyJeWM7yAnKSLOMK5xIHChgKqC0Dm/MeaLrnZvfb3XLzCvkLPOA90Gb/UHM1xOhXUWOHJimgrMpczg== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO8P265MB089518 Add a section to the documentation of `#[pin_data]` macro about the safe self-referential creation feature. Signed-off-by: Gary Guo --- Changes in v2: - Fix various typos (Alice) - Add an example of invariant capture and accessor (Philipp) - Link to v1: https://patch.msgid.link/20261124-dev-pin-init-doc-v1-1-dd0a3eda9018@garyguo.net --- rust/pin-init/src/lib.rs | 189 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 183 insertions(+), 6 deletions(-) diff --git a/rust/pin-init/src/lib.rs b/rust/pin-init/src/lib.rs index 9ffa76434310..724b67a92cb5 100644 --- a/rust/pin-init/src/lib.rs +++ b/rust/pin-init/src/lib.rs @@ -307,6 +307,9 @@ /// Tuple structs are supported as well. Their fields have no names, so the generated projection /// is a tuple struct too and its fields are accessed by index. /// +/// Self-referential structs, where a field borrows another field of the same struct, are also +/// supported. See the [section on self-referential structs](#self-referential-structs) below. +/// /// If your `struct` implements `Drop`, then you need to add `PinnedDrop` as arguments to this /// macro, and change your `Drop` implementation to `PinnedDrop` annotated with /// `#[`[`macro@pinned_drop`]`]`, since dropping pinned values requires extra care. @@ -376,6 +379,179 @@ /// } /// } /// ``` +/// +/// # Self-Referential Structs +/// +/// This macro also supports structs where a field borrows another field of the same struct. To do +/// that, use the name of the borrowed field as a lifetime (a *field lifetime*) in the type of the +/// borrowing field: +/// +/// ``` +/// # use pin_init::*; +/// #[pin_data] +/// struct SelfRef { +/// part: &'msg str, +/// msg: String, +/// } +/// ``` +/// +/// Here the field `part` captures the field lifetime `'msg` and thereby borrows the field `msg`. +/// A field may only borrow from fields declared after it: fields are dropped in declaration +/// order, so the borrowing field is then always dropped before the field it borrows. Structs +/// with borrowed fields or captured lifetimes do not implement `Unpin`. +/// +/// When initializing such a struct with [`pin_init!`], every named initialized field has a +/// binding generated for it (as `&T`/`Pin<&T>` for fields shared-borrowed, or +/// `&mut T`/`Pin<&mut T>` for fields mutably-borrowed), so a field can borrow from the fields +/// initialized before it: +/// +/// ``` +/// # use pin_init::*; +/// # #[pin_data] +/// # struct SelfRef { +/// # part: &'msg str, +/// # msg: String, +/// # } +/// stack_pin_init!(let foo = pin_init!(SelfRef { +/// msg: "hello world".to_owned(), +/// part: &msg[..5], +/// })); +/// assert_eq!(*foo.part(), "hello"); +/// ``` +/// +/// Note that `&mut T`/`Pin<&mut T>` bindings are also generated for non-borrowed fields, but access +/// to them is limited to within the initializer. +/// +/// ## Mutable Borrows +/// +/// A field is only shared-borrowed by default. To also allow for `&mut` borrows, mark the borrowed +/// field with `#[borrowed(mut)]`: +/// +/// ``` +/// # use pin_init::*; +/// #[pin_data] +/// struct MutSelfRef { +/// part: &'mut_msg mut str, +/// #[borrowed(mut)] +/// mut_msg: String, +/// } +/// +/// stack_pin_init!(let foo = pin_init!(MutSelfRef { +/// mut_msg: "hello world".to_owned(), +/// part: &mut mut_msg[..5], +/// })); +/// foo.as_mut().with_project(|proj| proj.part.make_ascii_uppercase()); +/// assert_eq!(*foo.part(), "HELLO"); +/// ``` +/// +/// Shared borrows are inferred automatically whenever a field lifetime is used, but they can also +/// be requested explicitly with `#[borrowed]`. +/// +/// ## Variance +/// +/// A captured field lifetime is *covariant* by default: just like a normal reference, the field +/// type allows the captured lifetime to be shortened. If the field type does not allow that (for +/// example because the borrow is stored behind a `Mutex`), the capture has to be marked as +/// *invariant* using the `#[uses]` attribute: +/// +/// ``` +/// # use pin_init::*; +/// # use std::sync::Mutex; +/// #[pin_data] +/// struct InvariantSelfRef { +/// #[uses('owner: invariant)] +/// part: Mutex<&'owner str>, +/// owner: String, +/// } +/// ``` +/// +/// The macro verifies that captures marked covariant really are covariant. `#[uses]` accepts a +/// comma-separated list of lifetimes, each with an optional variance (the default being +/// `covariant`). The special lifetime `'_` stands for all field (and existential) lifetimes +/// mentioned in the type of the field, e.g. `#[uses('_: invariant)]`. +/// +/// ## Existential Lifetimes +/// +/// A field lifetime ties a borrow to a specific field. Sometimes a field should instead borrow +/// from something outside the struct that merely outlives one of the struct's lifetime +/// parameters. Such lifetimes are declared in the where clause of the struct using `exists`: +/// +/// ``` +/// # use pin_init::*; +/// # use std::marker::PhantomData; +/// # use std::sync::Mutex; +/// struct CoherentBox<'a>(PhantomData<&'a ()>); +/// +/// #[pin_data] +/// struct DeviceBox<'a> +/// where +/// exists<'x>: 'a, +/// { +/// #[uses('x: invariant)] +/// m: Mutex>, +/// p: PhantomData<&'a ()>, +/// } +/// +/// // The struct is covariant in `'a`, so it can be shortened: +/// fn shorten<'long: 'short, 'short>(f: DeviceBox<'long>) -> DeviceBox<'short> { +/// f +/// } +/// # let _ = shorten; +/// ``` +/// +/// An existential lifetime is not a parameter of the struct, so just like a field lifetime it is +/// hidden from the type of the struct. Unlike a field lifetime, it is not tied to a field; the +/// only bounds placed on it are those written in the where clause (here `'x: 'a`, i.e. `'x` lives +/// longer than `'a`). +/// +/// ## Projections and Accessors +/// +/// Since field lifetimes are not parameters of the struct, borrows of the struct cannot carry +/// them. This macro therefore generates several methods for accessing the fields: +/// +/// - `project(self: Pin<&mut Self>)` — the pin projection: `#[pin]` fields are projected as +/// `Pin<&mut T>`, all other fields as `&mut T`. Fields that capture a field or existential +/// lifetime covariantly are only projected as (possibly pinned) shared references; fields with +/// invariant field lifetime capture are omitted entirely. +/// - `with_project(self: Pin<&mut Self>, f)` — calls `f` with a projection in which every +/// visible field has its actual field lifetime, so even invariant captures are visible. +/// - `with_project_ref(self: Pin<&Self>, f)` — the shared version of `with_project`. +/// +/// For all projections, shared-borrowed fields are only accessible with shared references, and +/// mutably borrowed fields are omitted (they are only accessible through the fields that borrow +/// them). +/// +/// Every field (except those borrowed mutably) that captures field or existential lifetimes also +/// gets an accessor method, because they cannot be directly accessed. `fn field(&self)` is +/// generated if all of its captures are covariant, otherwise `fn with_field(&self, f)` is generated +/// where `f` is called with the field at its captured lifetimes. +/// +/// ``` +/// # use pin_init::*; +/// # use std::sync::Mutex; +/// #[pin_data] +/// struct SelfRef { +/// #[uses('_: invariant)] +/// inv_part: Mutex<&'msg str>, +/// part: &'msg str, +/// msg: String, +/// } +/// # stack_pin_init!(let foo = pin_init!(SelfRef { +/// # msg: "hello world".to_owned(), +/// # part: &msg[..5], +/// # inv_part: Mutex::new(&msg[..5]), +/// # })); +/// foo.as_mut().with_project(|proj| { +/// *proj.part = &proj.msg[6..]; +/// }); +/// foo.as_ref().with_project_ref(|proj| { +/// *proj.inv_part.lock().unwrap() = &proj.msg[6..]; +/// }); +/// // Individual covariant field access +/// assert_eq!(*foo.part(), "world"); +/// // Individual invariant field access +/// foo.with_inv_part(|part| assert_eq!(*part.lock().unwrap(), "world")); +/// ``` pub use ::pin_init_internal::pin_data; /// Used to implement `PinnedDrop` safely. @@ -664,11 +840,10 @@ macro_rules! stack_try_pin_init { /// /// Arbitrary Rust expressions can be used to set the value of a variable. /// -/// The fields are initialized in the order that they appear in the initializer. So it is possible -/// to read already initialized fields using raw pointers. -/// -/// IMPORTANT: You are not allowed to create references to fields of the struct inside of the -/// initializer. +/// The fields are initialized in the order that they appear in the initializer. A let binding +/// is generated so already initialized named fields can be read. For [self-referential +/// structs](pin_data#self-referential-structs), you may also use such generated bindings to +/// initialize fields that borrow from them. /// /// # Init-functions /// @@ -834,7 +1009,9 @@ macro_rules! stack_try_pin_init { /// - `unsafe` code must guarantee either full initialization or return an error and allow /// deallocation of the memory. /// - the fields are initialized in the order given in the initializer. -/// - no references to fields are allowed to be created inside of the initializer. +/// - let bindings are generated for already initialized named fields for access within the +/// initializer; unlike [`pin_init!`], creation of self-referential struct is not permitted with +/// `init!`. /// /// This initializer is for initializing data in-place that might later be moved. If you want to /// pin-initialize, use [`pin_init!`]. --- base-commit: 246f6b0262bae1c4a8145804713c0a338f907bc4 change-id: 20261124-dev-pin-init-doc-c488879a1c79 Best regards, -- Gary Guo