pinapod 0.3.0

Zero-copy pod types with derive macros. Alignment-1 representations for zero-overhead data access.
Documentation
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use {crate::traits::ZcElem, core::mem::MaybeUninit};

#[repr(C)]
#[derive(Clone, Copy)]
/// An alignment-one optional value whose storage type satisfies [`ZcElem`].
///
/// Types with restricted Rust bit validity cannot be used as raw storage:
///
/// ```compile_fail
/// use {core::num::NonZeroU8, pinapod::pod::PodOption};
///
/// let _ = PodOption::<NonZeroU8>::none();
/// ```
///
/// Inactive payloads may contain arbitrary account bytes. Borrow the payload
/// through [`get_ref`](Self::get_ref), which returns `None` for an absent value.
/// There is no safe accessor that exposes an inactive payload as `&T`:
///
/// ```compile_fail
/// use pinapod::pod::PodOption;
///
/// let absent = PodOption::<u8>::none();
/// let _ = absent.value_unchecked();
/// ```
pub struct PodOption<T: ZcElem, const PFX: usize = 1> {
    tag: [u8; PFX],
    value: MaybeUninit<T>,
}

const _: () = assert!(core::mem::align_of::<PodOption<u8>>() == 1);
const _: () = assert!(core::mem::align_of::<PodOption<u8, 4>>() == 1);
const _: () = assert!(core::mem::align_of::<PodOption<u8, 8>>() == 1);
const _: () = assert!(core::mem::size_of::<PodOption<[u8; 32], 4>>() == 36);
const _: () = assert!(core::mem::size_of::<PodOption<u8, 8>>() == 9);

impl<T: ZcElem, const PFX: usize> PodOption<T, PFX> {
    const _PFX_CHECK: () = assert!(
        PFX == 1 || PFX == 2 || PFX == 4 || PFX == 8,
        "PodOption<T, PFX>: PFX must be 1, 2, 4, or 8"
    );

    #[inline(always)]
    fn decode_tag(&self) -> u64 {
        #[allow(clippy::let_unit_value)]
        let _ = Self::_PFX_CHECK;
        match PFX {
            1 => u64::from(self.tag[0]),
            2 => u64::from(u16::from_le_bytes([self.tag[0], self.tag[1]])),
            4 => u64::from(u32::from_le_bytes([
                self.tag[0],
                self.tag[1],
                self.tag[2],
                self.tag[3],
            ])),
            _ => u64::from_le_bytes([
                self.tag[0],
                self.tag[1],
                self.tag[2],
                self.tag[3],
                self.tag[4],
                self.tag[5],
                self.tag[6],
                self.tag[7],
            ]),
        }
    }

    #[inline(always)]
    fn encode_tag(v: u32) -> [u8; PFX] {
        #[allow(clippy::let_unit_value)]
        let _ = Self::_PFX_CHECK;
        let mut buf = [0u8; PFX];
        match PFX {
            1 => buf[0] = v as u8,
            2 => {
                let bytes = (v as u16).to_le_bytes();
                buf[0] = bytes[0];
                buf[1] = bytes[1];
            }
            4 => {
                let bytes = v.to_le_bytes();
                buf[..4].copy_from_slice(&bytes);
            }
            _ => {
                let bytes = u64::from(v).to_le_bytes();
                buf.copy_from_slice(&bytes);
            }
        }
        buf
    }

    #[inline(always)]
    pub fn none() -> Self {
        Self {
            tag: [0u8; PFX],
            value: MaybeUninit::zeroed(),
        }
    }

    #[inline(always)]
    pub fn some(value: T) -> Self {
        Self {
            tag: Self::encode_tag(1),
            value: MaybeUninit::new(value),
        }
    }

    #[inline(always)]
    pub fn is_some(&self) -> bool {
        self.decode_tag() == 1
    }

    #[inline(always)]
    pub fn is_none(&self) -> bool {
        !self.is_some()
    }

    #[inline(always)]
    pub fn get(&self) -> Option<T> {
        if self.is_some() {
            Some(unsafe { self.value.assume_init() })
        } else {
            None
        }
    }

    /// Borrow the inner value if `Some`.
    #[inline(always)]
    pub fn get_ref(&self) -> Option<&T> {
        if self.is_some() {
            Some(unsafe { self.value.assume_init_ref() })
        } else {
            None
        }
    }

    #[inline(always)]
    pub fn set(&mut self, value: Option<T>) {
        match value {
            Some(v) => {
                self.tag = Self::encode_tag(1);
                self.value = MaybeUninit::new(v);
            }
            None => {
                self.tag = [0u8; PFX];
                self.value = MaybeUninit::zeroed();
            }
        }
    }

    /// The raw decoded tag.
    ///
    /// This is the unvalidated prefix value. Tags are stored in `PFX` bytes,
    /// so the decoded width is `u64`; only `0` and `1` are valid. Safe
    /// accessors treat every other value as absent.
    pub fn raw_tag(&self) -> u64 {
        self.decode_tag()
    }

    #[inline(always)]
    pub fn tag_valid(&self) -> bool {
        self.raw_tag() <= 1
    }

    /// # Safety
    /// Caller must ensure tag == 1 (Some).
    #[inline(always)]
    pub unsafe fn assume_init_ref(&self) -> &T {
        // SAFETY: upheld by the caller as documented above.
        unsafe { self.value.assume_init_ref() }
    }

    pub fn take(&mut self) -> Option<T> {
        let result = self.get();
        self.tag = [0u8; PFX];
        self.value = MaybeUninit::zeroed();
        result
    }

    pub fn replace(&mut self, value: T) -> Option<T> {
        let old = self.get();
        self.tag = Self::encode_tag(1);
        self.value = MaybeUninit::new(value);
        old
    }

    pub fn clear(&mut self) {
        self.tag = [0u8; PFX];
        self.value = MaybeUninit::zeroed();
    }

    pub fn unwrap_or(self, default: T) -> T {
        match self.get() {
            Some(v) => v,
            None => default,
        }
    }

    pub fn map_or<U>(&self, default: U, f: impl FnOnce(T) -> U) -> U {
        match self.get() {
            Some(v) => f(v),
            None => default,
        }
    }
}

impl<T: ZcElem, const PFX: usize> Default for PodOption<T, PFX> {
    fn default() -> Self {
        Self::none()
    }
}

impl<T: ZcElem + PartialEq, const PFX: usize> PartialEq for PodOption<T, PFX> {
    fn eq(&self, other: &Self) -> bool {
        match (self.get(), other.get()) {
            (Some(a), Some(b)) => a == b,
            (None, None) => true,
            _ => false,
        }
    }
}

impl<T: ZcElem + Eq, const PFX: usize> Eq for PodOption<T, PFX> {}

impl<T: ZcElem + PartialEq, const PFX: usize> PartialEq<Option<T>> for PodOption<T, PFX> {
    fn eq(&self, other: &Option<T>) -> bool {
        match (self.get(), other) {
            (Some(a), Some(b)) => a == *b,
            (None, None) => true,
            _ => false,
        }
    }
}

impl<T: ZcElem + core::fmt::Debug, const PFX: usize> core::fmt::Debug for PodOption<T, PFX> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self.get() {
            Some(v) => write!(f, "Some({:?})", v),
            None => write!(f, "None"),
        }
    }
}

#[cfg(all(kani, feature = "kani"))]
mod kani_proofs {
    use super::*;

    // Macro to generate a proof for each PFX value (1, 2, 4, 8).
    macro_rules! pfx_proofs {
        ($base:ident, $body:expr) => {
            mod $base {
                use super::*;

                #[kani::proof]
                fn pfx1() {
                    const PFX: usize = 1;
                    $body
                }
                #[kani::proof]
                fn pfx2() {
                    const PFX: usize = 2;
                    $body
                }
                #[kani::proof]
                fn pfx4() {
                    const PFX: usize = 4;
                    $body
                }
                #[kani::proof]
                fn pfx8() {
                    const PFX: usize = 8;
                    $body
                }
            }
        };
    }

    pfx_proofs!(some_roundtrip, {
        let v: u8 = kani::any();
        let pod = PodOption::<u8, PFX>::some(v);
        assert!(pod.is_some());
        assert!(!pod.is_none());
        assert!(pod.get() == Some(v), "some roundtrip must preserve value");
    });

    pfx_proofs!(none_roundtrip, {
        let pod = PodOption::<u8, PFX>::none();
        assert!(pod.is_none());
        assert!(!pod.is_some());
        assert!(pod.get() == None, "none must return None");
    });

    pfx_proofs!(set_some_then_get, {
        let v: u8 = kani::any();
        let mut pod = PodOption::<u8, PFX>::none();
        pod.set(Some(v));
        assert!(
            pod.get() == Some(v),
            "set(Some(v)) then get() must return Some(v)"
        );
    });

    pfx_proofs!(set_none_then_get, {
        let v: u8 = kani::any();
        let mut pod = PodOption::<u8, PFX>::some(v);
        pod.set(None);
        assert!(pod.get() == None, "set(None) then get() must return None");
    });

    pfx_proofs!(take_returns_value_and_clears, {
        let v: u8 = kani::any();
        let mut pod = PodOption::<u8, PFX>::some(v);
        let taken = pod.take();
        assert!(taken == Some(v), "take must return the value");
        assert!(pod.is_none(), "take must clear to None");
    });

    pfx_proofs!(replace_returns_old, {
        let old: u8 = kani::any();
        let new: u8 = kani::any();
        let mut pod = PodOption::<u8, PFX>::some(old);
        let returned = pod.replace(new);
        assert!(returned == Some(old), "replace must return old value");
        assert!(pod.get() == Some(new), "replace must set new value");
    });

    pfx_proofs!(replace_on_none_returns_none, {
        let v: u8 = kani::any();
        let mut pod = PodOption::<u8, PFX>::none();
        let returned = pod.replace(v);
        assert!(returned == None, "replace on None must return None");
        assert!(pod.get() == Some(v), "replace must set value");
    });

    pfx_proofs!(unwrap_or_some, {
        let v: u8 = kani::any();
        let default: u8 = kani::any();
        let pod = PodOption::<u8, PFX>::some(v);
        assert!(
            pod.unwrap_or(default) == v,
            "unwrap_or on Some must return value"
        );
    });

    pfx_proofs!(unwrap_or_none, {
        let default: u8 = kani::any();
        let pod = PodOption::<u8, PFX>::none();
        assert!(
            pod.unwrap_or(default) == default,
            "unwrap_or on None must return default"
        );
    });

    pfx_proofs!(default_is_none, {
        let pod = PodOption::<u8, PFX>::default();
        assert!(pod.is_none(), "default must be None");
        assert!(pod.raw_tag() == 0, "default tag must be 0");
    });

    pfx_proofs!(clear_makes_none, {
        let v: u8 = kani::any();
        let mut pod = PodOption::<u8, PFX>::some(v);
        pod.clear();
        assert!(pod.is_none(), "clear must make None");
    });

    pfx_proofs!(get_ref_borrow, {
        let v: u8 = kani::any();
        let pod = PodOption::<u8, PFX>::some(v);
        assert!(pod.get_ref() == Some(&v), "get_ref must borrow the value");
        let none_pod = PodOption::<u8, PFX>::none();
        assert!(none_pod.get_ref().is_none(), "get_ref on None must be None");
    });

    // PFX=1 specific: invalid tag (not 0 or 1) — must not be Some.
    #[kani::proof]
    fn invalid_tag_pfx1() {
        let tag: u8 = kani::any();
        kani::assume(tag != 0 && tag != 1);
        let mut buf = [0u8; 2]; // PodOption<u8, 1>: 1 tag + 1 value
        buf[0] = tag;
        buf[1] = kani::any();
        let pod = unsafe { &*(buf.as_ptr() as *const PodOption<u8, 1>) };
        assert!(!pod.is_some(), "invalid tag must not be Some");
        assert!(pod.get() == None, "invalid tag must return None from get()");
    }

    // PFX=4: any 4-byte tag > 1 rejected.
    #[kani::proof]
    fn tag_rejection_pfx4() {
        let tag: u32 = kani::any();
        kani::assume(tag > 1);
        let mut buf = [0u8; 5]; // PodOption<u8, 4>: 4 tag + 1 value
        buf[..4].copy_from_slice(&tag.to_le_bytes());
        buf[4] = kani::any();
        let pod = unsafe { &*(buf.as_ptr() as *const PodOption<u8, 4>) };
        assert!(!pod.is_some(), "tag > 1 must not be Some");
    }

    // PFX=4: none() produces all-zero payload.
    #[kani::proof]
    fn none_zeroed_pfx4() {
        let pod = PodOption::<u8, 4>::none();
        let bytes = unsafe {
            core::slice::from_raw_parts(&pod as *const _ as *const u8, core::mem::size_of_val(&pod))
        };
        for &b in bytes {
            assert!(b == 0, "none() must produce all-zero bytes");
        }
    }

    pfx_proofs!(inactive_string_payload_is_not_exposed, {
        let mut bytes = [0u8; PFX + 2];
        bytes[PFX] = kani::any();
        bytes[PFX + 1] = kani::any();

        // SAFETY: The complete representation is initialized and alignment one.
        // Its zero tag makes the arbitrary string payload inactive.
        let pod = unsafe { &*(bytes.as_ptr() as *const PodOption<crate::pod::PodString<1>, PFX>) };

        assert!(crate::ZcValidate::validate_ref(pod).is_ok());
        assert!(pod.get().is_none());
        assert!(pod.get_ref().is_none());
    });
}