1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
use std::{
    borrow::Borrow,
    cell::RefCell,
    cmp::Ordering,
    ops::{Bound, Deref, DerefMut, RangeBounds},
    sync::Arc,
};

thread_local! {
    static BUFF_POOL: RefCell<Vec<Vec<u8>>> = Default::default()
}

// static BUFF_POOL: Lazy<ConcurrentQueue<Vec<u8>>> = Lazy::new(|| ConcurrentQueue::bounded(10000));

/// Represents a *mutable* buffer optimized for packet-sized payloads.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(transparent)]
pub struct BuffMut {
    inner: Vec<u8>,
}

impl Deref for BuffMut {
    type Target = Vec<u8>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for BuffMut {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl Drop for BuffMut {
    #[inline]
    fn drop(&mut self) {
        // dbg!(BUFF_POOL.len());
        let _ = BUFF_POOL.with(|bp| bp.borrow_mut().push(std::mem::take(&mut self.inner)));
    }
}

impl Default for BuffMut {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl BuffMut {
    /// Creates a new BuffMut
    #[inline]
    pub fn new() -> Self {
        let mut new_vec = BUFF_POOL.with(|bp| {
            bp.borrow_mut()
                .pop()
                .unwrap_or_else(|| Vec::with_capacity(2048))
        });
        new_vec.clear();
        Self { inner: new_vec }
    }

    /// Freezes the BuffMut into a Buff.
    #[inline]
    pub fn freeze(self) -> Buff {
        Buff {
            frozen: Arc::new(self),
            bounds: vec![(Bound::Unbounded, Bound::Unbounded)],
        }
    }

    /// Copies from a slice.
    #[inline]
    pub fn copy_from_slice(other: &[u8]) -> Self {
        let mut m = Self::new();
        m.extend_from_slice(other);
        m
    }
}

/// Represents an *immutable* buffer.
#[derive(Clone, Debug, Deserialize)]
#[serde(from = "BuffMut")]
pub struct Buff {
    frozen: Arc<BuffMut>,
    bounds: Vec<(Bound<usize>, Bound<usize>)>,
}

impl PartialEq<Buff> for Buff {
    #[inline]
    fn eq(&self, other: &Buff) -> bool {
        self.deref() == other.deref()
    }
}

impl Eq for Buff {}

impl PartialOrd<Buff> for Buff {
    #[inline]
    fn partial_cmp(&self, other: &Buff) -> Option<Ordering> {
        self.deref().partial_cmp(other.deref())
    }
}

impl Ord for Buff {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.deref().cmp(other.deref())
    }
}

impl Default for Buff {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Buff {
    /// Creates a new, empty Buff.
    #[inline]
    pub fn new() -> Self {
        Self::copy_from_slice(&[])
    }
    /// "Slices" the buff, making another buff. Takes ownership to prevent unnecessary cloning.
    #[inline]
    pub fn slice(mut self, bounds: impl RangeBounds<usize>) -> Self {
        // make sure not OOB
        let loo: &[u8] = self.as_ref();
        let start_bound = match bounds.start_bound() {
            Bound::Excluded(bound) => Bound::Excluded(*bound),
            Bound::Included(bound) => Bound::Included(*bound),
            Bound::Unbounded => Bound::Unbounded,
        };
        let end_bound = match bounds.end_bound() {
            Bound::Excluded(bound) => Bound::Excluded(*bound),
            Bound::Included(bound) => Bound::Included(*bound),
            Bound::Unbounded => Bound::Unbounded,
        };
        // intentionally trigger panic if OOB
        let _ = &loo[(start_bound, end_bound)];
        self.bounds.push((start_bound, end_bound));
        Self {
            frozen: self.frozen,
            bounds: self.bounds,
        }
    }

    /// Creates a new buff by copying from a slice
    #[inline]
    pub fn copy_from_slice(other: &[u8]) -> Self {
        let mut inner = BuffMut::new();
        inner.extend_from_slice(other);
        inner.freeze()
    }
}

impl Deref for Buff {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

impl From<BuffMut> for Buff {
    #[inline]
    fn from(m: BuffMut) -> Self {
        m.freeze()
    }
}

impl From<&[u8]> for Buff {
    #[inline]
    fn from(m: &[u8]) -> Self {
        Self::copy_from_slice(m)
    }
}

impl Serialize for Buff {
    // #[inline]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let buf = serde_bytes::Bytes::new(self.as_ref());
        buf.serialize(serializer)
    }
}

impl AsRef<[u8]> for Buff {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        let mut toret = self.frozen.as_slice();
        for bound in self.bounds.iter().copied() {
            toret = &toret[bound]
        }
        toret
    }
}

impl Borrow<[u8]> for Buff {
    #[inline]
    fn borrow(&self) -> &[u8] {
        self.as_ref()
    }
}

impl<'de> Deserialize<'de> for BuffMut {
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_bytes(BuffMutVisitor {})
    }
}

struct BuffMutVisitor;

impl<'de> Visitor<'de> for BuffMutVisitor {
    type Value = BuffMut;

    #[inline]
    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a byte array")
    }

    #[inline]
    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        let mut bm = BuffMut::new();
        bm.extend_from_slice(v);
        Ok(bm)
    }

    // #[inline]
    // fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
    // where
    //     E: serde::de::Error,
    // {
    //     Ok(BuffMut { inner: v })
    // }
}