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    pub(crate) fn empty() -> Self {
23        Self(ByteView::new(&[]))
24    }
25
26    pub(crate) unsafe fn builder_unzeroed(len: usize) -> Builder {
27        ByteView::builder_unzeroed(len)
28    }
29
30    pub(crate) fn slice(&self, range: impl std::ops::RangeBounds<usize>) -> Self {
31        Self(self.0.slice(range))
32    }
33
34    pub(crate) fn fused(left: &[u8], right: &[u8]) -> Self {
35        Self(ByteView::fused(left, right))
36    }
37
38    pub(crate) fn from_reader<R: std::io::Read>(
39        reader: &mut R,
40        len: usize,
41    ) -> std::io::Result<Self> {
42        ByteView::from_reader(reader, len).map(Self)
43    }
44}
45
46// Arc::from<Vec<u8>> is specialized
47impl From<Vec<u8>> for Slice {
48    fn from(value: Vec<u8>) -> Self {
49        Self(ByteView::from(value))
50    }
51}
52
53// Arc::from<Vec<String>> is specialized
54impl From<String> for Slice {
55    fn from(value: String) -> Self {
56        Self(ByteView::from(value.into_bytes()))
57    }
58}
59
60impl From<ByteView> for Slice {
61    fn from(value: ByteView) -> Self {
62        Self(value)
63    }
64}
65
66impl From<Slice> for ByteView {
67    fn from(value: Slice) -> Self {
68        value.0
69    }
70}