sciparse 0.6.1

Zero-copy SCION packet parsing, serialization and control plane components
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
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
// Copyright 2026 Anapaya Systems
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! SCION standard path views
//!
//! See [`View`](crate::core::view) for more information about views in general.

use std::{
    fmt::{Debug, Display},
    mem::transmute,
    ops::Range,
};

use crate::{
    core::{
        read::unchecked_bit_range_be_read,
        view::{
            View, ViewConversionError,
            macros::{gen_field_read, gen_field_write, gen_unsafe_field_write, gen_view_impl},
        },
        write::unchecked_bit_range_be_write,
    },
    dataplane_path::{
        standard::{
            layout::{
                HopFieldLayout, InfoFieldLayout, StdPathDataLayout, StdPathLayout,
                StdPathMetaLayout,
            },
            mac::{HopMacInput, HopMacInputSource},
            types::{HopFieldFlags, HopFieldMac, InfoFieldFlags, exp_time_to_duration},
        },
        types::PathReverseError,
    },
};

/// A view over a standard SCION path, including meta header and data
#[repr(transparent)]
#[derive(PartialEq, Eq)]
pub struct StandardPathView([u8]);
gen_view_impl!(StandardPathView, StdPathLayout);

// Meta header
impl StandardPathView {
    gen_field_read!(
        curr_info_field_idx,
        StdPathMetaLayout::CURR_INFO_FIELD_RNG,
        u8
    );
    gen_field_read!(
        curr_hop_field_idx,
        StdPathMetaLayout::CURR_HOP_FIELD_RNG,
        u8
    );
    gen_field_read!(seg0_len, StdPathMetaLayout::SEG0_LEN_RNG, u8);
    gen_field_read!(seg1_len, StdPathMetaLayout::SEG1_LEN_RNG, u8);
    gen_field_read!(seg2_len, StdPathMetaLayout::SEG2_LEN_RNG, u8);

    /// Returns the number of info fields present in the path
    #[inline]
    pub fn info_field_count(&self) -> u8 {
        (self.seg0_len() > 0) as u8 + (self.seg1_len() > 0) as u8 + (self.seg2_len() > 0) as u8
    }

    /// Returns the number of hop fields present in the path
    #[inline]
    pub fn hop_field_count(&self) -> u8 {
        self.seg0_len() + self.seg1_len() + self.seg2_len()
    }
}

// Meta header mut
impl StandardPathView {
    gen_field_write!(
        set_curr_info_field,
        StdPathMetaLayout::CURR_INFO_FIELD_RNG,
        u8
    );
    gen_field_write!(
        set_curr_hop_field,
        StdPathMetaLayout::CURR_HOP_FIELD_RNG,
        u8
    );
    gen_unsafe_field_write!(set_seg0_len, StdPathMetaLayout::SEG0_LEN_RNG, u8);
    gen_unsafe_field_write!(set_seg1_len, StdPathMetaLayout::SEG1_LEN_RNG, u8);
    gen_unsafe_field_write!(set_seg2_len, StdPathMetaLayout::SEG2_LEN_RNG, u8);
}
// Data Helpers
impl StandardPathView {
    /// Returns the byte range for the info field at the given index, or None if the index is out of
    /// bounds
    #[inline]
    fn checked_info_field_range(&self, index: usize) -> Option<Range<usize>> {
        let info_field_count = self.info_field_count() as usize;
        if index >= info_field_count {
            return None;
        }

        Some(
            StdPathDataLayout::new(self.seg0_len(), self.seg1_len(), self.seg2_len())
                .info_field_range(index)
                .shift(StdPathMetaLayout::SIZE_BYTES)
                .aligned_byte_range(),
        )
    }

    /// Returns the byte range for the hop field at the given index, or None if the index is out of
    /// bounds
    #[inline]
    pub fn checked_hop_field_range(&self, index: usize) -> Option<Range<usize>> {
        let hop_field_count = self.hop_field_count() as usize;
        if index >= hop_field_count {
            return None;
        }

        Some(
            StdPathDataLayout::new(self.seg0_len(), self.seg1_len(), self.seg2_len())
                .hop_field_range(index)
                .shift(StdPathMetaLayout::SIZE_BYTES)
                .aligned_byte_range(),
        )
    }
}
// Data
impl StandardPathView {
    /// Returns a view over the current info field, or None if the current info field index is out
    /// of bounds
    #[inline]
    pub fn curr_info_field(&self) -> Option<&InfoFieldView> {
        let index = self.curr_info_field_idx() as usize;
        self.info_field(index)
    }

    /// Returns a view over the info field at the given index, or None if the index is out of bounds
    #[inline]
    pub fn info_field(&self, index: usize) -> Option<&InfoFieldView> {
        let field_range = self.checked_info_field_range(index)?;

        // SAFETY:
        // - index is checked to be less than field count
        // - AddressHeaderView can only be created if buf is at least as large as indicated by field
        //   count
        let field =
            unsafe { InfoFieldView::from_slice_unchecked(self.0.get_unchecked(field_range)) };

        Some(field)
    }

    /// Returns a view over the current hop field, or None if the current hop field index is out of
    /// bounds
    #[inline]
    pub fn curr_hop_field(&self) -> Option<&HopFieldView> {
        let index = self.curr_hop_field_idx() as usize;
        self.hop_field(index)
    }

    /// Returns a view over the hop field at the given index, or None if the index is out of bounds
    #[inline]
    pub fn hop_field(&self, index: usize) -> Option<&HopFieldView> {
        let field_range = self.checked_hop_field_range(index)?;

        // SAFETY:
        // - index is checked to be less than field count
        // - AddressHeaderView can only be created if buf is at least as large as indicated by field
        //   count
        let field =
            unsafe { HopFieldView::from_slice_unchecked(self.0.get_unchecked(field_range)) };

        Some(field)
    }

    /// Returns a view over all info fields
    #[inline]
    pub fn info_fields(&self) -> &[InfoFieldView] {
        let layout = StdPathDataLayout::new(self.seg0_len(), self.seg1_len(), self.seg2_len());

        let info_fields_range = layout
            .info_fields_range()
            .shift(StdPathMetaLayout::SIZE_BYTES)
            .aligned_byte_range();

        // SAFETY: buffer size is checked on construction
        let slice = unsafe { self.0.get_unchecked(info_fields_range) };

        debug_assert!(slice.len() == layout.info_field_count() * InfoFieldLayout::SIZE_BYTES);

        // SAFETY: InfoFieldView is #[repr(transparent)] over [u8; SIZE_BYTES], as such the cast is
        // safe
        unsafe {
            std::slice::from_raw_parts(
                slice.as_ptr() as *const InfoFieldView,
                layout.info_field_count(),
            )
        }
    }

    /// Returns a view over all hop fields
    #[inline]
    pub fn hop_fields(&self) -> &[HopFieldView] {
        let layout = StdPathDataLayout::new(self.seg0_len(), self.seg1_len(), self.seg2_len());

        let hop_fields_range = layout
            .hop_fields_range()
            .shift(StdPathMetaLayout::SIZE_BYTES)
            .aligned_byte_range();

        // SAFETY: buffer size is checked on construction
        let slice = unsafe { self.0.get_unchecked(hop_fields_range) };

        // SAFETY: View is #[repr(transparent)] over [u8; SIZE_BYTES], as such raw byte slices can
        // be safely interpreted
        debug_assert!(slice.len() == layout.hop_field_count() * HopFieldLayout::SIZE_BYTES);
        unsafe {
            std::slice::from_raw_parts(
                slice.as_ptr() as *const HopFieldView,
                layout.hop_field_count(),
            )
        }
    }
}
// Data mut
impl StandardPathView {
    /// Returns a view over the current info field, or None if the current info field index is out
    /// of bounds
    #[inline]
    pub fn curr_info_field_mut(&mut self) -> Option<&mut InfoFieldView> {
        let index = self.curr_info_field_idx() as usize;
        self.info_field_mut(index)
    }

    /// Returns a view over the info field at the given index, or None if the index is out of bounds
    #[inline]
    pub fn info_field_mut(&mut self, index: usize) -> Option<&mut InfoFieldView> {
        let field_range = self.checked_info_field_range(index)?;

        // SAFETY:
        // - index is checked to be less than field count
        // - AddressHeaderView can only be created if buf is at least as large as indicated by field
        //   count
        let field = unsafe {
            InfoFieldView::from_mut_slice_unchecked(self.0.get_unchecked_mut(field_range))
        };

        Some(field)
    }

    /// Returns a view over the current hop field, or None if the current hop field index is out of
    /// bounds
    #[inline]
    pub fn curr_hop_field_mut(&mut self) -> Option<&mut HopFieldView> {
        let index = self.curr_hop_field_idx() as usize;
        self.hop_field_mut(index)
    }

    /// Returns a view over the hop field at the given index, or None if the index is out of bounds
    #[inline]
    pub fn hop_field_mut(&mut self, index: usize) -> Option<&mut HopFieldView> {
        let field_range = self.checked_hop_field_range(index)?;

        // SAFETY:
        // - index is checked to be less than field count
        // - AddressHeaderView can only be created if buf is at least as large as indicated by field
        //   count
        let field = unsafe {
            HopFieldView::from_mut_slice_unchecked(self.0.get_unchecked_mut(field_range))
        };

        Some(field)
    }

    /// Returns a view over all info fields
    #[inline]
    pub fn info_fields_mut(&mut self) -> &mut [InfoFieldView] {
        let layout = StdPathDataLayout::new(self.seg0_len(), self.seg1_len(), self.seg2_len());

        let info_fields_range = layout
            .info_fields_range()
            .shift(StdPathMetaLayout::SIZE_BYTES)
            .aligned_byte_range();

        // SAFETY: buffer size is checked on construction
        let slice = unsafe { self.0.get_unchecked_mut(info_fields_range) };

        debug_assert!(slice.len() == layout.info_field_count() * InfoFieldLayout::SIZE_BYTES);

        // SAFETY: InfoFieldView is #[repr(transparent)] over [u8; SIZE_BYTES], as such the cast is
        // safe
        unsafe {
            std::slice::from_raw_parts_mut(
                slice.as_mut_ptr() as *mut InfoFieldView,
                layout.info_field_count(),
            )
        }
    }

    /// Returns a view over all hop fields
    #[inline]
    pub fn hop_fields_mut(&mut self) -> &mut [HopFieldView] {
        let layout = StdPathDataLayout::new(self.seg0_len(), self.seg1_len(), self.seg2_len());

        let hop_fields_range = layout
            .hop_fields_range()
            .shift(StdPathMetaLayout::SIZE_BYTES)
            .aligned_byte_range();

        // SAFETY: buffer size is checked on construction
        let slice = unsafe { self.0.get_unchecked_mut(hop_fields_range) };
        // SAFETY: View is #[repr(transparent)] over [u8; SIZE_BYTES], as such raw byte slices can
        // be safely interpreted

        debug_assert!(slice.len() == layout.hop_field_count() * HopFieldLayout::SIZE_BYTES);
        unsafe {
            std::slice::from_raw_parts_mut(
                slice.as_mut_ptr() as *mut HopFieldView,
                layout.hop_field_count(),
            )
        }
    }

    /// Attempts to return the egress interface of the next hop field.
    ///
    /// Returns `None` if the current hop or info field index is out of bounds.
    #[inline]
    pub fn curr_egress_interface(&self) -> Option<u16> {
        let curr_hop = self.curr_hop_field()?;
        let curr_info = self.curr_info_field()?;

        Some(curr_hop.egress_interface(curr_info))
    }

    /// Reverses the path in-place
    ///
    /// This function preserves the current logical position in the path.
    #[inline]
    pub fn try_reverse(&mut self) -> Result<(), PathReverseError> {
        let seg0 = self.seg0_len();
        let seg1 = self.seg1_len();
        let seg2 = self.seg2_len();

        let seg_count;

        // Update current info and hop field indices
        let curr_hop_idx = self.curr_hop_field_idx() as usize;
        let curr_info_idx = self.curr_info_field_idx() as usize;

        // Reverse order of segment lengths
        {
            match (seg0, seg1, seg2) {
                (0, ..) => {
                    // Invalid path, no segments present, nothing to do
                    return Err(PathReverseError::new(
                        "Cannot reverse a path with no segments",
                    ));
                }
                (_, 0, _) => {
                    seg_count = 1;
                    // Only seg0 is present, nothing to do
                }
                (_, _, 0) => {
                    seg_count = 2;
                    // Swap seg0 and seg1
                    // SAFETY: Total number of hop fields is unchanged
                    unsafe {
                        self.set_seg0_len(seg1);
                        self.set_seg1_len(seg0);
                    }
                }
                (..) => {
                    seg_count = 3;
                    // All segments are present, swap seg0 with seg2, and keep seg1 in the middle
                    // SAFETY: Total number of hop fields is unchanged
                    unsafe {
                        self.set_seg0_len(seg2);
                        self.set_seg1_len(seg1);
                        self.set_seg2_len(seg0);
                    }
                }
            }
        }

        // Check if path is valid
        let total_hops = seg0 as usize + seg1 as usize + seg2 as usize;
        if curr_hop_idx >= total_hops {
            return Err(PathReverseError::new(
                "Current hop field index is out of bounds",
            ));
        }
        if curr_info_idx >= seg_count {
            return Err(PathReverseError::new(
                "Current info field index is out of bounds",
            ));
        }

        debug_assert!(
            total_hops > 0,
            "0 hops should have been caught by the check at the beginning of the function"
        );
        debug_assert!(
            seg_count > 0,
            "0 segments should have been caught by the check at the beginning of the function"
        );

        // Swap Construction dir and reverse order of info fields
        {
            let info_fields = self.info_fields_mut();

            for info_field in info_fields.iter_mut() {
                let mut flags = info_field.flags();
                flags.toggle(InfoFieldFlags::CONS_DIR);
                info_field.set_flags(flags);
            }

            info_fields.reverse();
        }

        // Reverse order of hop fields
        self.hop_fields_mut().reverse();

        let new_hop_idx = (total_hops - curr_hop_idx) - 1;
        let new_info_idx = (seg_count - curr_info_idx) - 1;
        self.set_curr_hop_field(new_hop_idx as u8);
        self.set_curr_info_field(new_info_idx as u8);

        Ok(())
    }
}
// Utility
impl StandardPathView {
    /// Returns an iterator over the segments of the path, where each segment is represented as a
    /// tuple of an info field and a slice of hop fields.
    ///
    /// The iterator guarantees that each info field has at least one hop field, and that the number
    /// of info fields and hop fields matches the segment lengths in the meta header.
    #[inline]
    pub fn segments(&self) -> SegmentIterator<'_> {
        SegmentIterator::new(self)
    }

    /// Calculates the expiry time of the path by scanning info and hop fields
    ///
    /// Returns the absolute expiry time as a UNIX timestamp in seconds, or 0 if the path has no hop
    /// fields.
    #[inline]
    pub fn expiration(&self) -> u32 {
        let segment_iter = self.segments();
        if segment_iter.is_empty() {
            return 0;
        }

        let mut expiry_time = u32::MAX;

        for (info_field, hop_fields) in self.segments() {
            // get the lowest exp_time of the hop fields in the segment
            let exp_time = hop_fields
                .iter()
                .map(|hop_field| hop_field.exp_time())
                .min()
                .expect("segment iterator ensures at least one hop field per segment");

            let info_expiry = info_field.timestamp();

            // calculate the absolute expiry time of the segment
            let exp_time: u32 = exp_time_to_duration(exp_time)
                .as_secs()
                .try_into()
                .expect("maximum expiry time fits in u32");

            let segment_expiry = info_expiry.saturating_add(exp_time);

            // Update the path expiry time to be the minimum of the current expiry time and the
            // segment expiry
            expiry_time = expiry_time.min(segment_expiry);
        }

        expiry_time
    }

    /// Calculates the segment of the given hop field index in the path.
    ///
    /// Returns (segment_idx, is_segment_start, is_segment_end) if the hop field index is valid,
    /// or None if the hop field index is out of bounds.
    #[inline]
    pub fn calculate_segment_index(&self, hop_idx: usize) -> Option<(usize, bool, bool)> {
        let segment_lengths = [self.seg0_len(), self.seg1_len(), self.seg2_len()];
        Self::_calculate_segment_index(hop_idx, segment_lengths)
    }

    #[inline]
    fn _calculate_segment_index(
        hop_idx: usize,
        segment_lengths: [u8; 3],
    ) -> Option<(usize, bool, bool)> {
        let mut seg_len_agg = 0;

        for (seg_idx, seg_len) in segment_lengths.into_iter().enumerate() {
            // Check if hop is part of this segment
            if hop_idx < seg_len_agg + seg_len as usize {
                let is_segment_start = hop_idx == seg_len_agg;
                let is_segment_end = (hop_idx + 1) == (seg_len_agg + seg_len as usize);

                return Some((seg_idx, is_segment_start, is_segment_end));
            }

            seg_len_agg += seg_len as usize;
        }

        // hop_idx is out of bounds
        None
    }
}

impl Debug for StandardPathView {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let hop_fields = self.hop_fields();
        let info_fields = self.info_fields();
        f.debug_struct("StandardPathMetaHeaderView")
            .field("current_info_field", &self.curr_info_field_idx())
            .field("curr_hop_field", &self.curr_hop_field_idx())
            .field("seg0_len", &self.seg0_len())
            .field("seg1_len", &self.seg1_len())
            .field("seg2_len", &self.seg2_len())
            .field("info_fields", &info_fields)
            .field("hop_fields", &hop_fields)
            .finish()
    }
}

impl Display for StandardPathView {
    /// Formats the path in a human-readable format, including the current info and hop field
    /// indices, segment lengths, and the contents of each segment.
    ///
    /// Example:
    /// `[std] ci:0 ch:0 seg: c[0,1; 1,2; 3,0], r[0,1; 1,0]`
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "[std] ci:{} ch:{} segs:",
            self.curr_info_field_idx(),
            self.curr_hop_field_idx(),
        )?;

        for (info, hops) in self.segments() {
            let const_dir = match info.flags().contains(InfoFieldFlags::CONS_DIR) {
                true => "",
                false => "r",
            };

            write!(f, " {}[", const_dir)?;

            let Some((last, head)) = hops.split_last() else {
                write!(f, "]")?;
                continue;
            };

            for hop in head {
                let ingress = hop.ingress_interface(info);
                let egress = hop.egress_interface(info);
                write!(f, "{},{}; ", ingress, egress)?;
            }

            let last_ingress = last.ingress_interface(info);
            let last_egress = last.egress_interface(info);
            write!(f, "{},{}", last_ingress, last_egress)?;

            write!(f, "]")?;
        }

        Ok(())
    }
}

/// Iterator over the segments of a standard path, where each segment is represented as a tuple of
/// an info field and a slice of hop fields.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SegmentIterator<'a> {
    segment_lengths: [u8; 3],
    hop_fields: &'a [HopFieldView],
    info_fields: &'a [InfoFieldView],
    seg_idx: usize,
    total_segments: usize,
    hop_idx: usize,
}
impl SegmentIterator<'_> {
    #[inline]
    fn new(path_view: &StandardPathView) -> SegmentIterator<'_> {
        let segment_lengths = [
            path_view.seg0_len(),
            path_view.seg1_len(),
            path_view.seg2_len(),
        ];

        let mut total_segments = 0;
        for &len in &segment_lengths {
            if len == 0 {
                break;
            }
            total_segments += 1;
        }

        SegmentIterator {
            total_segments: total_segments as usize,
            hop_fields: path_view.hop_fields(),
            info_fields: path_view.info_fields(),
            segment_lengths,
            seg_idx: 0,
            hop_idx: 0,
        }
    }

    /// Returns true if the path has no segments, i.e. no info fields and no hop fields.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.total_segments == 0
    }

    /// Returns the total number of segments in the path.
    #[inline]
    pub const fn segment_count(&self) -> usize {
        self.total_segments
    }

    /// Returns the total number of hop fields in the path.
    #[inline]
    pub const fn hop_field_count(&self) -> usize {
        self.hop_fields.len()
    }
}
impl<'a> Iterator for SegmentIterator<'a> {
    type Item = (&'a InfoFieldView, &'a [HopFieldView]);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.seg_idx >= self.total_segments {
            return None;
        }

        let info_field = self.info_fields.get(self.seg_idx)?;
        let hop_fields = &self.hop_fields
            [self.hop_idx..(self.hop_idx + self.segment_lengths[self.seg_idx] as usize)];

        self.seg_idx += 1;
        self.hop_idx += hop_fields.len();

        Some((info_field, hop_fields))
    }
}

/// A view over a standard SCION path info field
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct InfoFieldView([u8; InfoFieldLayout::SIZE_BYTES]);
impl View for InfoFieldView {
    #[inline]
    fn has_required_size(buf: &[u8]) -> Result<usize, ViewConversionError> {
        if buf.len() < InfoFieldLayout::SIZE_BYTES {
            return Err(ViewConversionError::BufferTooSmall {
                at: "InfoFieldView",
                required: InfoFieldLayout::SIZE_BYTES,
                actual: buf.len(),
            });
        }

        Ok(InfoFieldLayout::SIZE_BYTES)
    }

    #[inline]
    unsafe fn from_slice_unchecked(buf: &[u8]) -> &Self {
        // SAFETY: see View trait documentation
        let sized: &[u8; InfoFieldLayout::SIZE_BYTES] =
            unsafe { buf.try_into().unwrap_unchecked() };
        unsafe { transmute(sized) }
    }

    #[inline]
    unsafe fn from_mut_slice_unchecked(buf: &mut [u8]) -> &mut Self {
        // SAFETY: see View trait documentation
        let sized: &mut [u8; InfoFieldLayout::SIZE_BYTES] =
            unsafe { buf.try_into().unwrap_unchecked() };
        unsafe { transmute(sized) }
    }

    #[inline]
    unsafe fn from_boxed_unchecked(buf: Box<[u8]>) -> Box<Self> {
        // SAFETY: see View trait documentation
        let sized: Box<[u8; InfoFieldLayout::SIZE_BYTES]> =
            unsafe { buf.try_into().unwrap_unchecked() };
        unsafe { transmute(sized) }
    }

    #[inline]
    unsafe fn as_slice_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }

    #[inline]
    fn as_slice_boxed(self: Box<Self>) -> Box<[u8]> {
        // SAFETY: repr(transparent) over [u8; N]
        let sized: Box<[u8; InfoFieldLayout::SIZE_BYTES]> = unsafe { transmute(self) };
        sized
    }

    #[inline]
    fn as_slice(&self) -> &[u8] {
        &self.0
    }
}
// Immutable
impl InfoFieldView {
    /// Returns the flags of the info field
    #[inline]
    pub fn flags(&self) -> InfoFieldFlags {
        // SAFETY: buffer size is checked on construction
        let val = unsafe { unchecked_bit_range_be_read::<u8>(&self.0, InfoFieldLayout::FLAGS_RNG) };
        InfoFieldFlags::from_bits_retain(val)
    }

    gen_field_read!(segment_id, InfoFieldLayout::SEGMENT_ID_RNG, u16);

    /// Returns the timestamp of the info field, which is used for path expiry calculations
    ///
    /// The timestamp is the number of seconds since the UNIX epoch, and is used in combination with
    /// the `exp_time` field of the hop fields to calculate the absolute expiry time of the path.
    #[inline]
    pub fn timestamp(&self) -> u32 {
        use crate::core::read::unchecked_bit_range_be_read;
        unsafe { unchecked_bit_range_be_read::<u32>(&self.0, InfoFieldLayout::TIMESTAMP_RNG) }
    }
}
// Mutable
impl InfoFieldView {
    /// Sets the flags of the info field
    #[inline]
    pub fn set_flags(&mut self, flags: InfoFieldFlags) {
        // SAFETY: buffer size is checked on construction
        let val = flags.bits();
        unsafe { unchecked_bit_range_be_write::<u8>(&mut self.0, InfoFieldLayout::FLAGS_RNG, val) }
    }

    gen_field_write!(set_segment_id, InfoFieldLayout::SEGMENT_ID_RNG, u16);
    gen_field_write!(set_timestamp, InfoFieldLayout::TIMESTAMP_RNG, u32);
}
impl Debug for InfoFieldView {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StandardPathInfoFieldView")
            .field("flags", &self.flags())
            .field("segment_id", &self.segment_id())
            .field("timestamp", &self.timestamp())
            .finish()
    }
}

/// A view over a standard SCION path hop field
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct HopFieldView([u8; HopFieldLayout::SIZE_BYTES]);
impl View for HopFieldView {
    #[inline]
    fn has_required_size(buf: &[u8]) -> Result<usize, ViewConversionError> {
        if buf.len() < HopFieldLayout::SIZE_BYTES {
            return Err(ViewConversionError::BufferTooSmall {
                at: "HopFieldView",
                required: HopFieldLayout::SIZE_BYTES,
                actual: buf.len(),
            });
        }

        Ok(HopFieldLayout::SIZE_BYTES)
    }

    #[inline]
    unsafe fn from_slice_unchecked(buf: &[u8]) -> &Self {
        // SAFETY: see View trait documentation
        let sized: &[u8; HopFieldLayout::SIZE_BYTES] = unsafe { buf.try_into().unwrap_unchecked() };
        unsafe { transmute(sized) }
    }

    #[inline]
    unsafe fn from_mut_slice_unchecked(buf: &mut [u8]) -> &mut Self {
        // SAFETY: see View trait documentation
        let sized: &mut [u8; HopFieldLayout::SIZE_BYTES] =
            unsafe { buf.try_into().unwrap_unchecked() };
        unsafe { transmute(sized) }
    }

    #[inline]
    unsafe fn from_boxed_unchecked(buf: Box<[u8]>) -> Box<Self> {
        // SAFETY: see View trait documentation
        let sized: Box<[u8; HopFieldLayout::SIZE_BYTES]> =
            unsafe { buf.try_into().unwrap_unchecked() };
        unsafe { transmute(sized) }
    }

    #[inline]
    unsafe fn as_slice_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }

    #[inline]
    fn as_slice_boxed(self: Box<Self>) -> Box<[u8]> {
        // SAFETY: repr(transparent) over [u8; N]
        let sized: Box<[u8; HopFieldLayout::SIZE_BYTES]> = unsafe { transmute(self) };
        sized
    }

    #[inline]
    fn as_slice(&self) -> &[u8] {
        &self.0
    }
}
// Immutable
impl HopFieldView {
    /// Returns the flags of the hop field
    #[inline]
    pub fn flags(&self) -> HopFieldFlags {
        // SAFETY: buffer size is checked on construction
        let value =
            unsafe { unchecked_bit_range_be_read::<u8>(&self.0, HopFieldLayout::FLAGS_RNG) };
        HopFieldFlags::from_bits_retain(value)
    }

    gen_field_read!(exp_time, HopFieldLayout::EXP_TIME_RNG, u8);
    gen_field_read!(cons_ingress, HopFieldLayout::CONS_INGRESS_RNG, u16);
    gen_field_read!(cons_egress, HopFieldLayout::CONS_EGRESS_RNG, u16);

    /// Returns the MAC of the hop field
    #[inline]
    pub fn mac(&self) -> HopFieldMac {
        // SAFETY: buffer size is checked on construction
        let mac: [u8; 6] = unsafe {
            self.0
                .get_unchecked(HopFieldLayout::MAC_RNG.aligned_byte_range())
                .try_into()
                .unwrap_unchecked()
        };

        HopFieldMac(mac)
    }

    /// Returns the ingress interface in the direction the packet is travelling.
    ///
    /// Reads `cons_ingress` when the `CONS_DIR` flag is set on `info_field`, and
    /// `cons_egress` otherwise (reversed segment).
    #[inline]
    pub fn ingress_interface(&self, info_field: &InfoFieldView) -> u16 {
        if info_field.flags().cons_dir() {
            self.cons_ingress()
        } else {
            self.cons_egress()
        }
    }

    /// Returns the egress interface in the direction the packet is travelling.
    ///
    /// Reads `cons_egress` when the `CONS_DIR` flag is set on `info_field`, and
    /// `cons_ingress` otherwise (reversed segment).
    #[inline]
    pub fn egress_interface(&self, info_field: &InfoFieldView) -> u16 {
        if info_field.flags().cons_dir() {
            self.cons_egress()
        } else {
            self.cons_ingress()
        }
    }

    /// Returns true if the hop field has a ingress scmp alert flag set in the direction the packet
    /// is travelling.
    #[inline]
    pub fn ingress_scmp_alert(&self, info_field: &InfoFieldView) -> bool {
        let cons_dir = info_field.flags().cons_dir();
        self.flags().normalized_ingress_router_alert(cons_dir)
    }

    /// Returns true if the hop field has a egress scmp alert flag set in the direction the packet
    /// is travelling.
    #[inline]
    pub fn egress_scmp_alert(&self, info_field: &InfoFieldView) -> bool {
        let cons_dir = info_field.flags().cons_dir();
        self.flags().normalized_egress_router_alert(cons_dir)
    }
}
// Mutable
impl HopFieldView {
    /// Sets the flags of the hop field
    #[inline]
    pub fn set_flags(&mut self, flags: HopFieldFlags) {
        // SAFETY: buffer size is checked on construction
        let value = flags.bits();
        unsafe { unchecked_bit_range_be_write::<u8>(&mut self.0, HopFieldLayout::FLAGS_RNG, value) }
    }

    gen_field_write!(set_exp_time, HopFieldLayout::EXP_TIME_RNG, u8);
    gen_field_write!(set_cons_ingress, HopFieldLayout::CONS_INGRESS_RNG, u16);
    gen_field_write!(set_cons_egress, HopFieldLayout::CONS_EGRESS_RNG, u16);

    /// Sets the MAC of the hop field
    #[inline]
    pub fn set_mac(&mut self, mac: HopFieldMac) {
        // SAFETY: buffer size is checked on construction
        unsafe {
            self.0
                .get_unchecked_mut(HopFieldLayout::MAC_RNG.aligned_byte_range())
                .copy_from_slice(&mac.0);
        }
    }
}
// Util
impl HopFieldView {
    /// Calculates the absolute expiry timestamp of the hop field based on the timestamp of the info
    /// field and the exp_time of the hop field.
    ///
    /// The timestamp is a unix epoch timestamp in seconds.
    #[inline]
    pub fn expiry_timestamp(&self, info: &InfoFieldView) -> u32 {
        let info_expiry = info.timestamp();
        let exp_time = exp_time_to_duration(self.exp_time()).as_secs();
        info_expiry.saturating_add(exp_time.try_into().expect("expiry time fits in u32"))
    }
}
impl Debug for HopFieldView {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StandardPathHopFieldView")
            .field("flags", &self.flags())
            .field("exp_time", &self.exp_time())
            .field("cons_ingress", &self.cons_ingress())
            .field("cons_egress", &self.cons_egress())
            .field("mac", &self.mac())
            .finish()
    }
}
/// Provides the necessary input for calculating the MAC of a hop field.
/// Automatically implements [`HopMacCalculate`](crate::path::standard::mac::HopMacCalculate)
impl HopMacInputSource for HopFieldView {
    #[inline]
    fn get_mac_input(&self) -> HopMacInput {
        HopMacInput {
            exp_time: self.exp_time(),
            cons_ingress: self.cons_ingress(),
            cons_egress: self.cons_egress(),
        }
    }
}

#[cfg(test)]
mod test {
    mod standard_path_view {
        use tinyvec::{array_vec, tiny_vec};

        use crate::{
            core::{encode::WireEncode, view::View},
            dataplane_path::standard::{
                model::{HopField, InfoField, Segment, StandardPath},
                types::{HopFieldFlags, HopFieldMac, InfoFieldFlags},
                view::StandardPathView,
            },
        };

        #[test]
        fn should_correclty_determine_segment_position() {
            let tests = [
                (0, [1, 0, 0], Some((0, true, true))),
                (1, [1, 0, 0], None),
                (0, [2, 0, 0], Some((0, true, false))),
                (1, [2, 0, 0], Some((0, false, true))),
                (2, [2, 0, 0], None),
                (0, [3, 0, 0], Some((0, true, false))),
                (1, [3, 0, 0], Some((0, false, false))),
                (2, [3, 0, 0], Some((0, false, true))),
                (3, [3, 0, 0], None),
                (2, [2, 3, 0], Some((1, true, false))),
                (3, [2, 3, 0], Some((1, false, false))),
                (4, [2, 3, 0], Some((1, false, true))),
                (5, [2, 3, 0], None),
                (5, [2, 3, 4], Some((2, true, false))),
                (6, [2, 3, 4], Some((2, false, false))),
                (7, [2, 3, 4], Some((2, false, false))),
                (8, [2, 3, 4], Some((2, false, true))),
                (9, [2, 3, 4], None),
            ];

            for (test_idx, (hop_idx, seg_lens, expected)) in tests.iter().enumerate() {
                let result = StandardPathView::_calculate_segment_index(*hop_idx, *seg_lens);
                assert_eq!(
                    result, *expected,
                    "Failed for test {} hop_idx: {}, seg_lens: {:?}",
                    test_idx, hop_idx, seg_lens
                );
            }
        }

        #[test]
        fn std_path_should_correctly_display() {
            let mac = HopFieldMac::zero();
            let flags = HopFieldFlags::empty();

            let std = StandardPath {
                current_info_field: 1,
                current_hop_field: 2,
                segments: array_vec!([_;3] =>
                    Segment {
                        info_field: InfoField {
                            flags: InfoFieldFlags::empty(),
                            segment_id: 1,
                            timestamp: 2,
                        },
                        hop_fields: tiny_vec![
                            [_; 12] =>
                            HopField { flags, expiration_units: 1, cons_ingress: 1, cons_egress: 0, mac },
                            HopField { flags, expiration_units: 1, cons_ingress: 0, cons_egress: 2, mac }
                        ]
                    },
                     Segment {
                        info_field: InfoField {
                            flags: InfoFieldFlags::CONS_DIR,
                            segment_id: 2,
                            timestamp: 3,
                        },
                        hop_fields: tiny_vec![
                            [_; 12] =>
                            HopField { flags, expiration_units: 1, cons_ingress: 0, cons_egress: 3, mac },
                            HopField { flags, expiration_units: 1, cons_ingress: 5, cons_egress: 8, mac },
                            HopField { flags, expiration_units: 1, cons_ingress: 2, cons_egress: 0, mac }
                        ]
                    }
                ),
            };

            let data = std.try_encode_to_vec().unwrap();
            let (v, _) = StandardPathView::try_from_slice(&data).unwrap();
            let std_path_fmt = format!("{}", v);
            assert_eq!(
                std_path_fmt,
                "[std] ci:1 ch:2 segs: r[0,1; 2,0] [0,3; 5,8; 2,0]"
            );
        }
    }
}