Skip to main content

rust_rocksdb/
db_pinnable_slice.rs

1// Copyright 2020 Tyler Neely
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::{DB, ffi};
16use core::ops::Deref;
17use libc::size_t;
18use std::marker::PhantomData;
19use std::slice;
20
21/// Wrapper around RocksDB PinnableSlice struct.
22///
23/// With a pinnable slice, we can directly leverage in-memory data within
24/// RocksDB to avoid unnecessary memory copies. The struct here wraps the
25/// returned raw pointer and ensures proper finalization work.
26pub struct DBPinnableSlice<'a> {
27    ptr: *mut ffi::rocksdb_pinnableslice_t,
28    // `(data, len)` are resolved once at construction rather than on every
29    // deref. `rocksdb_pinnableslice_value` is an out-of-line C function that
30    // only reads `rep.data()` / `rep.size()`, so calling it from `deref` meant
31    // every `len()`, index, and `as_ref()` paid a cross-crate Rust call plus a
32    // C call. The underlying `PinnableSlice` is not mutated after RocksDB hands
33    // it back, so the pointer and length are stable for our lifetime.
34    data: *const u8,
35    len: usize,
36    db: PhantomData<&'a DB>,
37}
38
39unsafe impl Send for DBPinnableSlice<'_> {}
40unsafe impl Sync for DBPinnableSlice<'_> {}
41
42impl AsRef<[u8]> for DBPinnableSlice<'_> {
43    #[inline]
44    fn as_ref(&self) -> &[u8] {
45        // Implement this via Deref so as not to repeat ourselves
46        self
47    }
48}
49
50impl Deref for DBPinnableSlice<'_> {
51    type Target = [u8];
52
53    #[inline]
54    fn deref(&self) -> &[u8] {
55        if self.len == 0 {
56            // An empty-but-present value can carry a null data pointer, and
57            // `slice::from_raw_parts(null, 0)` is undefined behaviour.
58            return &[];
59        }
60        // SAFETY: `data`/`len` were read from the pinned slice at construction
61        // and describe memory kept alive by the pin until `Drop`.
62        unsafe { slice::from_raw_parts(self.data, self.len) }
63    }
64}
65
66impl Drop for DBPinnableSlice<'_> {
67    fn drop(&mut self) {
68        unsafe {
69            ffi::rocksdb_pinnableslice_destroy(self.ptr);
70        }
71    }
72}
73
74impl DBPinnableSlice<'_> {
75    /// Used to wrap a PinnableSlice from rocksdb to avoid unnecessary memcpy
76    ///
77    /// # Unsafe
78    /// Requires that the pointer must be generated by rocksdb_get_pinned
79    pub(crate) unsafe fn from_c(ptr: *mut ffi::rocksdb_pinnableslice_t) -> Self {
80        let mut len: size_t = 0;
81        // SAFETY: caller guarantees `ptr` is a live pinnable slice.
82        let data = unsafe { ffi::rocksdb_pinnableslice_value(ptr, &raw mut len) }.cast::<u8>();
83        Self {
84            ptr,
85            data,
86            len,
87            db: PhantomData,
88        }
89    }
90}