peam-ssz 2.0.1

Minimal performance-focused SSZ encoding, decoding, and merkleization crate extracted from Peam
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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
//! SSZ vectors and lists.
//!
//! These wrappers own a `Vec<T>` but enforce SSZ length semantics and provide
//! encode/decode/hash-tree-root implementations for both fixed-size and
//! variable-size element types.
use crate::ssz::hash::{
    BYTES_PER_CHUNK, chunkify_fixed_non_empty, merkleize_with_limit, mix_in_length,
};
use crate::ssz::{HashTreeRoot, SszDecode, SszElement, SszEncode, SszFixedLen};
use crate::types::bytes::Bytes32;
use crate::unsafe_vec::{write_at, write_bytes_at};

/// Fixed-length homogeneous sequence of exactly `LENGTH` elements.
///
/// SSZ encoding: fixed-size elements are concatenated directly; variable-size
/// elements use a 4-byte offset table followed by serialized payloads.
/// `hash_tree_root` merkleizes element roots (or packed bytes for fixed-size
/// primitives) with limit = `LENGTH`. No mix-in-length is applied because the
/// size is static.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SszVector<T, const LENGTH: usize> {
    /// Backing elements in SSZ order.
    data: Vec<T>,
}

/// Variable-length homogeneous sequence bounded by `LIMIT` elements.
///
/// SSZ encoding matches [`SszVector`] but the element count is inferred from
/// the offset table (variable-size) or total byte length (fixed-size).
/// `hash_tree_root` merkleizes element roots with limit = `LIMIT`, then mixes
/// in the actual length as a separate 32-byte little-endian chunk.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SszList<T, const LIMIT: usize> {
    /// Backing elements in SSZ order.
    data: Vec<T>,
}

#[inline]
fn pack_basic_fixed_chunks<T>(items: &[T], elem_len: usize) -> Vec<Bytes32>
where
    T: SszEncode,
{
    let total = items.len() * elem_len;
    if total == 0 {
        return Vec::new();
    }

    if elem_len > BYTES_PER_CHUNK {
        let mut bytes = Vec::with_capacity(total);
        for item in items {
            item.encode_ssz_into(&mut bytes);
        }
        return chunkify_fixed_non_empty(&bytes);
    }

    let chunk_count = total.div_ceil(BYTES_PER_CHUNK);
    let mut chunks = Vec::with_capacity(chunk_count);
    let mut chunk = [0u8; 32];
    let mut filled = 0usize;

    for item in items {
        let mut elem_buf = [0u8; 32];
        unsafe { item.write_fixed_ssz(elem_buf.as_mut_ptr()) };
        let mut src_start = 0usize;

        while src_start < elem_len {
            let space = BYTES_PER_CHUNK - filled;
            let to_copy = (elem_len - src_start).min(space);
            chunk[filled..filled + to_copy]
                .copy_from_slice(&elem_buf[src_start..src_start + to_copy]);
            filled += to_copy;
            src_start += to_copy;

            if filled == BYTES_PER_CHUNK {
                chunks.push(Bytes32::from(chunk));
                chunk = [0u8; 32];
                filled = 0;
            }
        }
    }

    if filled != 0 {
        chunks.push(Bytes32::from(chunk));
    }

    chunks
}

impl<T, const LENGTH: usize> SszVector<T, LENGTH> {
    /// Constructs a vector and enforces the exact SSZ element count.
    pub fn new(data: Vec<T>) -> Result<Self, String> {
        if data.len() != LENGTH {
            return Err(format!(
                "SszVector expects {} elements, got {}",
                LENGTH,
                data.len()
            ));
        }
        Ok(Self { data })
    }

    /// Returns the backing elements as a slice.
    #[inline]
    pub fn as_slice(&self) -> &[T] {
        &self.data
    }

    /// Returns the backing elements as a mutable slice.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        &mut self.data
    }

    /// Iterates over elements in SSZ order.
    #[inline]
    pub fn iter(&self) -> core::slice::Iter<'_, T> {
        self.data.iter()
    }

    /// Iterates mutably over elements in SSZ order.
    #[inline]
    pub fn iter_mut(&mut self) -> core::slice::IterMut<'_, T> {
        self.data.iter_mut()
    }

    /// Returns the exact element count for this vector.
    #[inline]
    pub fn len(&self) -> usize {
        LENGTH
    }

    /// Returns `true` when the vector length is zero.
    #[inline]
    pub fn is_empty(&self) -> bool {
        LENGTH == 0
    }

    /// Consumes the wrapper and returns the backing elements.
    #[inline]
    pub fn into_inner(self) -> Vec<T> {
        self.data
    }

    /// Returns the element at `index`, if present.
    #[inline]
    pub fn get(&self, index: usize) -> Option<&T> {
        self.data.get(index)
    }

    /// Returns the element at `index` mutably, if present.
    #[inline]
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        self.data.get_mut(index)
    }

    /// Returns the first element, if present.
    #[inline]
    pub fn first(&self) -> Option<&T> {
        self.data.first()
    }

    /// Returns the first element mutably, if present.
    #[inline]
    pub fn first_mut(&mut self) -> Option<&mut T> {
        self.data.first_mut()
    }

    /// Returns the last element, if present.
    #[inline]
    pub fn last(&self) -> Option<&T> {
        self.data.last()
    }

    /// Returns the last element mutably, if present.
    #[inline]
    pub fn last_mut(&mut self) -> Option<&mut T> {
        self.data.last_mut()
    }

    /// Encodes a fixed-size vector into caller-provided storage without allocation.
    ///
    /// `out` must be exactly `T::fixed_len() * LENGTH` bytes long.
    pub fn encode_ssz_fixed_into(&self, out: &mut [u8])
    where
        T: SszFixedLen + SszEncode + SszElement,
    {
        let elem_len = T::fixed_len();
        let expected = elem_len
            .checked_mul(LENGTH)
            .expect("SszVector fixed length overflows usize");
        debug_assert!(
            out.len() == expected,
            "fixed-size SszVector encode expects {} bytes, got {}",
            expected,
            out.len()
        );
        for (idx, item) in self.data.iter().enumerate() {
            let offset = idx * elem_len;
            unsafe { item.write_fixed_ssz(out.as_mut_ptr().add(offset)) };
        }
    }

    /// Validates vector byte layout before calling raw [`SszDecode`].
    ///
    /// This is mainly useful in tests and harnesses that want checked decoding
    /// without duplicating offset-table validation logic.
    pub fn decode_ssz_checked(bytes: &[u8]) -> Result<Self, String>
    where
        T: SszDecode + SszElement,
    {
        if let Some(elem_len) = T::fixed_len_opt() {
            let expected = elem_len * LENGTH;
            if bytes.len() != expected {
                return Err(format!(
                    "SszVector expects {} bytes, got {}",
                    expected,
                    bytes.len()
                ));
            }
            return Self::decode_ssz(bytes);
        }

        let table_len = 4 * LENGTH;
        if bytes.len() < table_len {
            return Err("SszVector offset table exceeds input length".to_string());
        }

        let off = u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;
        if off != table_len {
            return Err("SszVector first offset must equal table length".to_string());
        }

        let mut prev = off;
        for i in 1..LENGTH {
            let off_start = i * 4;
            let off_end = off_start + 4;
            let off = u32::from_le_bytes(bytes[off_start..off_end].try_into().unwrap()) as usize;
            if off < prev || off > bytes.len() {
                return Err("SszVector offsets are invalid".to_string());
            }
            prev = off;
        }
        Self::decode_ssz(bytes)
    }
}

impl<T, const LIMIT: usize> Default for SszList<T, LIMIT> {
    fn default() -> Self {
        Self { data: Vec::new() }
    }
}

impl<T, const LIMIT: usize> SszList<T, LIMIT> {
    /// Constructs a list and enforces the SSZ list limit.
    pub fn new(data: Vec<T>) -> Result<Self, String> {
        if data.len() > LIMIT {
            return Err(format!(
                "SszList length {} exceeds limit {}",
                data.len(),
                LIMIT
            ));
        }
        Ok(Self { data })
    }

    /// Returns the backing elements as a slice.
    #[inline]
    pub fn as_slice(&self) -> &[T] {
        &self.data
    }

    /// Returns the backing elements as a mutable slice.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        &mut self.data
    }

    /// Iterates over elements in SSZ order.
    #[inline]
    pub fn iter(&self) -> core::slice::Iter<'_, T> {
        self.data.iter()
    }

    /// Iterates mutably over elements in SSZ order.
    #[inline]
    pub fn iter_mut(&mut self) -> core::slice::IterMut<'_, T> {
        self.data.iter_mut()
    }

    /// Returns the current element count.
    #[inline]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns `true` when the list has no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Consumes the wrapper and returns the backing elements.
    #[inline]
    pub fn into_inner(self) -> Vec<T> {
        self.data
    }

    /// Returns the element at `index`, if present.
    #[inline]
    pub fn get(&self, index: usize) -> Option<&T> {
        self.data.get(index)
    }

    /// Returns the element at `index` mutably, if present.
    #[inline]
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        self.data.get_mut(index)
    }

    /// Returns the first element, if present.
    #[inline]
    pub fn first(&self) -> Option<&T> {
        self.data.first()
    }

    /// Returns the first element mutably, if present.
    #[inline]
    pub fn first_mut(&mut self) -> Option<&mut T> {
        self.data.first_mut()
    }

    /// Returns the last element, if present.
    #[inline]
    pub fn last(&self) -> Option<&T> {
        self.data.last()
    }

    /// Returns the last element mutably, if present.
    #[inline]
    pub fn last_mut(&mut self) -> Option<&mut T> {
        self.data.last_mut()
    }

    /// Appends an element when doing so stays within `LIMIT`.
    #[inline]
    pub fn push(&mut self, value: T) -> Result<(), String> {
        if self.data.len() == LIMIT {
            return Err(format!("SszList length {} exceeds limit {}", LIMIT + 1, LIMIT));
        }
        self.data.push(value);
        Ok(())
    }

    /// Appends `additional` copies of `value` while preserving the list limit.
    ///
    /// This is a fast path for callers that need bulk growth with a repeated
    /// `Copy` value, such as zero-filling fixed-size roots.
    #[inline]
    pub fn extend_copy(&mut self, additional: usize, value: T) -> Result<(), String>
    where
        T: Copy,
    {
        if additional == 0 {
            return Ok(());
        }
        let new_len = self
            .data
            .len()
            .checked_add(additional)
            .ok_or_else(|| "SszList length overflow".to_string())?;
        if new_len > LIMIT {
            return Err(format!("SszList length {} exceeds limit {}", new_len, LIMIT));
        }

        let start = self.data.len();
        self.data.reserve(additional);
        unsafe { self.data.set_len(new_len) };
        for idx in 0..additional {
            unsafe { write_at(&mut self.data, start + idx, value) };
        }
        Ok(())
    }

    /// Removes and returns the last element, if present.
    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        self.data.pop()
    }

    /// Truncates the list to `len` elements.
    #[inline]
    pub fn truncate(&mut self, len: usize) {
        self.data.truncate(len);
    }

    /// Removes all elements from the list.
    #[inline]
    pub fn clear(&mut self) {
        self.data.clear();
    }

    /// Validates list byte layout and limit checks before decoding elements.
    ///
    /// This is mainly useful in tests and harnesses that want checked decoding
    /// without duplicating offset-table validation logic.
    pub fn decode_ssz_checked(bytes: &[u8]) -> Result<Self, String>
    where
        T: SszDecode + SszElement,
    {
        if let Some(elem_len) = T::fixed_len_opt() {
            if !bytes.len().is_multiple_of(elem_len) {
                return Err("SszList length is not a multiple of element size".to_string());
            }
            let len = bytes.len() / elem_len;
            if len > LIMIT {
                return Err(format!("SszList length {} exceeds limit {}", len, LIMIT));
            }
            return Self::decode_ssz(bytes);
        }

        if bytes.is_empty() {
            return Ok(Self { data: Vec::new() });
        }
        if bytes.len() < 4 {
            return Err("SszList missing offset table".to_string());
        }

        let first = u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;
        if !first.is_multiple_of(4) {
            return Err("SszList first offset must be multiple of 4".to_string());
        }
        let len = first / 4;
        if len > LIMIT {
            return Err(format!("SszList length {} exceeds limit {}", len, LIMIT));
        }
        let table_len = 4 * len;
        if first != table_len {
            return Err("SszList first offset must equal table length".to_string());
        }
        if bytes.len() < table_len {
            return Err("SszList offset table exceeds input length".to_string());
        }

        let mut prev = table_len;
        for i in 1..len {
            let off_start = i * 4;
            let off_end = off_start + 4;
            let off = u32::from_le_bytes(bytes[off_start..off_end].try_into().unwrap()) as usize;
            if off < prev || off > bytes.len() {
                return Err("SszList offsets are invalid".to_string());
            }
            prev = off;
        }
        Self::decode_ssz(bytes)
    }
}

impl<T, const LENGTH: usize> SszEncode for SszVector<T, LENGTH>
where
    T: SszEncode + SszElement,
{
    fn encode_ssz(&self) -> Vec<u8> {
        if let Some(elem_len) = T::fixed_len_opt() {
            let total = elem_len * LENGTH;
            let mut out: Vec<u8> = Vec::with_capacity(total);
            unsafe { out.set_len(total) };
            for (idx, item) in self.data.iter().enumerate() {
                let offset = idx * elem_len;
                unsafe { item.write_fixed_ssz(out.as_mut_ptr().add(offset)) };
            }
            return out;
        }

        let count = self.data.len();
        let mut offsets = Vec::with_capacity(count);
        let mut elems = Vec::with_capacity(count);
        unsafe {
            offsets.set_len(count);
            elems.set_len(count);
        }
        let mut cursor = 4 * count;
        for (idx, item) in self.data.iter().enumerate() {
            let bytes = item.encode_ssz();
            // SSZ offsets are u32. We keep the direct cast here because the
            // Ethereum-spec objects this crate targets do not approach 4 GiB
            // variable payload sections in practice.
            unsafe { write_at(&mut offsets, idx, cursor as u32) };
            cursor += bytes.len();
            unsafe { write_at(&mut elems, idx, bytes) };
        }
        let mut out = Vec::with_capacity(cursor);
        unsafe { out.set_len(cursor) };
        let mut cursor = 0usize;
        for off in offsets {
            unsafe { write_bytes_at(&mut out, cursor, &off.to_le_bytes()) };
            cursor += 4;
        }
        for bytes in elems {
            unsafe { write_bytes_at(&mut out, cursor, &bytes) };
            cursor += bytes.len();
        }
        out
    }

    fn encode_ssz_checked(&self) -> Result<Vec<u8>, String> {
        if let Some(elem_len) = T::fixed_len_opt() {
            let total = elem_len * LENGTH;
            let mut out = Vec::with_capacity(total);
            for item in &self.data {
                let bytes = item.encode_ssz_checked()?;
                if bytes.len() != elem_len {
                    return Err(format!(
                        "fixed-size SszVector element encoded to {} bytes, expected {}",
                        bytes.len(),
                        elem_len
                    ));
                }
                out.extend_from_slice(&bytes);
            }
            return Ok(out);
        }

        let count = self.data.len();
        let mut offsets = Vec::with_capacity(count);
        let mut elems = Vec::with_capacity(count);
        let mut cursor = 4 * count;
        for item in &self.data {
            let bytes = item.encode_ssz_checked()?;
            // SSZ offsets are u32. We keep the direct cast here because the
            // Ethereum-spec objects this crate targets do not approach 4 GiB
            // variable payload sections in practice.
            offsets.push(cursor as u32);
            cursor += bytes.len();
            elems.push(bytes);
        }
        let mut out = Vec::with_capacity(cursor);
        unsafe { out.set_len(cursor) };
        let mut cursor = 0usize;
        for off in offsets {
            unsafe { write_bytes_at(&mut out, cursor, &off.to_le_bytes()) };
            cursor += 4;
        }
        for bytes in elems {
            unsafe { write_bytes_at(&mut out, cursor, &bytes) };
            cursor += bytes.len();
        }
        Ok(out)
    }

    fn encode_ssz_into(&self, out: &mut Vec<u8>) {
        if let Some(elem_len) = T::fixed_len_opt() {
            let total = elem_len * LENGTH;
            let start = out.len();
            out.reserve(total);
            unsafe { out.set_len(start + total) };
            for (idx, item) in self.data.iter().enumerate() {
                let offset = start + idx * elem_len;
                unsafe { item.write_fixed_ssz(out.as_mut_ptr().add(offset)) };
            }
            return;
        }

        let count = self.data.len();
        let table_start = out.len();
        let table_len = 4 * count;
        out.reserve(table_len);
        unsafe { out.set_len(table_start + table_len) };
        for (idx, item) in self.data.iter().enumerate() {
            let offset = (out.len() - table_start) as u32;
            unsafe { write_bytes_at(out, table_start + idx * 4, &offset.to_le_bytes()) };
            item.encode_ssz_into(out);
        }
    }

    unsafe fn write_fixed_ssz(&self, dst: *mut u8) {
        let Some(elem_len) = T::fixed_len_opt() else {
            panic!("variable-size SszVector cannot be written via write_fixed_ssz");
        };
        for (idx, item) in self.data.iter().enumerate() {
            let offset = idx * elem_len;
            unsafe { item.write_fixed_ssz(dst.add(offset)) };
        }
    }
}

impl<T, const LIMIT: usize> SszEncode for SszList<T, LIMIT>
where
    T: SszEncode + SszElement,
{
    fn encode_ssz(&self) -> Vec<u8> {
        if let Some(elem_len) = T::fixed_len_opt() {
            let total = elem_len * self.data.len();
            let mut out: Vec<u8> = Vec::with_capacity(total);
            unsafe { out.set_len(total) };
            for (idx, item) in self.data.iter().enumerate() {
                let offset = idx * elem_len;
                unsafe { item.write_fixed_ssz(out.as_mut_ptr().add(offset)) };
            }
            return out;
        }

        let count = self.data.len();
        let mut offsets = Vec::with_capacity(count);
        let mut elems = Vec::with_capacity(count);
        unsafe {
            offsets.set_len(count);
            elems.set_len(count);
        }
        let mut cursor = 4 * count;
        for (idx, item) in self.data.iter().enumerate() {
            let bytes = item.encode_ssz();
            unsafe { write_at(&mut offsets, idx, cursor as u32) };
            cursor += bytes.len();
            unsafe { write_at(&mut elems, idx, bytes) };
        }
        let mut out = Vec::with_capacity(cursor);
        let table_len = 4 * count;
        unsafe { out.set_len(cursor) };
        for (idx, off) in offsets.iter().enumerate() {
            unsafe { write_bytes_at(&mut out, idx * 4, &off.to_le_bytes()) };
        }
        let mut payload_cursor = table_len;
        for bytes in elems {
            unsafe { write_bytes_at(&mut out, payload_cursor, &bytes) };
            payload_cursor += bytes.len();
        }
        out
    }

    fn encode_ssz_checked(&self) -> Result<Vec<u8>, String> {
        if let Some(elem_len) = T::fixed_len_opt() {
            let total = elem_len * self.data.len();
            let mut out = Vec::with_capacity(total);
            for item in &self.data {
                let bytes = item.encode_ssz_checked()?;
                if bytes.len() != elem_len {
                    return Err(format!(
                        "fixed-size SszList element encoded to {} bytes, expected {}",
                        bytes.len(),
                        elem_len
                    ));
                }
                out.extend_from_slice(&bytes);
            }
            return Ok(out);
        }

        let count = self.data.len();
        let mut offsets = Vec::with_capacity(count);
        let mut elems = Vec::with_capacity(count);
        let mut cursor = 4 * count;
        for item in &self.data {
            let bytes = item.encode_ssz_checked()?;
            // SSZ offsets are u32. We keep the direct cast here because the
            // Ethereum-spec objects this crate targets do not approach 4 GiB
            // variable payload sections in practice.
            offsets.push(cursor as u32);
            cursor += bytes.len();
            elems.push(bytes);
        }
        let mut out = Vec::with_capacity(cursor);
        let table_len = 4 * count;
        unsafe { out.set_len(cursor) };
        for (idx, off) in offsets.iter().enumerate() {
            unsafe { write_bytes_at(&mut out, idx * 4, &off.to_le_bytes()) };
        }
        let mut payload_cursor = table_len;
        for bytes in elems {
            unsafe { write_bytes_at(&mut out, payload_cursor, &bytes) };
            payload_cursor += bytes.len();
        }
        Ok(out)
    }

    fn encode_ssz_into(&self, out: &mut Vec<u8>) {
        if let Some(elem_len) = T::fixed_len_opt() {
            let total = elem_len * self.data.len();
            let start = out.len();
            out.reserve(total);
            unsafe { out.set_len(start + total) };
            for (idx, item) in self.data.iter().enumerate() {
                let offset = start + idx * elem_len;
                unsafe { item.write_fixed_ssz(out.as_mut_ptr().add(offset)) };
            }
            return;
        }

        let count = self.data.len();
        let table_start = out.len();
        let table_len = 4 * count;
        out.reserve(table_len);
        unsafe { out.set_len(table_start + table_len) };
        for (idx, item) in self.data.iter().enumerate() {
            let offset = (out.len() - table_start) as u32;
            unsafe { write_bytes_at(out, table_start + idx * 4, &offset.to_le_bytes()) };
            item.encode_ssz_into(out);
        }
    }

    unsafe fn write_fixed_ssz(&self, _dst: *mut u8) {
        panic!("SszList is variable-size and cannot be written via write_fixed_ssz");
    }
}

impl<T, const LENGTH: usize> SszDecode for SszVector<T, LENGTH>
where
    T: SszDecode + SszElement,
{
    fn decode_ssz(bytes: &[u8]) -> Result<Self, String> {
        if let Some(elem_len) = T::fixed_len_opt() {
            let mut data = Vec::with_capacity(LENGTH);
            unsafe { data.set_len(LENGTH) };
            for i in 0..LENGTH {
                let start = i * elem_len;
                let end = start + elem_len;
                let x = match T::decode_ssz(&bytes[start..end]) {
                    Ok(val) => val,
                    Err(err) => {
                        unsafe {
                            let ptr: *mut T = data.as_mut_ptr();
                            for j in 0..i {
                                core::ptr::drop_in_place(ptr.add(j));
                            }
                            data.set_len(0);
                        }
                        return Err(err);
                    }
                };
                unsafe { write_at(&mut data, i, x) };
            }
            return Ok(Self { data });
        }

        let mut data = Vec::with_capacity(LENGTH);
        unsafe { data.set_len(LENGTH) };
        for i in 0..LENGTH {
            let off_start = i * 4;
            let off_end = off_start + 4;
            let start = u32::from_le_bytes(bytes[off_start..off_end].try_into().unwrap()) as usize;
            let end = if i + 1 < LENGTH {
                let next_start = (i + 1) * 4;
                let next_end = next_start + 4;
                u32::from_le_bytes(bytes[next_start..next_end].try_into().unwrap()) as usize
            } else {
                bytes.len()
            };
            let x = match T::decode_ssz(&bytes[start..end]) {
                Ok(val) => val,
                Err(err) => {
                    unsafe {
                        let ptr: *mut T = data.as_mut_ptr();
                        for j in 0..i {
                            core::ptr::drop_in_place(ptr.add(j));
                        }
                        data.set_len(0);
                    }
                    return Err(err);
                }
            };
            unsafe { write_at(&mut data, i, x) };
        }
        Ok(Self { data })
    }
}

impl<T, const LIMIT: usize> SszDecode for SszList<T, LIMIT>
where
    T: SszDecode + SszElement,
{
    fn decode_ssz(bytes: &[u8]) -> Result<Self, String> {
        if let Some(elem_len) = T::fixed_len_opt() {
            let len = bytes.len() / elem_len;
            let mut data = Vec::with_capacity(len);
            unsafe { data.set_len(len) };
            for i in 0..len {
                let start = i * elem_len;
                let end = start + elem_len;
                let x = match T::decode_ssz(&bytes[start..end]) {
                    Ok(val) => val,
                    Err(err) => {
                        unsafe {
                            let ptr: *mut T = data.as_mut_ptr();
                            for j in 0..i {
                                core::ptr::drop_in_place(ptr.add(j));
                            }
                            data.set_len(0);
                        }
                        return Err(err);
                    }
                };
                unsafe { write_at(&mut data, i, x) };
            }
            return Ok(Self { data });
        }

        if bytes.is_empty() {
            return Ok(Self { data: Vec::new() });
        }

        let first = u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;
        let len = first / 4;
        let mut data = Vec::with_capacity(len);
        unsafe { data.set_len(len) };
        for i in 0..len {
            let off_start = i * 4;
            let off_end = off_start + 4;
            let start = u32::from_le_bytes(bytes[off_start..off_end].try_into().unwrap()) as usize;
            let end = if i + 1 < len {
                let next_start = (i + 1) * 4;
                let next_end = next_start + 4;
                u32::from_le_bytes(bytes[next_start..next_end].try_into().unwrap()) as usize
            } else {
                bytes.len()
            };
            let x = match T::decode_ssz(&bytes[start..end]) {
                Ok(val) => val,
                Err(err) => {
                    unsafe {
                        let ptr: *mut T = data.as_mut_ptr();
                        for j in 0..i {
                            core::ptr::drop_in_place(ptr.add(j));
                        }
                        data.set_len(0);
                    }
                    return Err(err);
                }
            };
            unsafe { write_at(&mut data, i, x) };
        }
        Ok(Self { data })
    }
}

impl<T, const LENGTH: usize> HashTreeRoot for SszVector<T, LENGTH>
where
    T: SszEncode + SszElement + HashTreeRoot,
{
    fn hash_tree_root(&self) -> [u8; 32] {
        if let Some(elem_len) = T::fixed_len_opt().filter(|_| T::tree_pack_basic()) {
            let chunks = pack_basic_fixed_chunks(&self.data, elem_len);
            let limit_chunks = (LENGTH * elem_len).div_ceil(BYTES_PER_CHUNK);
            let root =
                merkleize_with_limit(&chunks, limit_chunks).unwrap_or_else(|_| Bytes32::zero());
            return *root.as_ref();
        }

        let count = self.data.len();
        let mut chunks = Vec::with_capacity(count);
        unsafe { chunks.set_len(count) };
        for (i, item) in self.data.iter().enumerate() {
            let root = Bytes32::from(item.hash_tree_root());
            unsafe { write_at(&mut chunks, i, root) };
        }
        let root = merkleize_with_limit(&chunks, LENGTH).unwrap_or_else(|_| Bytes32::zero());
        *root.as_ref()
    }
}

impl<T, const LIMIT: usize> HashTreeRoot for SszList<T, LIMIT>
where
    T: SszEncode + SszElement + HashTreeRoot,
{
    fn hash_tree_root(&self) -> [u8; 32] {
        if let Some(elem_len) = T::fixed_len_opt().filter(|_| T::tree_pack_basic()) {
            let chunks = pack_basic_fixed_chunks(&self.data, elem_len);
            let limit_chunks = (LIMIT * elem_len).div_ceil(BYTES_PER_CHUNK);
            let root =
                merkleize_with_limit(&chunks, limit_chunks).unwrap_or_else(|_| Bytes32::zero());
            let mixed = mix_in_length(&root, self.data.len());
            return *mixed.as_ref();
        }

        let count = self.data.len();
        let mut chunks = Vec::with_capacity(count);
        unsafe { chunks.set_len(count) };
        for (i, item) in self.data.iter().enumerate() {
            let root = Bytes32::from(item.hash_tree_root());
            unsafe { write_at(&mut chunks, i, root) };
        }
        let root = merkleize_with_limit(&chunks, LIMIT).unwrap_or_else(|_| Bytes32::zero());
        let mixed = mix_in_length(&root, count);
        *mixed.as_ref()
    }
}

impl<T, const LENGTH: usize> SszElement for SszVector<T, LENGTH>
where
    T: SszElement,
{
    fn fixed_len_opt() -> Option<usize> {
        if LENGTH == 0 {
            // Zero-length vectors encode to empty bytes, but treating them as
            // fixed-size list elements would make `SszList<SszVector<_, 0>, _>`
            // ambiguous to decode because every list length would serialize to
            // the same empty payload. Keep them on the offset-table path.
            return None;
        }
        T::fixed_len_opt().and_then(|elem_len| elem_len.checked_mul(LENGTH))
    }
}

impl<T, const LIMIT: usize> SszElement for SszList<T, LIMIT> {}

#[cfg(test)]
mod tests {
    use super::{SszList, SszVector};
    use crate::ssz::SszEncode;
    use crate::types::bitlist::BitVector;

    #[test]
    fn list_encode_into_matches_encode_ssz_for_nested_lists() {
        let inner = SszList::<u64, 8>::new(vec![1, 2, 3, 4]).unwrap();
        let outer = SszList::<SszList<u64, 8>, 4>::new(vec![inner.clone(), inner]).unwrap();

        let mut out = Vec::new();
        outer.encode_ssz_into(&mut out);

        assert_eq!(out, outer.encode_ssz());
    }

    #[test]
    fn vector_encode_into_matches_encode_ssz_for_nested_lists() {
        let inner = SszList::<u64, 8>::new(vec![1, 2, 3, 4]).unwrap();
        let vector = SszVector::<SszList<u64, 8>, 2>::new(vec![inner.clone(), inner]).unwrap();

        let mut out = Vec::new();
        vector.encode_ssz_into(&mut out);

        assert_eq!(out, vector.encode_ssz());
    }

    #[test]
    fn list_of_fixed_vectors_encodes_without_offsets() {
        let first = SszVector::<u64, 2>::new(vec![1, 2]).unwrap();
        let second = SszVector::<u64, 2>::new(vec![3, 4]).unwrap();
        let outer = SszList::<SszVector<u64, 2>, 4>::new(vec![first, second]).unwrap();

        let mut expected = Vec::new();
        for value in [1u64, 2, 3, 4] {
            expected.extend_from_slice(&value.to_le_bytes());
        }

        assert_eq!(outer.encode_ssz(), expected);
    }

    #[test]
    fn list_of_zero_length_vectors_uses_offsets_and_round_trips() {
        let first = SszVector::<u64, 0>::new(vec![]).unwrap();
        let second = SszVector::<u64, 0>::new(vec![]).unwrap();
        let outer = SszList::<SszVector<u64, 0>, 4>::new(vec![first, second]).unwrap();

        assert_eq!(outer.encode_ssz(), vec![8, 0, 0, 0, 8, 0, 0, 0]);
        let decoded = SszList::<SszVector<u64, 0>, 4>::decode_ssz_checked(&outer.encode_ssz())
            .expect("zero-length vector list should decode");
        assert_eq!(decoded, outer);
    }

    #[test]
    fn list_encode_ssz_checked_validates_elements() {
        let invalid = BitVector::<3> { data: vec![0xff] };
        let list = SszList::<BitVector<3>, 4>::new(vec![invalid]).unwrap();

        assert_eq!(
            list.encode_ssz_checked().unwrap_err(),
            "BitVector has non-zero unused bits"
        );
    }

    #[test]
    fn vector_encode_ssz_checked_validates_elements() {
        let invalid = BitVector::<3> { data: vec![0xff] };
        let vector = SszVector::<BitVector<3>, 1>::new(vec![invalid]).unwrap();

        assert_eq!(
            vector.encode_ssz_checked().unwrap_err(),
            "BitVector has non-zero unused bits"
        );
    }

    #[test]
    fn fixed_vector_fixed_encode_matches_vec_encode() {
        let vector = SszVector::<u64, 2>::new(vec![1, 2]).unwrap();

        let mut out = [0u8; 16];
        vector.encode_ssz_fixed_into(&mut out);

        assert_eq!(out.as_slice(), vector.encode_ssz().as_slice());
    }

    #[test]
    fn vector_mut_access_preserves_length_invariant() {
        let mut vector = SszVector::<u64, 2>::new(vec![1, 2]).unwrap();
        vector.as_mut_slice()[0] = 9;
        *vector.get_mut(1).unwrap() = 7;

        assert_eq!(vector.as_slice(), &[9, 7]);
        assert_eq!(vector.len(), 2);
    }

    #[test]
    fn list_push_respects_limit() {
        let mut list = SszList::<u64, 2>::new(vec![1]).unwrap();
        list.push(2).unwrap();

        assert_eq!(list.as_slice(), &[1, 2]);
        assert_eq!(
            list.push(3).unwrap_err(),
            "SszList length 3 exceeds limit 2"
        );
    }

    #[test]
    fn list_mutators_update_contents_without_exposing_backing_vec() {
        let mut list = SszList::<u64, 4>::new(vec![1, 2, 3]).unwrap();
        *list.first_mut().unwrap() = 10;
        *list.last_mut().unwrap() = 30;
        list.truncate(2);
        list.push(40).unwrap();
        assert_eq!(list.pop(), Some(40));
        list.clear();

        assert!(list.is_empty());
    }

    #[test]
    fn list_extend_copy_respects_limit_and_repeats_value() {
        let mut list = SszList::<u64, 4>::new(vec![1]).unwrap();
        list.extend_copy(2, 9).unwrap();
        assert_eq!(list.as_slice(), &[1, 9, 9]);

        assert_eq!(
            list.extend_copy(2, 7).unwrap_err(),
            "SszList length 5 exceeds limit 4"
        );
    }
}