lsm_tree/slice/slice_default/
mod.rs

1// Copyright (c) 2024-present, fjall-rs
2// This source code is licensed under both the Apache 2.0 and MIT License
3// (found in the LICENSE-* files in the repository)
4
5use byteview::ByteView;
6
7pub use byteview::Builder;
8
9/// An immutable byte slice that can be cloned without additional heap allocation
10///
11/// There is no guarantee of any sort of alignment for zero-copy (de)serialization.
12#[derive(Debug, Clone, Eq, Hash, Ord)]
13pub struct Slice(pub(super) ByteView);
14
15impl Slice {
16    /// Construct a [`Slice`] from a byte slice.
17    #[must_use]
18    pub fn new(bytes: &[u8]) -> Self {
19        Self(bytes.into())
20    }
21
22    #[doc(hidden)]
23    #[must_use]
24    pub fn empty() -> Self {
25        Self(ByteView::new(&[]))
26    }
27
28    #[doc(hidden)]
29    #[must_use]
30    pub unsafe fn builder_unzeroed(len: usize) -> Builder {
31        ByteView::builder_unzeroed(len)
32    }
33
34    pub(crate) fn slice(&self, range: impl std::ops::RangeBounds<usize>) -> Self {
35        Self(self.0.slice(range))
36    }
37
38    pub(crate) fn fused(left: &[u8], right: &[u8]) -> Self {
39        Self(ByteView::fused(left, right))
40    }
41
42    #[doc(hidden)]
43    pub fn from_reader<R: std::io::Read>(reader: &mut R, len: usize) -> std::io::Result<Self> {
44        ByteView::from_reader(reader, len).map(Self)
45    }
46}
47
48// Arc::from<Vec<u8>> is specialized
49impl From<Vec<u8>> for Slice {
50    fn from(value: Vec<u8>) -> Self {
51        Self(ByteView::from(value))
52    }
53}
54
55// Arc::from<Vec<String>> is specialized
56impl From<String> for Slice {
57    fn from(value: String) -> Self {
58        Self(ByteView::from(value.into_bytes()))
59    }
60}
61
62impl From<ByteView> for Slice {
63    fn from(value: ByteView) -> Self {
64        Self(value)
65    }
66}
67
68impl From<Slice> for ByteView {
69    fn from(value: Slice) -> Self {
70        value.0
71    }
72}