diff --git a/neqo-common/src/datagram.rs b/neqo-common/src/datagram.rs index b2d346d02..802a27078 100644 --- a/neqo-common/src/datagram.rs +++ b/neqo-common/src/datagram.rs @@ -9,23 +9,14 @@ use std::{net::SocketAddr, ops::Deref}; use crate::{hex_with_len, IpTos}; #[derive(Clone, PartialEq, Eq)] -pub struct Datagram { +pub struct Datagram> { src: SocketAddr, dst: SocketAddr, tos: IpTos, - d: Vec, + d: D, } -impl Datagram { - pub fn new>>(src: SocketAddr, dst: SocketAddr, tos: IpTos, d: V) -> Self { - Self { - src, - dst, - tos, - d: d.into(), - } - } - +impl Datagram { #[must_use] pub const fn source(&self) -> SocketAddr { self.src @@ -46,6 +37,27 @@ impl Datagram { } } +impl Datagram> { + pub fn new>>(src: SocketAddr, dst: SocketAddr, tos: IpTos, d: V) -> Self { + Self { + src, + dst, + tos, + d: d.into(), + } + } + + #[must_use] + pub fn borrow(&self) -> Datagram<&[u8]> { + Datagram { + src: self.src, + dst: self.dst, + tos: self.tos, + d: self.d.as_ref(), + } + } +} + impl Deref for Datagram { type Target = Vec; #[must_use] @@ -54,7 +66,7 @@ impl Deref for Datagram { } } -impl std::fmt::Debug for Datagram { +impl> std::fmt::Debug for Datagram { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, @@ -67,6 +79,43 @@ impl std::fmt::Debug for Datagram { } } +impl Deref for Datagram<&[u8]> { + type Target = [u8]; + #[must_use] + fn deref(&self) -> &Self::Target { + self.d + } +} + +impl<'a> Datagram<&'a [u8]> { + #[must_use] + pub const fn from_slice(src: SocketAddr, dst: SocketAddr, tos: IpTos, d: &'a [u8]) -> Self { + Self { src, dst, tos, d } + } + + #[must_use] + pub fn to_owned(&self) -> Datagram { + Datagram { + src: self.src, + dst: self.dst, + tos: self.tos, + d: self.d.to_vec(), + } + } +} + +impl<'a> From<&'a Datagram> for Datagram<&'a [u8]> { + fn from(value: &'a Datagram) -> Self { + value.borrow() + } +} + +impl> AsRef<[u8]> for Datagram { + fn as_ref(&self) -> &[u8] { + self.d.as_ref() + } +} + #[cfg(test)] use test_fixture::datagram; diff --git a/test-fixture/src/lib.rs b/test-fixture/src/lib.rs index d58294668..0b1047159 100644 --- a/test-fixture/src/lib.rs +++ b/test-fixture/src/lib.rs @@ -358,8 +358,8 @@ fn split_packet(buf: &[u8]) -> (&[u8], Option<&[u8]>) { pub fn split_datagram(d: &Datagram) -> (Datagram, Option) { let (a, b) = split_packet(&d[..]); ( - Datagram::new(d.source(), d.destination(), d.tos(), a), - b.map(|b| Datagram::new(d.source(), d.destination(), d.tos(), b)), + Datagram::new(d.source(), d.destination(), d.tos(), a.to_vec()), + b.map(|b| Datagram::new(d.source(), d.destination(), d.tos(), b.to_vec())), ) }