sciparse 0.5.2

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
// 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, 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,
    },
    path::standard::{
        layout::{
            HopFieldLayout, InfoFieldLayout, StdPathDataLayout, StdPathLayout, StdPathMetaLayout,
        },
        mac::{HopMacInput, HopMacInputSource},
        types::{HopFieldFlags, HopFieldMac, InfoFieldFlags},
    },
};

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

// Meta header
impl StandardPathView {
    gen_field_read!(curr_info_field, StdPathMetaLayout::CURR_INFO_FIELD_RNG, u8);
    gen_field_read!(curr_hop_field, 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 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 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 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 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(),
            )
        }
    }
}
impl Debug for StandardPathView {
    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())
            .field("curr_hop_field", &self.curr_hop_field())
            .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()
    }
}

/// A view over a standard SCION path info field
#[repr(transparent)]
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_bytes_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }

    #[inline]
    fn as_bytes_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_bytes(&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);
    gen_field_read!(timestamp, InfoFieldLayout::TIMESTAMP_RNG, u32);
}
// 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 {
    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)]
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_bytes_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }

    #[inline]
    fn as_bytes_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_bytes(&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().contains(InfoFieldFlags::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().contains(InfoFieldFlags::CONS_DIR) {
            self.cons_egress()
        } else {
            self.cons_ingress()
        }
    }
}
// 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);
        }
    }
}
impl Debug for HopFieldView {
    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(),
        }
    }
}