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::{ffi, DB};
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 db: PhantomData<&'a DB>,
29}
30
31unsafe impl<'a> Send for DBPinnableSlice<'a> {}
32unsafe impl<'a> Sync for DBPinnableSlice<'a> {}
33
34impl<'a> AsRef<[u8]> for DBPinnableSlice<'a> {
35 fn as_ref(&self) -> &[u8] {
36 // Implement this via Deref so as not to repeat ourselves
37 self
38 }
39}
40
41impl<'a> Deref for DBPinnableSlice<'a> {
42 type Target = [u8];
43
44 fn deref(&self) -> &[u8] {
45 unsafe {
46 let mut val_len: size_t = 0;
47 let val = ffi::rocksdb_pinnableslice_value(self.ptr, &mut val_len) as *mut u8;
48 slice::from_raw_parts(val, val_len)
49 }
50 }
51}
52
53impl<'a> Drop for DBPinnableSlice<'a> {
54 fn drop(&mut self) {
55 unsafe {
56 ffi::rocksdb_pinnableslice_destroy(self.ptr);
57 }
58 }
59}
60
61impl<'a> DBPinnableSlice<'a> {
62 /// Used to wrap a PinnableSlice from rocksdb to avoid unnecessary memcpy
63 ///
64 /// # Unsafe
65 /// Requires that the pointer must be generated by rocksdb_get_pinned
66 pub(crate) unsafe fn from_c(ptr: *mut ffi::rocksdb_pinnableslice_t) -> Self {
67 Self {
68 ptr,
69 db: PhantomData,
70 }
71 }
72}