1use core::{
2 net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
3 time::Duration,
4};
5use std::num::NonZeroUsize;
6
7use varing::{Varint, decode_duration, encode_duration_to, encoded_duration_len};
8
9use crate::{Data, DataRef, DecodeError, EncodeError, WireType};
10
11const IPV4_ADDR_LEN: usize = 4;
12const IPV6_ADDR_LEN: usize = 16;
13
14impl<'a> DataRef<'a, Self> for Ipv4Addr {
15 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError> {
16 if src.len() < IPV4_ADDR_LEN {
17 return Err(DecodeError::buffer_underflow());
18 }
19
20 let octets: [u8; IPV4_ADDR_LEN] = src[..IPV4_ADDR_LEN].try_into().unwrap();
21 Ok((IPV4_ADDR_LEN, Self::from(octets)))
22 }
23}
24
25impl Data for Ipv4Addr {
26 type Ref<'a> = Self;
27
28 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
29 Ok(val)
30 }
31
32 #[inline]
33 fn encoded_len(&self) -> usize {
34 IPV4_ADDR_LEN
35 }
36
37 #[inline]
38 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
39 if buf.len() < IPV4_ADDR_LEN {
40 return Err(EncodeError::insufficient_buffer(IPV4_ADDR_LEN, buf.len()));
41 }
42 buf[..IPV4_ADDR_LEN].copy_from_slice(&self.octets());
43 Ok(IPV4_ADDR_LEN)
44 }
45}
46
47impl<'a> DataRef<'a, Self> for Ipv6Addr {
48 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError> {
49 if src.len() < IPV6_ADDR_LEN {
50 return Err(DecodeError::buffer_underflow());
51 }
52
53 let octets: [u8; IPV6_ADDR_LEN] = src[..IPV6_ADDR_LEN].try_into().unwrap();
54 Ok((IPV6_ADDR_LEN, Self::from(octets)))
55 }
56}
57
58impl Data for Ipv6Addr {
59 type Ref<'a> = Self;
60
61 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
62 Ok(val)
63 }
64
65 #[inline]
66 fn encoded_len(&self) -> usize {
67 IPV6_ADDR_LEN
68 }
69
70 #[inline]
71 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
72 if buf.len() < IPV6_ADDR_LEN {
73 return Err(EncodeError::insufficient_buffer(IPV6_ADDR_LEN, buf.len()));
74 }
75 buf[..IPV6_ADDR_LEN].copy_from_slice(&self.octets());
76 Ok(IPV6_ADDR_LEN)
77 }
78}
79
80impl<'a> DataRef<'a, Self> for IpAddr {
81 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError> {
82 let buf_len = src.len();
83
84 if buf_len < 1 {
85 return Err(DecodeError::buffer_underflow());
86 }
87
88 match src[0] {
89 0 => {
90 let (len, addr) = <Ipv4Addr as DataRef<Ipv4Addr>>::decode(&src[1..])?;
91 Ok((len + 1, IpAddr::V4(addr)))
92 }
93 1 => {
94 let (len, addr) = <Ipv6Addr as DataRef<Ipv6Addr>>::decode(&src[1..])?;
95 Ok((len + 1, IpAddr::V6(addr)))
96 }
97 val => Err(DecodeError::unknown_tag("IpAddr", val)),
98 }
99 }
100}
101
102impl Data for IpAddr {
103 type Ref<'a> = Self;
104
105 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
106 Ok(val)
107 }
108
109 #[inline]
110 fn encoded_len(&self) -> usize {
111 1 + match self {
112 IpAddr::V4(addr) => addr.encoded_len(),
113 IpAddr::V6(addr) => addr.encoded_len(),
114 }
115 }
116
117 #[inline]
118 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
119 match self {
120 Self::V4(addr) => {
121 const V4_REQUIRED: usize = 1 + IPV4_ADDR_LEN;
122
123 if buf.len() < V4_REQUIRED {
124 return Err(EncodeError::insufficient_buffer(V4_REQUIRED, buf.len()));
125 }
126
127 buf[0] = 0;
128 buf[1..V4_REQUIRED].copy_from_slice(&addr.octets());
129 Ok(V4_REQUIRED)
130 }
131 Self::V6(addr) => {
132 const V6_REQUIRED: usize = 1 + IPV6_ADDR_LEN;
133
134 if buf.len() < V6_REQUIRED {
135 return Err(EncodeError::insufficient_buffer(V6_REQUIRED, buf.len()));
136 }
137
138 buf[0] = 1;
139 buf[1..V6_REQUIRED].copy_from_slice(&addr.octets());
140 Ok(V6_REQUIRED)
141 }
142 }
143 }
144}
145
146impl<'a> DataRef<'a, Self> for SocketAddrV4 {
147 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError>
148 where
149 Self: Sized,
150 {
151 const V4_REQUIRED: usize = IPV4_ADDR_LEN + 2;
152
153 let buf_len = src.len();
154
155 if buf_len < V4_REQUIRED {
156 return Err(DecodeError::buffer_underflow());
157 }
158
159 let (ip_len, ip) = <Ipv4Addr as DataRef<Ipv4Addr>>::decode(src)?;
160 let port = u16::from_be_bytes(src[ip_len..ip_len + 2].try_into().unwrap());
161 Ok((V4_REQUIRED, SocketAddrV4::new(ip, port)))
162 }
163}
164
165impl Data for SocketAddrV4 {
166 type Ref<'a> = Self;
167
168 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
169 Ok(val)
170 }
171
172 #[inline]
173 fn encoded_len(&self) -> usize {
174 IPV4_ADDR_LEN + 2
175 }
176
177 #[inline]
178 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
179 const V4_REQUIRED: usize = IPV4_ADDR_LEN + 2;
180
181 if buf.len() < V4_REQUIRED {
182 return Err(EncodeError::insufficient_buffer(V4_REQUIRED, buf.len()));
183 }
184
185 buf[..IPV4_ADDR_LEN].copy_from_slice(&self.ip().octets());
186 buf[IPV4_ADDR_LEN..V4_REQUIRED].copy_from_slice(&self.port().to_be_bytes());
187 Ok(V4_REQUIRED)
188 }
189}
190
191impl<'a> DataRef<'a, Self> for SocketAddrV6 {
192 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError>
193 where
194 Self: Sized,
195 {
196 const V6_REQUIRED: usize = IPV6_ADDR_LEN + 2;
197 let buf_len = src.len();
198
199 if buf_len < V6_REQUIRED {
200 return Err(DecodeError::buffer_underflow());
201 }
202
203 let (ip_len, ip) = <Ipv6Addr as DataRef<Ipv6Addr>>::decode(src)?;
204 let port = u16::from_be_bytes(src[ip_len..ip_len + 2].try_into().unwrap());
205 Ok((V6_REQUIRED, SocketAddrV6::new(ip, port, 0, 0)))
206 }
207}
208
209impl Data for SocketAddrV6 {
210 type Ref<'a> = Self;
211
212 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
213 Ok(val)
214 }
215
216 #[inline]
217 fn encoded_len(&self) -> usize {
218 IPV6_ADDR_LEN + 2
219 }
220
221 #[inline]
222 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
223 const V6_REQUIRED: usize = IPV6_ADDR_LEN + 2;
224
225 if buf.len() < V6_REQUIRED {
226 return Err(EncodeError::insufficient_buffer(V6_REQUIRED, buf.len()));
227 }
228
229 buf[..IPV6_ADDR_LEN].copy_from_slice(&self.ip().octets());
230 buf[IPV6_ADDR_LEN..V6_REQUIRED].copy_from_slice(&self.port().to_be_bytes());
231 Ok(V6_REQUIRED)
232 }
233}
234
235impl<'a> DataRef<'a, Self> for SocketAddr {
236 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError>
237 where
238 Self: Sized,
239 {
240 let buf_len = src.len();
241
242 if buf_len < 1 {
243 return Err(DecodeError::buffer_underflow());
244 }
245
246 match src[0] {
247 0 => {
248 let (len, addr) = <SocketAddrV4 as DataRef<SocketAddrV4>>::decode(&src[1..])?;
249 Ok((len + 1, SocketAddr::V4(addr)))
250 }
251 1 => {
252 let (len, addr) = <SocketAddrV6 as DataRef<SocketAddrV6>>::decode(&src[1..])?;
253 Ok((len + 1, SocketAddr::V6(addr)))
254 }
255 val => Err(DecodeError::unknown_tag("SocketAddr", val)),
256 }
257 }
258}
259
260impl Data for SocketAddr {
261 type Ref<'a> = Self;
262
263 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
264 Ok(val)
265 }
266
267 #[inline]
268 fn encoded_len(&self) -> usize {
269 1 + match self {
270 SocketAddr::V4(addr) => addr.encoded_len(),
271 SocketAddr::V6(addr) => addr.encoded_len(),
272 }
273 }
274
275 #[inline]
276 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
277 match self {
278 Self::V4(addr) => {
279 const V4_REQUIRED: usize = 1 + IPV4_ADDR_LEN + 2;
280
281 if buf.len() < V4_REQUIRED {
282 return Err(EncodeError::insufficient_buffer(V4_REQUIRED, buf.len()));
283 }
284
285 buf[0] = 0;
286 let len = addr.encode(&mut buf[1..])?;
287 Ok(len + 1)
288 }
289 Self::V6(addr) => {
290 const V6_REQUIRED: usize = 1 + IPV6_ADDR_LEN + 2;
291
292 if buf.len() < V6_REQUIRED {
293 return Err(EncodeError::insufficient_buffer(V6_REQUIRED, buf.len()));
294 }
295
296 buf[0] = 1;
297 let len = addr.encode(&mut buf[1..])?;
298 Ok(len + 1)
299 }
300 }
301 }
302}
303
304macro_rules! impl_primitives {
305 (@integer $($ty:ident), +$(,)?) => {
306 $(
307 impl<'a> DataRef<'a, Self> for $ty {
308 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError> {
309 Varint::decode(src).map(|(read, val)| (read.get(), val)).map_err(Into::into)
310 }
311 }
312
313 impl Data for $ty {
314 const WIRE_TYPE: WireType = WireType::Varint;
315
316 type Ref<'a> = Self;
317
318 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
319 Ok(val)
320 }
321
322 fn encoded_len(&self) -> usize {
323 Varint::encoded_len(self).get()
324 }
325
326 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
327 Varint::encode(self, buf).map(::core::num::NonZeroUsize::get).map_err(Into::into)
328 }
329 }
330 )*
331 };
332 (@float $($ty:literal), +$(,)?) => {
333 paste::paste! {
334 $(
335 impl<'a> DataRef<'a, Self> for [< f $ty >] {
336 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError> {
337 const SIZE: usize = core::mem::size_of::<[< f $ty >]>();
338
339 if src.len() < SIZE {
340 return Err(DecodeError::buffer_underflow());
341 }
342
343 let mut bytes = [0; SIZE];
344 bytes.copy_from_slice(&src[..SIZE]);
345 Ok((SIZE, Self::from_le_bytes(bytes)))
346 }
347 }
348
349 impl Data for [< f $ty >] {
350 const WIRE_TYPE: WireType = WireType:: [< Fixed $ty >];
351
352 type Ref<'a> = Self;
353
354 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
355 Ok(val)
356 }
357
358 fn encoded_len(&self) -> usize {
359 core::mem::size_of::<[< f $ty >]>()
360 }
361
362 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
363 const SIZE: usize = core::mem::size_of::<[< f $ty >]>();
364
365 if buf.len() < SIZE {
366 return Err(EncodeError::insufficient_buffer(
367 SIZE, buf.len(),
368 ));
369 }
370
371 buf[..SIZE].copy_from_slice(&self.to_le_bytes());
372 Ok(SIZE)
373 }
374 }
375 )*
376 }
377 };
378 (@as_u8 $($ty:ident), +$(,)?) => {
379 $(
380 impl<'a> DataRef<'a, Self> for $ty {
381 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError> {
382 <u8 as DataRef<u8>>::decode(src).map(|(bytes_read, value)| (bytes_read, value as $ty))
383 }
384 }
385
386 impl Data for $ty {
387 const WIRE_TYPE: WireType = WireType::Byte;
388
389 type Ref<'a> = Self;
390
391 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
392 Ok(val)
393 }
394
395 fn encoded_len(&self) -> usize {
396 <u8 as Data>::encoded_len(&(*self as u8))
397 }
398
399 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
400 <u8 as Data>::encode(&(*self as u8), buf)
401 }
402 }
403 )*
404 };
405 (@wrapper $($wrapper:ty), +$(,)?) => {
406 $(
407 impl<'a, T> DataRef<'a, $wrapper> for T::Ref<'a>
408 where
409 T: Data,
410 {
411 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError> {
412 let (bytes_read, value) = T::Ref::decode(src)?;
413 Ok((bytes_read, value))
414 }
415 }
416
417 impl<T> Data for $wrapper
418 where
419 T: Data,
420 {
421 const WIRE_TYPE: WireType = T::WIRE_TYPE;
422
423 type Ref<'a> = <T as Data>::Ref<'a>;
424
425 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
426 T::from_ref(val).map(From::from)
427 }
428
429 fn encoded_len(&self) -> usize {
430 T::encoded_len(&**self)
431 }
432
433 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
434 T::encode(&**self, buf)
435 }
436 }
437 )*
438 };
439}
440
441impl_primitives!(@integer u16, u32, u64, u128, i16, i32, i64, i128);
442impl_primitives!(@float 32, 64);
443impl_primitives!(@as_u8 i8);
444
445#[cfg(any(feature = "std", feature = "alloc"))]
446impl_primitives!(@wrapper std::sync::Arc<T>, std::boxed::Box<T>, triomphe::Arc<T>);
447
448impl<'a> DataRef<'a, Self> for char {
449 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError> {
450 let (bytes_read, value) = Varint::decode(src)?;
451 Ok((
452 bytes_read.get(),
453 char::from_u32(value).ok_or_else(|| DecodeError::custom("invalid character value"))?,
454 ))
455 }
456}
457
458impl Data for char {
459 const WIRE_TYPE: WireType = WireType::Varint;
460
461 type Ref<'a> = Self;
462
463 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
464 Ok(val)
465 }
466
467 fn encoded_len(&self) -> usize {
468 Varint::encoded_len(&(*self as u32)).get()
469 }
470
471 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
472 Varint::encode(&(*self as u32), buf)
473 .map(NonZeroUsize::get)
474 .map_err(Into::into)
475 }
476}
477
478impl<'a> DataRef<'a, Self> for u8 {
479 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError> {
480 if src.is_empty() {
481 return Err(DecodeError::buffer_underflow());
482 }
483
484 Ok((1, src[0]))
485 }
486}
487
488impl Data for u8 {
489 const WIRE_TYPE: WireType = WireType::Byte;
490
491 type Ref<'a> = Self;
492
493 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
494 Ok(val)
495 }
496
497 fn encoded_len(&self) -> usize {
498 1
499 }
500
501 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
502 if buf.is_empty() {
503 return Err(EncodeError::insufficient_buffer(1, 0));
504 }
505
506 buf[0] = *self;
507 Ok(1)
508 }
509}
510
511impl<'a> DataRef<'a, Self> for bool {
512 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError> {
513 if src.is_empty() {
514 return Err(DecodeError::buffer_underflow());
515 }
516 Ok((1, src[0] != 0))
517 }
518}
519
520impl Data for bool {
521 const WIRE_TYPE: WireType = WireType::Byte;
522
523 type Ref<'a> = Self;
524
525 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
526 Ok(val)
527 }
528
529 fn encoded_len(&self) -> usize {
530 1
531 }
532
533 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
534 <u8 as Data>::encode(&(*self as u8), buf)
535 }
536}
537
538impl<'a> DataRef<'a, Self> for Duration {
539 fn decode(src: &'a [u8]) -> Result<(usize, Self), DecodeError> {
540 decode_duration(src)
541 .map(|(read, val)| (read.get(), val))
542 .map_err(|_| DecodeError::custom("invalid duration"))
543 }
544}
545
546impl Data for Duration {
547 const WIRE_TYPE: WireType = WireType::Varint;
548
549 type Ref<'a> = Self;
550
551 fn from_ref(val: Self::Ref<'_>) -> Result<Self, DecodeError> {
552 Ok(val)
553 }
554
555 fn encoded_len(&self) -> usize {
556 encoded_duration_len(self).get()
557 }
558
559 fn encode(&self, buf: &mut [u8]) -> Result<usize, EncodeError> {
560 encode_duration_to(self, buf)
561 .map(NonZeroUsize::get)
562 .map_err(Into::into)
563 }
564}