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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
use std::{
    borrow::Cow,
    fs::File,
    hash::Hash,
    ops::{Deref, Index, RangeBounds},
    path::{Path, PathBuf},
};

use bytes::{Buf, Bytes};

use crate::{mmap::MmappedSlice, MmapError};

/// A cheaply cloneable owned buffer that may be backed by a memory-mapped file
/// or [`Bytes`] in memory.
#[derive(Debug, Clone, Default)]
pub struct OwnedBuffer {
    repr: Repr,
}

impl OwnedBuffer {
    pub const fn new() -> Self {
        OwnedBuffer {
            repr: Repr::InMemory(Bytes::new()),
        }
    }

    pub const fn from_static(bytes: &'static [u8]) -> Self {
        OwnedBuffer {
            repr: Repr::InMemory(Bytes::from_static(bytes)),
        }
    }

    pub fn from_bytes(bytes: impl Into<Bytes>) -> Self {
        bytes.into().into()
    }

    pub fn mmap(path: impl AsRef<Path>) -> Result<Self, MmapError> {
        let mmap = MmappedSlice::from_path(path.as_ref())?;
        Ok(mmap.into())
    }

    pub fn from_file(file: &File) -> Result<Self, MmapError> {
        let mmap = MmappedSlice::from_file(file)?;
        Ok(mmap.into())
    }

    pub fn into_bytes(self) -> Bytes {
        match self.repr {
            Repr::InMemory(b) => b,
            Repr::Mmap(m) => Bytes::from(m.as_slice().to_vec()),
        }
    }

    pub fn as_bytes(&self) -> Option<&Bytes> {
        self.repr.as_bytes()
    }

    #[inline]
    pub fn as_slice(&self) -> &[u8] {
        match &self.repr {
            Repr::InMemory(b) => b,
            Repr::Mmap(m) => m.as_slice(),
        }
    }

    #[inline]
    pub fn slice(&self, range: impl RangeBounds<usize>) -> Self {
        self.repr.slice(range).into()
    }

    pub fn is_mmapped(&self) -> bool {
        matches!(self.repr, Repr::Mmap(_))
    }
}

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

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

impl AsRef<[u8]> for OwnedBuffer {
    fn as_ref(&self) -> &[u8] {
        self.as_slice()
    }
}

impl PartialEq for OwnedBuffer {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.as_slice() == other.as_slice()
    }
}

impl PartialEq<[u8]> for OwnedBuffer {
    fn eq(&self, other: &[u8]) -> bool {
        self.as_slice() == other
    }
}

impl PartialEq<&[u8]> for OwnedBuffer {
    fn eq(&self, other: &&[u8]) -> bool {
        self.as_slice() == *other
    }
}

impl<const N: usize> PartialEq<[u8; N]> for OwnedBuffer {
    fn eq(&self, other: &[u8; N]) -> bool {
        self.as_slice() == other
    }
}

impl<const N: usize> PartialEq<&[u8; N]> for OwnedBuffer {
    fn eq(&self, other: &&[u8; N]) -> bool {
        self.as_slice() == *other
    }
}

impl PartialEq<Vec<u8>> for OwnedBuffer {
    fn eq(&self, other: &Vec<u8>) -> bool {
        self.as_slice() == other
    }
}

impl PartialEq<&Vec<u8>> for OwnedBuffer {
    fn eq(&self, other: &&Vec<u8>) -> bool {
        self.as_slice() == *other
    }
}

impl PartialEq<OwnedBuffer> for [u8] {
    fn eq(&self, other: &OwnedBuffer) -> bool {
        other == self
    }
}

impl PartialEq<OwnedBuffer> for &[u8] {
    fn eq(&self, other: &OwnedBuffer) -> bool {
        other == self
    }
}

impl<const N: usize> PartialEq<OwnedBuffer> for [u8; N] {
    fn eq(&self, other: &OwnedBuffer) -> bool {
        other == self
    }
}

impl<const N: usize> PartialEq<OwnedBuffer> for &[u8; N] {
    fn eq(&self, other: &OwnedBuffer) -> bool {
        other == self
    }
}

impl PartialEq<OwnedBuffer> for Vec<u8> {
    fn eq(&self, other: &OwnedBuffer) -> bool {
        other == self
    }
}

impl PartialEq<OwnedBuffer> for &Vec<u8> {
    fn eq(&self, other: &OwnedBuffer) -> bool {
        other == self
    }
}

impl<'a> IntoIterator for &'a OwnedBuffer {
    type Item = &'a u8;
    type IntoIter = std::slice::Iter<'a, u8>;

    fn into_iter(self) -> Self::IntoIter {
        self.as_slice().iter()
    }
}

impl IntoIterator for OwnedBuffer {
    type Item = u8;
    type IntoIter = OwnedIntoIter;

    fn into_iter(self) -> Self::IntoIter {
        OwnedIntoIter {
            buffer: self,
            next_index: 0,
        }
    }
}

impl<I> Index<I> for OwnedBuffer
where
    [u8]: Index<I>,
{
    type Output = <[u8] as Index<I>>::Output;

    fn index(&self, index: I) -> &Self::Output {
        &self.as_slice()[index]
    }
}

impl Eq for OwnedBuffer {}

impl Ord for OwnedBuffer {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_slice().cmp(other.as_slice())
    }
}

impl PartialOrd for OwnedBuffer {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Hash for OwnedBuffer {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.as_slice().hash(state);
    }
}

impl Buf for OwnedBuffer {
    fn remaining(&self) -> usize {
        self.len()
    }

    fn chunk(&self) -> &[u8] {
        self.as_slice()
    }

    fn advance(&mut self, cnt: usize) {
        match &mut self.repr {
            Repr::InMemory(b) => b.advance(cnt),
            Repr::Mmap(m) => m.advance(cnt),
        }
    }
}

impl From<Bytes> for OwnedBuffer {
    fn from(value: Bytes) -> Self {
        OwnedBuffer {
            repr: Repr::InMemory(value),
        }
    }
}

impl From<&[u8]> for OwnedBuffer {
    fn from(value: &[u8]) -> Self {
        value.to_vec().into()
    }
}

impl From<Cow<'_, [u8]>> for OwnedBuffer {
    fn from(value: Cow<'_, [u8]>) -> Self {
        match value {
            Cow::Borrowed(value) => value.into(),
            Cow::Owned(value) => value.into(),
        }
    }
}

impl From<Vec<u8>> for OwnedBuffer {
    fn from(value: Vec<u8>) -> Self {
        Bytes::from(value).into()
    }
}

impl From<&Vec<u8>> for OwnedBuffer {
    fn from(value: &Vec<u8>) -> Self {
        value.as_slice().into()
    }
}

impl From<OwnedBuffer> for Vec<u8> {
    fn from(value: OwnedBuffer) -> Self {
        value.to_vec()
    }
}

impl From<Repr> for OwnedBuffer {
    fn from(repr: Repr) -> Self {
        OwnedBuffer { repr }
    }
}

impl From<MmappedSlice> for OwnedBuffer {
    fn from(mmap: MmappedSlice) -> Self {
        Repr::Mmap(mmap).into()
    }
}

impl TryFrom<&Path> for OwnedBuffer {
    type Error = MmapError;

    fn try_from(value: &Path) -> Result<Self, Self::Error> {
        OwnedBuffer::mmap(value)
    }
}

impl TryFrom<PathBuf> for OwnedBuffer {
    type Error = MmapError;

    fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
        OwnedBuffer::mmap(value)
    }
}

impl TryFrom<&PathBuf> for OwnedBuffer {
    type Error = MmapError;

    fn try_from(value: &PathBuf) -> Result<Self, Self::Error> {
        OwnedBuffer::mmap(value)
    }
}

impl TryFrom<&std::fs::File> for OwnedBuffer {
    type Error = MmapError;

    fn try_from(file: &std::fs::File) -> Result<Self, Self::Error> {
        OwnedBuffer::from_file(file)
    }
}

impl TryFrom<std::fs::File> for OwnedBuffer {
    type Error = MmapError;

    fn try_from(file: std::fs::File) -> Result<Self, Self::Error> {
        OwnedBuffer::from_file(&file)
    }
}

impl TryFrom<OwnedBuffer> for Bytes {
    type Error = OwnedBuffer;

    fn try_from(value: OwnedBuffer) -> Result<Self, Self::Error> {
        if let Repr::InMemory(bytes) = value.repr {
            Ok(bytes)
        } else {
            Err(value)
        }
    }
}

#[derive(Debug, Clone)]
enum Repr {
    InMemory(Bytes),
    Mmap(MmappedSlice),
}

impl Repr {
    #[inline]
    fn slice(&self, range: impl RangeBounds<usize>) -> Self {
        match self {
            Repr::InMemory(b) => Repr::InMemory(b.slice(range)),
            Repr::Mmap(m) => Repr::Mmap(m.slice(range)),
        }
    }

    #[inline]
    fn as_bytes(&self) -> Option<&Bytes> {
        match self {
            Repr::InMemory(b) => Some(b),
            _ => None,
        }
    }
}

impl Default for Repr {
    fn default() -> Self {
        Repr::InMemory(Bytes::new())
    }
}

#[derive(Debug, Clone)]
pub struct OwnedIntoIter {
    buffer: OwnedBuffer,
    next_index: usize,
}

impl Iterator for OwnedIntoIter {
    type Item = u8;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let &byte = self.buffer.as_slice().get(self.next_index)?;
        self.next_index += 1;
        Some(byte)
    }
}