Skip to main content

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