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
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Link device (L2) definitions.
//!
//! This module contains definitions of link-layer devices, otherwise known as
//! L2 devices.

use core::fmt::Debug;

use net_types::ethernet::Mac;
use net_types::UnicastAddress;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};

use crate::Device;

/// The type of address used by a link device.
pub trait LinkAddress:
    'static
    + FromBytes
    + IntoBytes
    + KnownLayout
    + Immutable
    + Unaligned
    + Copy
    + Clone
    + Debug
    + Eq
    + Send
{
    /// The length of the address in bytes.
    const BYTES_LENGTH: usize;

    /// Returns the underlying bytes of a `LinkAddress`.
    fn bytes(&self) -> &[u8];

    /// Constructs a `LinkLayerAddress` from the provided bytes.
    ///
    /// # Panics
    ///
    /// `from_bytes` may panic if `bytes` is not **exactly** [`BYTES_LENGTH`]
    /// long.
    fn from_bytes(bytes: &[u8]) -> Self;
}

impl LinkAddress for Mac {
    const BYTES_LENGTH: usize = 6;

    fn bytes(&self) -> &[u8] {
        self.as_ref()
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        // Assert that contract is being held.
        debug_assert_eq!(bytes.len(), Self::BYTES_LENGTH);
        let mut b = [0; Self::BYTES_LENGTH];
        b.copy_from_slice(bytes);
        Self::new(b)
    }
}

/// A link address that can be unicast.
pub trait LinkUnicastAddress: LinkAddress + UnicastAddress {}
impl<L: LinkAddress + UnicastAddress> LinkUnicastAddress for L {}

/// A link device.
///
/// `LinkDevice` is used to identify a particular link device implementation. It
/// is only intended to exist at the type level, never instantiated at runtime.
pub trait LinkDevice: Device + Debug {
    /// The type of address used to address link devices of this type.
    type Address: LinkUnicastAddress;
}

/// Utilities for testing link devices.
#[cfg(any(test, feature = "testutils"))]
pub(crate) mod testutil {
    use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};

    use super::*;
    use crate::testutil::{FakeCoreCtx, FakeStrongDeviceId, FakeWeakDeviceId};
    use crate::{DeviceIdContext, DeviceIdentifier, StrongDeviceIdentifier};

    /// A fake [`LinkDevice`].
    #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
    pub enum FakeLinkDevice {}

    const FAKE_LINK_ADDRESS_LEN: usize = 1;

    /// A fake [`LinkAddress`].
    ///
    /// The value 0xFF is the broadcast address.
    #[derive(
        KnownLayout,
        FromBytes,
        IntoBytes,
        Immutable,
        Unaligned,
        Copy,
        Clone,
        Debug,
        Hash,
        PartialEq,
        Eq,
    )]
    #[repr(transparent)]
    pub struct FakeLinkAddress(pub [u8; FAKE_LINK_ADDRESS_LEN]);

    impl UnicastAddress for FakeLinkAddress {
        fn is_unicast(&self) -> bool {
            let Self(bytes) = self;
            bytes != &[0xff]
        }
    }

    impl LinkAddress for FakeLinkAddress {
        const BYTES_LENGTH: usize = FAKE_LINK_ADDRESS_LEN;

        fn bytes(&self) -> &[u8] {
            &self.0[..]
        }

        fn from_bytes(bytes: &[u8]) -> FakeLinkAddress {
            FakeLinkAddress(bytes.try_into().unwrap())
        }
    }

    impl Device for FakeLinkDevice {}

    impl LinkDevice for FakeLinkDevice {
        type Address = FakeLinkAddress;
    }

    /// A fake ID identifying a [`FakeLinkDevice`].
    #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
    pub struct FakeLinkDeviceId;

    impl StrongDeviceIdentifier for FakeLinkDeviceId {
        type Weak = FakeWeakDeviceId<Self>;

        fn downgrade(&self) -> Self::Weak {
            FakeWeakDeviceId(*self)
        }
    }

    impl DeviceIdentifier for FakeLinkDeviceId {
        fn is_loopback(&self) -> bool {
            false
        }
    }

    impl<S, M> DeviceIdContext<FakeLinkDevice> for FakeCoreCtx<S, M, FakeLinkDeviceId> {
        type DeviceId = FakeLinkDeviceId;
        type WeakDeviceId = FakeWeakDeviceId<FakeLinkDeviceId>;
    }

    impl FakeStrongDeviceId for FakeLinkDeviceId {
        fn is_alive(&self) -> bool {
            true
        }
    }

    impl PartialEq<FakeWeakDeviceId<FakeLinkDeviceId>> for FakeLinkDeviceId {
        fn eq(&self, FakeWeakDeviceId(other): &FakeWeakDeviceId<FakeLinkDeviceId>) -> bool {
            self == other
        }
    }
}