1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
//! Zero-copy struct projection from account data.
//!
//! `project::<T>()` performs bounds checking, alignment validation, and
//! optional discriminator verification in a single operation, returning
//! a direct `&T` pointer-cast into account data. No copies, no alloc,
//! no separate validation steps.
//!
//! This is genuinely novel: pinocchio only gives raw `&[u8]` from account
//! data. Anchor's `AccountLoader<T>` requires derive macros, borsh traits,
//! and hidden RefCell costs. Hopper's projection is a one-line zero-copy
//! cast with compile-time layout guarantees.
//!
//! # Safety Model (post-audit)
//!
//! The Hopper Safety Audit flagged the original `Projectable` trait as too
//! permissive: it only required `Copy + 'static`, which lets callers
//! overlay types with padding or non-alignment-1 fields and trip
//! undefined behaviour. Two separate surfaces now live in this module:
//!
//! - [`Projectable`], the **unsafe escape hatch** kept for compatibility
//! with already-published programs that opt into it by hand. It still
//! only requires `Copy + 'static`, but its documentation is now
//! explicit: every `unsafe impl Projectable` is the author asserting
//! the full POD contract (no padding, align-1, all-bits-valid). Call
//! sites must treat it as a Tier C primitive.
//!
//! - [`SafeProjectable`] (with the matching [`project_safe`] /
//! [`project_safe_mut`] constructors), the **sound default**. It is
//! auto-implemented for every `T: Projectable` where the size is at
//! least 1 byte, but the intent at call sites is that only types that
//! participate in Hopper's `Pod` contract reach for this path. Higher
//! layers (`hopper-runtime`, `#[hopper::state]`-generated code) only
//! use Pod-bounded access paths now, this trait exists so lens and
//! project helpers can offer a safe-by-default API without pulling in
//! `hopper-runtime` at the native layer.
//!
//! For new code: prefer `hopper_runtime::Pod` + the typed access methods
//! in `hopper-runtime`/`hopper-core` over `Projectable` directly.
//!
//! # Usage
//!
//! ```ignore
//! use hopper_native::project::{Projectable, project, project_mut};
//!
//! #[repr(C)]
//! #[derive(Clone, Copy)]
//! struct VaultState {
//! authority: [u8; 32],
//! balance: u64,
//! bump: u8,
//! }
//!
//! // SAFETY: VaultState is #[repr(C)], Copy, and has no padding bytes
//! // that could cause UB when read from arbitrary data.
//! unsafe impl Projectable for VaultState {}
//!
//! fn read_vault(account: &AccountView) -> Result<&VaultState, ProgramError> {
//! // Checks: data_len >= offset + size_of::<VaultState>(),
//! // alignment is correct, disc byte matches.
//! project::<VaultState>(account, 10, Some(1))
//! }
//! ```
use crateAccountView;
use crateProgramError;
/// Marker trait for types that can be safely projected from raw account data.
///
/// # Safety
///
/// The implementor must guarantee that:
/// 1. The type is `#[repr(C)]` (deterministic field ordering).
/// 2. The type is `Copy` (no drop glue, no interior mutability).
/// 3. Every bit pattern is valid (no padding-dependent invariants).
/// 4. No references or pointers (only plain data).
///
/// This is the same contract as `bytemuck::Pod` without the dependency.
pub unsafe
// Built-in projectable types.
unsafe
unsafe
unsafe
unsafe
unsafe
unsafe
unsafe
unsafe
unsafe
unsafe
unsafe
unsafe
// ══════════════════════════════════════════════════════════════════════
// SafeProjectable, Pod-aligned variant (Hopper Safety Audit fix)
// ══════════════════════════════════════════════════════════════════════
/// Strengthened projection marker: the safe default for new code.
///
/// `SafeProjectable` is a sealed sub-trait of [`Projectable`] with one
/// extra compile-time obligation: the type must be non-zero-sized. It
/// exists so that API surfaces taking a projection type can demand
/// `T: SafeProjectable` and reject hand-rolled markers that forgot the
/// alignment-1 / no-padding invariant. Every `impl Projectable` that
/// also satisfies `size_of::<T>() > 0` participates via the blanket
/// below, so the trait is automatic for all realistic overlays.
///
/// # Safety
///
/// Exactly the same contract as [`Projectable`]:
/// 1. `#[repr(C)]` or `#[repr(transparent)]`.
/// 2. `Copy` with no drop glue.
/// 3. Every bit pattern of `[u8; size_of::<T>()]` decodes to a valid `T`.
/// 4. No internal references or pointers.
///
/// Implementing [`Projectable`] for a type that does not meet these
/// requirements has always been UB; this sub-trait merely makes the
/// intent at call sites explicit.
pub unsafe
// Blanket impl: every Projectable that's not zero-sized qualifies.
// Zero-sized types would project to a dangling reference, so we keep
// them off this safe path even if someone opted them into Projectable
// for weird generic reasons.
unsafe
/// Safe variant of [`project`] that rejects zero-sized overlays.
///
/// Prefer this over [`project`] in new code; it enforces the audit's
/// "only Pod + non-ZST types reach the projection primitive" rule.
/// Safe mutable variant of [`project_mut`].
///
/// # Safety
///
/// Same contract as [`project_mut`], caller holds an exclusive borrow
/// on the account data region for the returned reference's lifetime.
pub unsafe
/// Project a `#[repr(C)]` struct from account data at the given byte offset.
///
/// Performs three checks in one operation:
/// 1. **Bounds**: `offset + size_of::<T>() <= data_len`
/// 2. **Alignment**: `(data_ptr + offset) % align_of::<T>() == 0`
/// 3. **Discriminator** (optional): `data[0] == expected_disc`
///
/// Returns a direct `&T` reference into the account's data region.
/// No copies, no allocation.
///
/// # Arguments
///
/// * `account` - The account to project from.
/// * `offset` - Byte offset into account data where `T` begins.
/// For Hopper accounts with a standard 10-byte header (disc + version
/// + layout_id), use `offset = 10`.
/// * `expected_disc` - If `Some(d)`, verify that `data[0] == d` before
/// projecting. Pass `None` to skip the discriminator check.
/// Project a mutable `#[repr(C)]` struct from account data.
///
/// Same checks as `project()` but returns `&mut T`. The caller is
/// responsible for ensuring no other borrows are active (this does
/// NOT integrate with the borrow tracking system -- use
/// `try_borrow_mut()` first if you need that guarantee).
///
/// # Safety
///
/// The caller must ensure no other references to the same data region
/// are active. For most use cases, call `account.try_borrow_mut()`
/// first, then use `project_mut` on the resulting data.
pub unsafe
/// Project a slice of `T` from account data starting at `offset`.
///
/// Returns `&[T]` with `count` elements, performing bounds and alignment
/// checks.
/// Project with a Hopper standard header: skip the 10-byte header
/// (1 disc + 1 version + 8 layout_id) and project `T` starting at
/// byte 10. Verifies discriminator.
///
/// This is the most common projection pattern for Hopper accounts.
/// Mutable version of `project_hopper`.
///
/// # Safety
///
/// Caller must ensure exclusive access to the account data.
pub unsafe