ckb_rocksdb/
db_vector.rs

1// Copyright 2019 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//
15
16use libc::{self, c_void, size_t};
17use std::ops::Deref;
18use std::slice;
19use std::str;
20
21/// Vector of bytes stored in the database.
22///
23/// This is a `C` allocated byte array and a length value.
24/// Normal usage would be to utilize the fact it implements `Deref<[u8]>` and use it as
25/// a slice.
26pub struct DBVector {
27    base: *mut u8,
28    len: usize,
29}
30
31impl Deref for DBVector {
32    type Target = [u8];
33
34    fn deref(&self) -> &[u8] {
35        unsafe { slice::from_raw_parts(self.base, self.len) }
36    }
37}
38
39impl AsRef<[u8]> for DBVector {
40    fn as_ref(&self) -> &[u8] {
41        // Implement this via Deref so as not to repeat ourselves
42        self
43    }
44}
45
46impl Drop for DBVector {
47    fn drop(&mut self) {
48        unsafe {
49            ffi::rocksdb_free(self.base as *mut c_void);
50        }
51    }
52}
53
54impl DBVector {
55    /// Used internally to create a DBVector from a `C` memory block
56    ///
57    /// # Unsafe
58    /// Requires that the ponter be allocated by a `malloc` derivative (all C libraries), and
59    /// `val_len` be the length of the C array to be safe (since `sizeof(u8) = 1`).
60    ///
61    /// # Examples
62    ///
63    /// ```ignore
64    /// let buf_len: libc::size_t = unsafe { mem::uninitialized() };
65    /// // Assume the function fills buf_len with the length of the returned array
66    /// let buf: *mut u8 = unsafe { ffi_function_returning_byte_array(&buf_len) };
67    /// DBVector::from_c(buf, buf_len)
68    /// ```
69    pub unsafe fn from_c(val: *mut u8, val_len: size_t) -> DBVector {
70        DBVector {
71            base: val,
72            len: val_len,
73        }
74    }
75
76    /// Convenience function to attempt to reinterperet value as string.
77    ///
78    /// implemented as `str::from_utf8(&self[..])`
79    pub fn to_utf8(&self) -> Option<&str> {
80        str::from_utf8(self.deref()).ok()
81    }
82}