Debian Codegraph @

rust/hg-core/src/dyn_bytes.rs

raw
1 use std::ops::Deref;
2
3 /// An owned object that can be borrowed as a byte array,
4 /// but without the dynamic dispatch overhead involved when
5 /// accessing the byte array.
6 use self_cell::self_cell;
7
8 /// A byte array representation that supports truncation.
9 pub trait ByteStoreTrunc: Deref<Target = [u8]> {
10 fn truncate(&mut self, new_size: usize);
11 }
12
13 /// Wrapper needed to make the `self_cell!` macro happy.
14 struct BorrowedBytes<'a> {
15 bytes: &'a [u8],
16 }
17
18 self_cell!(
19 struct CachedBytes<'w> {
20 owner: Box<dyn Deref<Target = [u8]> + Send + Sync + 'w>,
21 #[covariant]
22 dependent: BorrowedBytes,
23 }
24 );
25
26 /// `DynBytes` keeps an owned slice of bytes backed with opaque boxed storage,
27 /// whose destructor is based on dynamic dispatch.
28 pub struct DynBytes<'w> {
29 // the indirection lets us put a nicer interface on the
30 // slightly-ugly thing derived by self_cell
31 inner: CachedBytes<'w>,
32 }
33
34 impl DynBytes<'_> {
35 pub fn new(store: Box<dyn Deref<Target = [u8]> + Send + Sync>) -> Self {
36 Self {
37 inner: CachedBytes::new(store, |store| BorrowedBytes {
38 bytes: store.deref(),
39 }),
40 }
41 }
42 }
43
44 impl ByteStoreTrunc for DynBytes<'_> {
45 fn truncate(&mut self, new_size: usize) {
46 self.inner.with_dependent_mut(|_owning, bytes: &mut BorrowedBytes| {
47 bytes.bytes = &bytes.bytes[..new_size]
48 })
49 }
50 }
51
52 impl Deref for DynBytes<'_> {
53 type Target = [u8];
54
55 fn deref(&self) -> &Self::Target {
56 self.inner.borrow_dependent().bytes
57 }
58 }
59
60 impl Default for DynBytes<'_> {
61 fn default() -> Self {
62 DynBytes::new(Box::<Vec<u8>>::default())
63 }
64 }