psp_net/traits/
mod.rs

1//! Traits implemented by the crate types.
2
3use alloc::vec::Vec;
4use core::fmt::Debug;
5
6#[cfg(feature = "psp")]
7pub mod dns;
8pub mod io;
9
10/// A trait for a buffer that can be used with a socket.
11///
12/// It can be used by either a read or write buffer of a socket.
13pub trait SocketBuffer: Clone + Debug + Default {
14    /// Create a new buffer
15    fn new() -> Self
16    where
17        Self: Sized;
18
19    /// Append a buffer to the end.
20    ///
21    /// # Arguments
22    /// - `buf`: buffer containing the data to be appended
23    fn append_buffer(&mut self, buf: &[u8]);
24
25    /// Shift the buffer to the left by amount
26    ///
27    /// This is used to remove data from the buffer.
28    fn shift_left_buffer(&mut self, amount: usize);
29
30    /// Clear the buffer
31    fn clear(&mut self) {
32        self.shift_left_buffer(self.len());
33    }
34
35    /// Check if the buffer is empty
36    fn is_empty(&self) -> bool {
37        self.len() == 0
38    }
39
40    /// Get the buffer as a slice
41    ///
42    /// # Returns
43    /// - The buffer as a slice of bytes
44    fn as_slice(&self) -> &[u8];
45
46    /// Get the length of the buffer
47    fn len(&self) -> usize;
48}
49
50impl SocketBuffer for Vec<u8> {
51    #[inline]
52    fn new() -> Self {
53        Vec::new()
54    }
55
56    #[inline]
57    fn append_buffer(&mut self, buf: &[u8]) {
58        self.append(&mut buf.to_vec());
59    }
60
61    fn shift_left_buffer(&mut self, amount: usize) {
62        // shift the buffer to the left by amount
63        if self.len() <= amount {
64            self.clear();
65        } else {
66            self.drain(..amount);
67        }
68    }
69
70    #[inline]
71    fn len(&self) -> usize {
72        self.len()
73    }
74
75    #[inline]
76    fn clear(&mut self) {
77        self.clear();
78    }
79
80    #[inline]
81    fn as_slice(&self) -> &[u8] {
82        self.as_slice()
83    }
84}