value_log/slice/
slice_default.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
7/// An immutable byte slice that can be cloned without additional heap allocation
8///
9/// There is no guarantee of any sort of alignment for zero-copy (de)serialization.
10#[derive(Debug, Clone, Eq, Hash, Ord)]
11pub struct Slice(pub(super) ByteView);
12
13impl Slice {
14    /// Construct a [`Slice`] from a byte slice.
15    #[must_use]
16    pub fn new(bytes: &[u8]) -> Self {
17        Self(bytes.into())
18    }
19
20    #[doc(hidden)]
21    #[must_use]
22    pub fn empty() -> Self {
23        Self(ByteView::new(&[]))
24    }
25
26    #[doc(hidden)]
27    #[must_use]
28    pub fn slice(&self, range: impl std::ops::RangeBounds<usize>) -> Self {
29        Self(self.0.slice(range))
30    }
31
32    // TODO: change to unzeroed and provide a _zeroed method instead
33    #[must_use]
34    #[doc(hidden)]
35    pub fn with_size(len: usize) -> Self {
36        Self(ByteView::with_size(len))
37    }
38
39    /// Constructs a [`Slice`] from an I/O reader by pulling in `len` bytes.
40    #[doc(hidden)]
41    pub fn from_reader<R: std::io::Read>(reader: &mut R, len: usize) -> std::io::Result<Self> {
42        let view = ByteView::from_reader(reader, len)?;
43        Ok(Self(view))
44    }
45}
46
47// Arc::from<Vec<u8>> is specialized
48impl From<Vec<u8>> for Slice {
49    fn from(value: Vec<u8>) -> Self {
50        Self(ByteView::from(value))
51    }
52}
53
54// Arc::from<Vec<String>> is specialized
55impl From<String> for Slice {
56    fn from(value: String) -> Self {
57        Self(ByteView::from(value.into_bytes()))
58    }
59}
60
61impl From<ByteView> for Slice {
62    fn from(value: ByteView) -> Self {
63        Self(value)
64    }
65}
66
67impl From<Slice> for ByteView {
68    fn from(value: Slice) -> Self {
69        value.0
70    }
71}