jiminy-core 0.17.0

Core systems layer for Jiminy: account layout, zero-copy IO, validation, PDA, sysvar access, math, time checks. Declarative macros for error codes, instruction dispatch, and account uniqueness. no_std, no_alloc, no proc macros, BPF-safe.
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
//! Zero-copy struct overlay for account data.
//!
//! Maps a `#[repr(C)]` struct directly onto borrowed account bytes.
//! No deserialization, no copies. Read fields via offset accessors
//! that the [`zero_copy_layout!`](crate::zero_copy_layout!) macro generates for you.
//!
//! ## Why a declarative macro instead of a proc-macro?
//!
//! Jiminy is no-proc-macro by design. `zero_copy_layout!` generates
//! typed accessors using field-offset tables computed from the declared
//! layout. The struct itself is `#[repr(C)]` + `Pod` + `FixedLayout`.
//!
//! ## Usage
//!
//! ```rust,ignore
//! use jiminy_core::zero_copy_layout;
//! use jiminy_core::account::{AccountHeader, Pod, FixedLayout, HEADER_LEN};
//! use hopper_runtime::Address;
//!
//! zero_copy_layout! {
//!     /// My on-chain vault account.
//!     pub struct Vault, discriminator = 1, version = 1 {
//!         header:    AccountHeader = 16,
//!         authority: Address       = 32,
//!         mint:      Address       = 32,
//!         balance:   u64           = 8,
//!         bump:      u8            = 1,
//!     }
//! }
//!
//! // Read from borrowed account data:
//! let vault = Vault::overlay(&data)?;            // &Vault, zero-copy
//! let vault = Vault::overlay_mut(&mut data)?;    // &mut Vault, zero-copy
//! let auth: &Address = &vault.authority;
//!
//! // Constants generated by the macro:
//! assert_eq!(Vault::DISC, 1);
//! assert_eq!(Vault::VERSION, 1);
//! let _id: [u8; 8] = Vault::LAYOUT_ID;
//! ```
//!
//! ## Generated API
//!
//! The macro emits for each struct:
//!
//! ### Constants
//!
//! `LEN`, `DISC`, `VERSION`, `LAYOUT_ID`
//!
//! ### Raw-byte methods (operate on `&[u8]` / `&mut [u8]`)
//!
//! | Method | Returns | What it checks |
//! |--------|---------|----------------|
//! | `overlay(data)` | `&Self` | size only |
//! | `overlay_mut(data)` | `&mut Self` | size only |
//! | `read(data)` | `Self` (copy) | size only (alignment-safe) |
//! | `load_checked(data)` | `&Self` | disc + version + layout_id + size |
//! | `load_checked_mut(data)` | `&mut Self` | disc + version + layout_id + size |
//!
//! ### Tiered loading (operate on `AccountView`, see `view` module)
//!
//! | Tier | Method | Returns | Validates |
//! |------|--------|---------|-----------|
//! | 1 | `load(account, program_id)` | `VerifiedAccount` | owner + disc + version + layout_id + exact size |
//! | 1m | `load_mut(account, program_id)` | `VerifiedAccountMut` | same as Tier 1 |
//! | 2 | `load_foreign(account, owner)` | `VerifiedAccount` | owner + layout_id + exact size |
//! | 4 | `unsafe load_unchecked(data)` | `&Self` | none |
//! | 5 | `load_unverified_overlay(data)` | `(&Self, bool)` | header if present, fallback |
//!
//! ### Borrow-splitting
//!
//! | Method | Returns |
//! |--------|---------|
//! | `split_fields(data)` | `(FieldRef, FieldRef, ...)` |
//! | `split_fields_mut(data)` | `(FieldMut, FieldMut, ...)` |

/// Generate `const OFFSET_<FIELD>` for each field in a layout.
///
/// Uses a TT-muncher to accumulate offsets from field sizes. Called
/// internally by `zero_copy_layout!`.
#[doc(hidden)]
#[macro_export]
macro_rules! __gen_offsets {
    // Base case: no fields left.
    (@acc $offset:expr ;) => {};
    // Recursive case: emit one const, advance accumulator.
    (@acc $offset:expr ; $field:ident = $fsize:expr, $( $rest_field:ident = $rest_fsize:expr, )*) => {
        /// Byte offset of this field within the account layout.
        #[allow(non_upper_case_globals)]
        #[doc(hidden)]
        pub const $field: usize = $offset;
        $crate::__gen_offsets!(@acc ($offset + $fsize) ; $( $rest_field = $rest_fsize, )*);
    };
    // Entry point: start accumulator at 0.
    ( $( $field:ident = $fsize:expr ),+ $(,)? ) => {
        $crate::__gen_offsets!(@acc 0usize ; $( $field = $fsize, )+);
    };
}

/// Emit a single `pub const <field>: usize` constant.
#[doc(hidden)]
#[macro_export]
macro_rules! __gen_offset_const {
    ($field:ident, $offset:expr) => {
        #[doc = concat!("Byte offset of the `", stringify!($field), "` field.")]
        #[allow(non_upper_case_globals)]
        pub const $field: usize = $offset;
    };
}

/// Map any token to `FieldRef<'_>` in type position. Used by `zero_copy_layout!`
/// to repeat `FieldRef` once per field in the return-type tuple.
#[doc(hidden)]
#[macro_export]
macro_rules! __field_ref_type {
    ($ignore:ident) => { $crate::abi::FieldRef<'_> };
}

/// Map any token to `FieldMut<'_>` in type position. Used by `zero_copy_layout!`
/// to repeat `FieldMut` once per field in the return-type tuple.
#[doc(hidden)]
#[macro_export]
macro_rules! __field_mut_type {
    ($ignore:ident) => { $crate::abi::FieldMut<'_> };
}

/// Map a Rust identifier type to its canonical hash string.
///
/// Used internally by [`zero_copy_layout!`] to produce deterministic
/// layout IDs regardless of type aliases.
#[doc(hidden)]
#[macro_export]
macro_rules! __canonical_type {
    (u8) => { "u8" };
    (u16) => { "u16" };
    (u32) => { "u32" };
    (u64) => { "u64" };
    (u128) => { "u128" };
    (i8) => { "i8" };
    (i16) => { "i16" };
    (i32) => { "i32" };
    (i64) => { "i64" };
    (i128) => { "i128" };
    (bool) => { "bool" };
    (Address) => { "pubkey" };
    (AccountHeader) => { "header" };
    // Jiminy-native Le* types hash to the same canonical strings.
    (LeU16) => { "u16" };
    (LeU32) => { "u32" };
    (LeU64) => { "u64" };
    (LeU128) => { "u128" };
    (LeI16) => { "i16" };
    (LeI32) => { "i32" };
    (LeI64) => { "i64" };
    (LeI128) => { "i128" };
    (LeBool) => { "bool" };
    ($other:ident) => { stringify!($other) };
}

/// Declare a zero-copy account layout with typed field accessors.
///
/// Each field specifies `name: Type = byte_size`. The macro generates a
/// `#[repr(C)]` struct along with `Pod`, `FixedLayout`, overlay methods,
/// and a deterministic `LAYOUT_ID` computed via SHA-256.
///
/// ```rust,ignore
/// zero_copy_layout! {
///     pub struct Pool, discriminator = 3, version = 1 {
///         header:     AccountHeader = 16,
///         authority:  Address       = 32,
///         reserve_a:  u64           = 8,
///         reserve_b:  u64           = 8,
///     }
/// }
/// ```
///
/// ## Layout Inheritance
///
/// Use `extends = ParentType` to assert that a new version is a
/// byte-compatible superset of an older version. The macro verifies
/// at compile time that the child has the same discriminator and is
/// at least as large as the parent:
///
/// ```rust,ignore
/// zero_copy_layout! {
///     pub struct PoolV2, discriminator = 3, version = 2, extends = Pool {
///         header:     AccountHeader = 16,
///         authority:  Address       = 32,
///         reserve_a:  u64           = 8,
///         reserve_b:  u64           = 8,
///         fee_bps:    u16           = 2,
///     }
/// }
/// ```
#[macro_export]
macro_rules! zero_copy_layout {
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident, discriminator = $disc:literal, version = $ver:literal {
            $( $(#[$fmeta:meta])* $field:ident : $fty:ident = $fsize:expr ),+ $(,)?
        }
    ) => {
        $(#[$meta])*
        #[repr(C)]
        #[derive(Clone, Copy)]
        $vis struct $name {
            $( $(#[$fmeta])* pub $field: $fty ),+
        }

        // SAFETY: The type is repr(C), Copy, and all fields implement Pod.
        // The caller guarantees all bit patterns are valid.
        unsafe impl $crate::account::Pod for $name {}

        impl $crate::account::FixedLayout for $name {
            const SIZE: usize = 0 $( + $fsize )+;
        }

        // Compile-time assertion: size_of must equal the declared LEN.
        // Catches cases where a field's declared byte size doesn't match
        // its actual Rust type size.
        const _: () = assert!(
            core::mem::size_of::<$name>() == 0 $( + $fsize )+,
            "size_of does not match declared LEN - check field sizes"
        );

        // Compile-time assertion: alignment must not exceed 8 bytes.
        // Solana's loader aligns program input to 8-byte boundaries.
        // Types requiring >8 alignment (e.g. u128) would cause UB on-chain.
        // Use Le128 / Le* wrappers for 16-byte scalars.
        const _: () = assert!(
            core::mem::align_of::<$name>() <= 8,
            "layout alignment exceeds 8 bytes - use Le* wrappers for u128 fields"
        );

        impl $name {
            /// Total byte size of this account layout.
            pub const LEN: usize = 0 $( + $fsize )+;

            /// Account discriminator byte.
            pub const DISC: u8 = $disc;

            /// Account schema version.
            pub const VERSION: u8 = $ver;

            /// Deterministic ABI fingerprint (first 8 bytes of SHA-256).
            ///
            /// Hash input: `"jiminy:v1:<Name>:<version>:<field>:<canonical_type>:<size>,..."`
            pub const LAYOUT_ID: [u8; 8] = {
                const INPUT: &str = concat!(
                    "jiminy:v1:",
                    stringify!($name), ":",
                    stringify!($ver), ":",
                    $( stringify!($field), ":", $crate::__canonical_type!($fty), ":", stringify!($fsize), ",", )+
                );
                const HASH: [u8; 32] = $crate::__sha256_const(INPUT.as_bytes());
                [HASH[0], HASH[1], HASH[2], HASH[3], HASH[4], HASH[5], HASH[6], HASH[7]]
            };

            /// Overlay an immutable reference onto borrowed account data.
            ///
            /// Returns `AccountDataTooSmall` if the slice is shorter than
            /// the layout size.
            #[inline(always)]
            pub fn overlay(data: &[u8]) -> Result<&Self, $crate::ProgramError> {
                $crate::account::pod_from_bytes::<Self>(data)
            }

            /// Overlay a mutable reference onto borrowed account data.
            ///
            /// Returns `AccountDataTooSmall` if the slice is shorter than
            /// the layout size.
            #[inline(always)]
            pub fn overlay_mut(data: &mut [u8]) -> Result<&mut Self, $crate::ProgramError> {
                $crate::account::pod_from_bytes_mut::<Self>(data)
            }

            /// Read a copy of this struct from a byte slice.
            ///
            /// Alignment-safe on all targets (uses `read_unaligned`
            /// internally). Ideal for native tests.
            #[inline(always)]
            pub fn read(data: &[u8]) -> Result<Self, $crate::ProgramError> {
                $crate::account::pod_read::<Self>(data)
            }

            /// Load with full header validation (disc + version + layout_id),
            /// then overlay immutably.
            #[inline(always)]
            pub fn load_checked(data: &[u8]) -> Result<&Self, $crate::ProgramError> {
                $crate::account::check_header(data, Self::DISC, Self::VERSION, &Self::LAYOUT_ID)?;
                $crate::account::pod_from_bytes::<Self>(data)
            }

            /// Load with full header validation (disc + version + layout_id),
            /// then overlay mutably.
            #[inline(always)]
            pub fn load_checked_mut(data: &mut [u8]) -> Result<&mut Self, $crate::ProgramError> {
                $crate::account::check_header(data, Self::DISC, Self::VERSION, &Self::LAYOUT_ID)?;
                $crate::account::pod_from_bytes_mut::<Self>(data)
            }

            // ── Tiered loading API ───────────────────────────────────────

            /// **Tier 1: Standard path.** Validate owner + disc + version +
            /// exact size + layout_id, then borrow.
            ///
            /// Returns a `VerifiedAccount` whose `get()` is infallible.
            /// This is the recommended way to load a Jiminy account.
            #[inline(always)]
            pub fn load<'a>(
                account: &'a $crate::AccountView,
                program_id: &$crate::Address,
            ) -> Result<$crate::account::VerifiedAccount<'a, Self>, $crate::ProgramError> {
                let data = $crate::account::view::validate_account(
                    account, program_id, Self::DISC, Self::VERSION, &Self::LAYOUT_ID, Self::LEN,
                )?;
                $crate::account::VerifiedAccount::new(data)
            }

            /// **Tier 1 (mutable): Standard mutable path.** Same checks as
            /// `load()` but returns `VerifiedAccountMut` for write access.
            #[inline(always)]
            pub fn load_mut<'a>(
                account: &'a $crate::AccountView,
                program_id: &$crate::Address,
            ) -> Result<$crate::account::VerifiedAccountMut<'a, Self>, $crate::ProgramError> {
                let data = $crate::account::view::validate_account_mut(
                    account, program_id, Self::DISC, Self::VERSION, &Self::LAYOUT_ID, Self::LEN,
                )?;
                $crate::account::VerifiedAccountMut::new(data)
            }

            /// **Tier 2: Cross-program read.** Validate owner + layout_id
            /// + exact size, then borrow. Use for reading foreign program
            /// accounts whose discriminator conventions you don't control.
            ///
            /// Returns a `VerifiedAccount` whose `get()` is infallible.
            #[inline(always)]
            pub fn load_foreign<'a>(
                account: &'a $crate::AccountView,
                expected_owner: &$crate::Address,
            ) -> Result<$crate::account::VerifiedAccount<'a, Self>, $crate::ProgramError> {
                let data = $crate::account::view::validate_foreign(
                    account, expected_owner, &Self::LAYOUT_ID, Self::LEN,
                )?;
                $crate::account::VerifiedAccount::new(data)
            }

            /// **Tier 4: Unsafe unchecked load.** No validation at all.
            ///
            /// # Safety
            ///
            /// Caller must ensure the data represents a valid instance of
            /// this layout. Intended for legacy / non-Jiminy accounts
            /// where manual validation has already been performed.
            #[inline(always)]
            pub unsafe fn load_unchecked(data: &[u8]) -> Result<&Self, $crate::ProgramError> {
                $crate::account::pod_from_bytes::<Self>(data)
            }

            /// **Tier 5: Unverified overlay.** Try header + layout_id
            /// validation; if it fails, fall back to a plain overlay.
            ///
            /// No ABI guarantees. Returns `(overlay, validated)` where
            /// `validated` is `true` when the header matched. Useful for
            /// indexers/tooling. Never use in on-chain program logic.
            #[inline(always)]
            pub fn load_unverified_overlay(data: &[u8]) -> Result<(&Self, bool), $crate::ProgramError> {
                $crate::account::view::load_unverified_overlay::<Self>(
                    data, Self::DISC, Self::VERSION, &Self::LAYOUT_ID,
                )
            }

            // ── Const field offsets ──────────────────────────────────────

            $crate::__gen_offsets!( $( $field = $fsize ),+ );

            // ── Borrow-splitting ─────────────────────────────────────────

            /// Split borrowed data into independent per-field `FieldRef` slices.
            ///
            /// Each `FieldRef` holds a non-overlapping `&[u8]` subslice,
            /// enabling typed reads of multiple fields without aliasing issues.
            #[inline]
            #[allow(unused_variables)]
            pub fn split_fields(data: &[u8]) -> Result<( $( $crate::__field_ref_type!($field), )+ ), $crate::ProgramError> {
                if data.len() < Self::LEN {
                    return Err($crate::ProgramError::AccountDataTooSmall);
                }
                let mut _pos = 0usize;
                Ok(( $({
                    let start = _pos;
                    _pos += $fsize;
                    $crate::abi::FieldRef::new(&data[start..start + $fsize])
                }, )+ ))
            }

            /// Split mutably borrowed data into independent per-field `FieldMut` slices.
            ///
            /// Enables safe simultaneous mutation of multiple fields via
            /// non-overlapping `&mut [u8]` subslices. The borrow checker sees
            /// independent mutable references - no `unsafe` needed.
            ///
            /// ```rust,ignore
            /// let (header, balance, authority) = Vault::split_fields_mut(&mut data)?;
            /// balance.write_u64(1000);
            /// authority.copy_from(&new_auth);
            /// ```
            #[inline]
            #[allow(unused_variables)]
            pub fn split_fields_mut(data: &mut [u8]) -> Result<( $( $crate::__field_mut_type!($field), )+ ), $crate::ProgramError> {
                if data.len() < Self::LEN {
                    return Err($crate::ProgramError::AccountDataTooSmall);
                }
                let _remaining = &mut data[..Self::LEN];
                $(
                    let ($field, _remaining) = _remaining.split_at_mut($fsize);
                )+
                Ok(( $( $crate::abi::FieldMut::new($field), )+ ))
            }
        }
    };

    // ── extends arm ──────────────────────────────────────────────────
    //
    // Identical to the base arm but adds compile-time assertions that
    // the child layout is a byte-compatible superset of the parent:
    //   - same discriminator
    //   - child LEN >= parent LEN
    //   - child VERSION > parent VERSION
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident, discriminator = $disc:literal, version = $ver:literal, extends = $parent:ty {
            $( $(#[$fmeta:meta])* $field:ident : $fty:ident = $fsize:expr ),+ $(,)?
        }
    ) => {
        // Delegate to the base arm for all standard codegen.
        $crate::zero_copy_layout! {
            $(#[$meta])*
            $vis struct $name, discriminator = $disc, version = $ver {
                $( $(#[$fmeta])* $field : $fty = $fsize ),+
            }
        }

        // Compile-time V2 ⊃ V1 assertions.
        const _: () = assert!(
            <$name>::DISC == <$parent>::DISC,
            "extends: child and parent must share the same discriminator"
        );
        const _: () = assert!(
            <$name>::LEN >= <$parent>::LEN,
            "extends: child layout must be at least as large as parent (append-only)"
        );
        const _: () = assert!(
            <$name>::VERSION > <$parent>::VERSION,
            "extends: child version must be strictly greater than parent version"
        );
    };
}

/// Assert that an existing non-Jiminy account layout is safe to overlay.
///
/// Use this for live programs that already have account bytes in production and
/// cannot adopt Jiminy's 16-byte header or `layout_id` convention yet. The
/// macro does **not** generate a struct, header, discriminator, or ABI hash. It
/// only proves that the type has opted into Jiminy's `Pod + FixedLayout`
/// contract and that the Rust layout still matches the declared legacy size.
///
/// ```rust,ignore
/// #[repr(C)]
/// #[derive(Clone, Copy)]
/// pub struct ArgusVaultV1 {
///     pub authority: Address,
///     pub balance: LeU64,
/// }
///
/// unsafe impl jiminy_core::account::Pod for ArgusVaultV1 {}
/// impl jiminy_core::account::FixedLayout for ArgusVaultV1 {
///     const SIZE: usize = 40;
/// }
///
/// jiminy_core::assert_legacy_layout!(ArgusVaultV1, 40);
/// ```
#[macro_export]
macro_rules! assert_legacy_layout {
    ($ty:ty, $size:expr $(,)?) => {
        $crate::assert_legacy_layout!(@inner $ty, $size, 8usize);
    };
    ($ty:ty, size = $size:expr $(,)?) => {
        $crate::assert_legacy_layout!(@inner $ty, $size, 8usize);
    };
    ($ty:ty, size = $size:expr, max_align = $max_align:expr $(,)?) => {
        $crate::assert_legacy_layout!(@inner $ty, $size, $max_align);
    };
    (@inner $ty:ty, $size:expr, $max_align:expr) => {
        const _: fn() = {
            fn __jiminy_assert_legacy_layout<T: $crate::account::Pod + $crate::account::FixedLayout>() {}
            __jiminy_assert_legacy_layout::<$ty>
        };
        const _: () = assert!(
            core::mem::size_of::<$ty>() == $size,
            "legacy layout size_of does not match declared size"
        );
        const _: () = assert!(
            <$ty as $crate::account::FixedLayout>::SIZE == $size,
            "legacy layout FixedLayout::SIZE does not match declared size"
        );
        const _: () = assert!(
            core::mem::align_of::<$ty>() <= $max_align,
            "legacy layout alignment exceeds configured maximum"
        );
    };
}

/// Count the number of token-tree repetitions (segments).
#[doc(hidden)]
#[macro_export]
macro_rules! __count_segments {
    () => { 0usize };
    ($head:ident $($tail:ident)*) => { 1usize + $crate::__count_segments!($($tail)*) };
}

/// Generate `pub const <seg_name>: usize` index constants for each segment.
#[doc(hidden)]
#[macro_export]
macro_rules! __gen_segment_indices {
    (@acc $offset:expr ;) => {};
    (@acc $offset:expr ; $seg_name:ident, $( $rest:ident, )*) => {
        #[doc = concat!("Index of the `", stringify!($seg_name), "` segment in the segment table.")]
        #[allow(non_upper_case_globals)]
        pub const $seg_name: usize = $offset;
        $crate::__gen_segment_indices!(@acc ($offset + 1usize) ; $( $rest, )*);
    };
    ($( $seg_name:ident ),+ $(,)?) => {
        $crate::__gen_segment_indices!(@acc 0usize ; $( $seg_name, )+);
    };
}

/// Declare a segmented zero-copy account layout.
///
/// Combines a fixed prefix (same as `zero_copy_layout!`) with one or
/// more variable-length segments. The segment table sits right after
/// the fixed fields, and the macro generates typed accessors per
/// segment.
///
/// ```rust,ignore
/// use jiminy_core::segmented_layout;
/// use jiminy_core::account::{AccountHeader, Pod, FixedLayout};
/// use hopper_runtime::Address;
///
/// // A simple element type.
/// #[repr(C)]
/// #[derive(Clone, Copy, Debug)]
/// pub struct Order {
///     pub price: [u8; 8],
///     pub qty: [u8; 8],
/// }
/// unsafe impl Pod for Order {}
/// impl FixedLayout for Order { const SIZE: usize = 16; }
///
/// segmented_layout! {
///     pub struct OrderBook, discriminator = 5, version = 1 {
///         header:     AccountHeader = 16,
///         market:     Address       = 32,
///     } segments {
///         bids: Order = 16,
///         asks: Order = 16,
///     }
/// }
///
/// // Wire layout (example with 3 bids, 2 asks, Order = 16):
/// //   Offset 0–15: header, 16–47: market,
/// //   48–55: bids descriptor, 56–63: asks descriptor,
/// //   64+: bids data, then asks data.
///
/// // Access:
/// let table = OrderBook::segment_table(&data)?;
/// let bids = SegmentSlice::<Order>::from_descriptor(&data, &table.descriptor(0)?)?;
/// let first_bid: Order = bids.read(0)?;
/// ```
///
/// ## Generated API
///
/// In addition to the standard `zero_copy_layout!` API on the fixed
/// prefix struct:
///
/// - `SEGMENT_COUNT: usize`: number of declared segments
/// - `FIXED_LEN: usize`: byte size of the fixed prefix
/// - `TABLE_OFFSET: usize`: byte offset where the segment table starts
/// - `DATA_START_OFFSET: usize`: byte offset where segment data starts
/// - `MIN_ACCOUNT_SIZE: usize`: minimum account size (fixed + table, no data)
/// - `SEGMENTED_LAYOUT_ID: [u8; 8]`: layout hash including segment entries
/// - `segment_sizes() -> &[u16]`: expected element sizes per segment
/// - `segment_table(data) -> SegmentTable`: parse immutable segment table
/// - `segment_table_mut(data) -> SegmentTableMut`: parse mutable segment table
/// - `validate_segments(data)`: full segment table validation
/// - `init_segments(data, counts)`: write initial segment table
/// - `compute_account_size(counts) -> usize`: total account size for given counts
#[macro_export]
macro_rules! segmented_layout {
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident, discriminator = $disc:literal, version = $ver:literal {
            $( $(#[$fmeta:meta])* $field:ident : $fty:ident = $fsize:expr ),+ $(,)?
        } segments {
            $( $seg_name:ident : $seg_ty:ident = $seg_elem_size:expr ),+ $(,)?
        }
    ) => {
        // Generate the fixed prefix struct with zero_copy_layout!.
        $crate::zero_copy_layout! {
            $(#[$meta])*
            $vis struct $name, discriminator = $disc, version = $ver {
                $( $(#[$fmeta])* $field : $fty = $fsize ),+
            }
        }

        impl $name {
            /// Number of dynamic segments in this layout.
            pub const SEGMENT_COUNT: usize = $crate::__count_segments!($($seg_name)+);

            /// Byte size of the fixed prefix (before the segment table).
            pub const FIXED_LEN: usize = Self::LEN;

            /// Byte offset where the segment table begins.
            pub const TABLE_OFFSET: usize = Self::LEN;

            /// Byte offset where segment data starts (after fixed + table).
            pub const DATA_START_OFFSET: usize =
                Self::LEN + Self::SEGMENT_COUNT * $crate::account::segment::SEGMENT_DESC_SIZE;

            /// Deterministic ABI fingerprint including segment declarations.
            ///
            /// Extends the base hash with `seg:<name>:<type>:<size>` entries.
            pub const SEGMENTED_LAYOUT_ID: [u8; 8] = {
                const INPUT: &str = concat!(
                    "jiminy:v1:",
                    stringify!($name), ":",
                    stringify!($ver), ":",
                    $( stringify!($field), ":", $crate::__canonical_type!($fty), ":", stringify!($fsize), ",", )+
                    $( "seg:", stringify!($seg_name), ":", stringify!($seg_ty), ":", stringify!($seg_elem_size), ",", )+
                );
                const HASH: [u8; 32] = $crate::__sha256_const(INPUT.as_bytes());
                [HASH[0], HASH[1], HASH[2], HASH[3], HASH[4], HASH[5], HASH[6], HASH[7]]
            };

            /// Expected element sizes for each segment, in declaration order.
            #[inline(always)]
            pub const fn segment_sizes() -> &'static [u16] {
                // Compile-time assertion: declared sizes must match type sizes.
                $(
                    const _: () = assert!(
                        <$seg_ty as $crate::account::FixedLayout>::SIZE == $seg_elem_size,
                        "segmented_layout! segment size does not match type FixedLayout::SIZE"
                    );
                )+
                &[ $( <$seg_ty as $crate::account::FixedLayout>::SIZE as u16, )+ ]
            }

            /// Minimum account size: fixed prefix + segment table (no elements).
            pub const MIN_ACCOUNT_SIZE: usize = Self::DATA_START_OFFSET;

            /// Read the segment table from account data.
            #[inline(always)]
            pub fn segment_table(data: &[u8]) -> Result<$crate::account::segment::SegmentTable<'_>, $crate::ProgramError> {
                if data.len() < Self::DATA_START_OFFSET {
                    return Err($crate::ProgramError::AccountDataTooSmall);
                }
                $crate::account::segment::SegmentTable::from_bytes(
                    &data[Self::TABLE_OFFSET..],
                    Self::SEGMENT_COUNT,
                )
            }

            /// Read the mutable segment table from account data.
            #[inline(always)]
            pub fn segment_table_mut(data: &mut [u8]) -> Result<$crate::account::segment::SegmentTableMut<'_>, $crate::ProgramError> {
                if data.len() < Self::DATA_START_OFFSET {
                    return Err($crate::ProgramError::AccountDataTooSmall);
                }
                $crate::account::segment::SegmentTableMut::from_bytes(
                    &mut data[Self::TABLE_OFFSET..],
                    Self::SEGMENT_COUNT,
                )
            }

            /// Validate the segment table against the account data.
            ///
            /// Checks element sizes, bounds, ordering, and no overlaps.
            #[inline]
            pub fn validate_segments(data: &[u8]) -> Result<(), $crate::ProgramError> {
                let table = Self::segment_table(data)?;
                table.validate(data.len(), Self::segment_sizes(), Self::DATA_START_OFFSET)
            }

            /// Initialize segment descriptors in a freshly allocated account.
            ///
            /// `counts` gives the initial element count per segment.
            /// Each segment's capacity is set equal to its count (tight
            /// fit, no room for push). Offsets are computed by laying out
            /// segments contiguously based on these counts.
            ///
            /// If you plan to `push` elements later, use
            /// [`init_segments_with_capacity`](Self::init_segments_with_capacity)
            /// instead to pre-allocate space.
            #[inline]
            pub fn init_segments(
                data: &mut [u8],
                counts: &[u16],
            ) -> Result<(), $crate::ProgramError> {
                if counts.len() != Self::SEGMENT_COUNT {
                    return Err($crate::ProgramError::InvalidArgument);
                }
                let sizes = Self::segment_sizes();
                // count == capacity for pre-populated init (tight fit).
                let specs: [_; Self::SEGMENT_COUNT] = {
                    let mut arr = [(0u16, 0u16, 0u16); Self::SEGMENT_COUNT];
                    let mut i = 0;
                    while i < Self::SEGMENT_COUNT {
                        arr[i] = (sizes[i], counts[i], counts[i]);
                        i += 1;
                    }
                    arr
                };
                $crate::account::segment::SegmentTableMut::init(
                    &mut data[Self::TABLE_OFFSET..],
                    Self::DATA_START_OFFSET as u32,
                    &specs,
                )?;
                Ok(())
            }

            /// Initialize segment descriptors with pre-allocated capacity.
            ///
            /// `capacities` gives the maximum number of elements each
            /// segment can hold. Offsets are spaced by capacity so that
            /// `push` cannot overwrite an adjacent segment. All counts
            /// start at zero.
            ///
            /// Use [`compute_account_size`](Self::compute_account_size)
            /// with the same `capacities` to determine the account size.
            ///
            /// ```rust,ignore
            /// let size = OrderBook::compute_account_size(&[100, 100])?;
            /// // ... create account with `size` bytes ...
            /// OrderBook::init_segments_with_capacity(&mut data, &[100, 100])?;
            /// // Now you can safely push up to 100 bids and 100 asks.
            /// ```
            #[inline]
            pub fn init_segments_with_capacity(
                data: &mut [u8],
                capacities: &[u16],
            ) -> Result<(), $crate::ProgramError> {
                if capacities.len() != Self::SEGMENT_COUNT {
                    return Err($crate::ProgramError::InvalidArgument);
                }
                let sizes = Self::segment_sizes();
                // count = 0, capacity = capacities[i] (push workflow).
                let specs: [_; Self::SEGMENT_COUNT] = {
                    let mut arr = [(0u16, 0u16, 0u16); Self::SEGMENT_COUNT];
                    let mut i = 0;
                    while i < Self::SEGMENT_COUNT {
                        arr[i] = (sizes[i], 0, capacities[i]);
                        i += 1;
                    }
                    arr
                };
                $crate::account::segment::SegmentTableMut::init(
                    &mut data[Self::TABLE_OFFSET..],
                    Self::DATA_START_OFFSET as u32,
                    &specs,
                )?;
                Ok(())
            }

            /// Compute the total account size for given capacities.
            ///
            /// `capacities[i]` is the number of elements to reserve
            /// space for in segment `i`. The account must be created with
            /// at least this many bytes to hold the segment table plus
            /// the full reserved regions.
            #[inline]
            pub fn compute_account_size(capacities: &[u16]) -> Result<usize, $crate::ProgramError> {
                if capacities.len() != Self::SEGMENT_COUNT {
                    return Err($crate::ProgramError::InvalidArgument);
                }
                let sizes = Self::segment_sizes();
                let mut total = Self::DATA_START_OFFSET;
                let mut i = 0;
                while i < Self::SEGMENT_COUNT {
                    let seg_bytes = (capacities[i] as usize)
                        .checked_mul(sizes[i] as usize)
                        .ok_or($crate::ProgramError::ArithmeticOverflow)?;
                    total = total
                        .checked_add(seg_bytes)
                        .ok_or($crate::ProgramError::ArithmeticOverflow)?;
                    i += 1;
                }
                Ok(total)
            }

            // ── Segment index constants ──────────────────────────────────

            $crate::__gen_segment_indices!($($seg_name),+);

            // ── Typed segment accessors ──────────────────────────────────

            /// Get an immutable typed view over a segment by index.
            ///
            /// ```rust,ignore
            /// let bids = OrderBook::segment::<Order>(&data, OrderBook::bids)?;
            /// let first = bids.read(0)?;
            /// ```
            #[inline(always)]
            pub fn segment<T: $crate::account::Pod + $crate::account::FixedLayout>(
                data: &[u8],
                index: usize,
            ) -> Result<$crate::account::segment::SegmentSlice<'_, T>, $crate::ProgramError> {
                let desc = {
                    let table = Self::segment_table(data)?;
                    table.descriptor(index)?
                };
                $crate::account::segment::SegmentSlice::from_descriptor(data, &desc)
            }

            /// Get a mutable typed view over a segment by index.
            ///
            /// ```rust,ignore
            /// let mut bids = OrderBook::segment_mut::<Order>(&mut data, OrderBook::bids)?;
            /// bids.set(0, &new_order)?;
            /// ```
            #[inline(always)]
            pub fn segment_mut<T: $crate::account::Pod + $crate::account::FixedLayout>(
                data: &mut [u8],
                index: usize,
            ) -> Result<$crate::account::segment::SegmentSliceMut<'_, T>, $crate::ProgramError> {
                let desc = {
                    let table = Self::segment_table(data)?;
                    table.descriptor(index)?
                };
                $crate::account::segment::SegmentSliceMut::from_descriptor(data, &desc)
            }

            /// Push an element at the end of a segment.
            ///
            /// Updates both the data and the descriptor count automatically.
            ///
            /// ```rust,ignore
            /// OrderBook::push::<Order>(&mut data, OrderBook::bids, &new_order)?;
            /// ```
            #[inline(always)]
            pub fn push<T: $crate::account::Pod + $crate::account::FixedLayout>(
                data: &mut [u8],
                index: usize,
                value: &T,
            ) -> Result<(), $crate::ProgramError> {
                $crate::account::segment::segment_push::<T>(
                    data, Self::TABLE_OFFSET, Self::SEGMENT_COUNT, index, value,
                )
            }

            /// Remove an element by swapping it with the last. Returns the
            /// removed element. O(1) but does not preserve order.
            ///
            /// ```rust,ignore
            /// let removed = OrderBook::swap_remove::<Order>(&mut data, OrderBook::bids, 0)?;
            /// ```
            #[inline(always)]
            pub fn swap_remove<T: $crate::account::Pod + $crate::account::FixedLayout>(
                data: &mut [u8],
                index: usize,
                elem_index: u16,
            ) -> Result<T, $crate::ProgramError> {
                $crate::account::segment::segment_swap_remove::<T>(
                    data, Self::TABLE_OFFSET, Self::SEGMENT_COUNT, index, elem_index,
                )
            }
        }
    };
}