Skip to main content

simple_someip/
net_endpoint.rs

1//! Shared network-endpoint identity types.
2//!
3//! [`NetEndpoint`] is the crate's transport-layer identity: the full spec
4//! socket plus the transport protocol. AUTOSAR `PRS_SOMEIP` §4.2.1.3
5//! identifies a service instance "through the combination of the Service
6//! ID combined with the socket (i.e. IP-address, transport protocol, and
7//! port number)" — this type is the socket half of that pair. It carries
8//! no application-layer discriminator (service id, instance id,
9//! eventgroup), so sibling protocol crates can share the same shape.
10
11use core::net::SocketAddr;
12
13/// Transport protocol of a network endpoint.
14///
15/// `Udp`/`Tcp` correspond to the IANA protocol numbers SOME/IP-SD
16/// endpoint options carry on the wire (0x11 / 0x06) — the only two
17/// transport protocols the SOME/IP specification defines for endpoint
18/// options.
19#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
20#[non_exhaustive]
21pub enum TransportProtocol {
22    /// UDP (IANA 0x11).
23    Udp,
24    /// TCP (IANA 0x06).
25    Tcp,
26}
27
28/// A full transport endpoint: socket address plus transport protocol.
29#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
30pub struct NetEndpoint {
31    /// IP address and port.
32    pub addr: SocketAddr,
33    /// Transport protocol on that socket.
34    pub protocol: TransportProtocol,
35}
36
37impl NetEndpoint {
38    #[must_use]
39    pub const fn new(addr: SocketAddr, protocol: TransportProtocol) -> Self {
40        Self { addr, protocol }
41    }
42
43    #[must_use]
44    pub const fn udp(addr: SocketAddr) -> Self {
45        Self::new(addr, TransportProtocol::Udp)
46    }
47
48    #[must_use]
49    pub const fn tcp(addr: SocketAddr) -> Self {
50        Self::new(addr, TransportProtocol::Tcp)
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57    use core::net::{Ipv4Addr, SocketAddrV4};
58
59    #[test]
60    fn constructors_set_protocol() {
61        let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 30490));
62        assert_eq!(NetEndpoint::udp(addr).protocol, TransportProtocol::Udp);
63        assert_eq!(NetEndpoint::tcp(addr).protocol, TransportProtocol::Tcp);
64        assert_eq!(NetEndpoint::udp(addr).addr, addr);
65    }
66
67    #[test]
68    fn endpoints_differing_only_in_protocol_are_distinct() {
69        let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 30490));
70        assert_ne!(NetEndpoint::udp(addr), NetEndpoint::tcp(addr));
71    }
72}