Debian Codegraph @

third_party/rust/neqo-common/src/datagram.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 use std::{
8 fmt::{self, Debug, Formatter},
9 net::SocketAddr,
10 ops::{Deref, DerefMut},
11 };
12
13 use crate::{hex_with_len, IpTos};
14
15 #[derive(Clone, PartialEq, Eq)]
16 pub struct Datagram<D = Vec<u8>> {
17 src: SocketAddr,
18 dst: SocketAddr,
19 tos: IpTos,
20 d: D,
21 }
22
23 impl<D> Datagram<D> {
24 #[must_use]
25 pub const fn source(&self) -> SocketAddr {
26 self.src
27 }
28
29 #[must_use]
30 pub const fn destination(&self) -> SocketAddr {
31 self.dst
32 }
33
34 #[must_use]
35 pub const fn tos(&self) -> IpTos {
36 self.tos
37 }
38
39 pub fn set_tos(&mut self, tos: IpTos) {
40 self.tos = tos;
41 }
42 }
43
44 impl<D: AsRef<[u8]>> Datagram<D> {
45 pub fn len(&self) -> usize {
46 self.d.as_ref().len()
47 }
48
49 pub fn is_empty(&self) -> bool {
50 self.len() == 0
51 }
52 }
53
54 impl<D: AsMut<[u8]> + AsRef<[u8]>> AsMut<[u8]> for Datagram<D> {
55 fn as_mut(&mut self) -> &mut [u8] {
56 self.d.as_mut()
57 }
58 }
59
60 impl Datagram<Vec<u8>> {
61 pub fn new<V: Into<Vec<u8>>>(src: SocketAddr, dst: SocketAddr, tos: IpTos, d: V) -> Self {
62 Self {
63 src,
64 dst,
65 tos,
66 d: d.into(),
67 }
68 }
69 }
70
71 impl<D: AsRef<[u8]> + AsMut<[u8]>> DerefMut for Datagram<D> {
72 fn deref_mut(&mut self) -> &mut Self::Target {
73 AsMut::<[u8]>::as_mut(self)
74 }
75 }
76
77 impl<D: AsRef<[u8]>> Deref for Datagram<D> {
78 type Target = [u8];
79 fn deref(&self) -> &Self::Target {
80 AsRef::<[u8]>::as_ref(self)
81 }
82 }
83
84 impl<D: AsRef<[u8]>> Debug for Datagram<D> {
85 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
86 write!(
87 f,
88 "Datagram {:?} {:?}->{:?}: {}",
89 self.tos,
90 self.src,
91 self.dst,
92 hex_with_len(&self.d)
93 )
94 }
95 }
96
97 impl<'a> Datagram<&'a mut [u8]> {
98 #[must_use]
99 pub fn from_slice(src: SocketAddr, dst: SocketAddr, tos: IpTos, d: &'a mut [u8]) -> Self {
100 Self { src, dst, tos, d }
101 }
102
103 #[must_use]
104 pub fn to_owned(&self) -> Datagram {
105 Datagram {
106 src: self.src,
107 dst: self.dst,
108 tos: self.tos,
109 d: self.d.to_vec(),
110 }
111 }
112 }
113
114 impl<D: AsRef<[u8]>> AsRef<[u8]> for Datagram<D> {
115 fn as_ref(&self) -> &[u8] {
116 self.d.as_ref()
117 }
118 }
119
120 #[cfg(test)]
121 mod tests {
122 use test_fixture::datagram;
123
124 #[test]
125 fn fmt_datagram() {
126 let d = datagram([0; 1].to_vec());
127 assert_eq!(
128 &format!("{d:?}"),
129 "Datagram IpTos(Cs0, Ect0) [fe80::1]:443->[fe80::1]:443: [1]: 00"
130 );
131 }
132
133 #[test]
134 fn is_empty() {
135 let d = datagram(vec![]);
136 assert_eq!(d.len(), 0);
137 assert!(d.is_empty());
138 }
139 }