diesel/sqlite/connection/serialized_database.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#![allow(unsafe_code)]
extern crate libsqlite3_sys as ffi;
use std::ops::Deref;
/// `SerializedDatabase` is a wrapper for a serialized database that is dynamically allocated by calling `sqlite3_serialize`.
/// This RAII wrapper is necessary to deallocate the memory when it goes out of scope with `sqlite3_free`.
#[derive(Debug)]
pub struct SerializedDatabase {
data: *mut u8,
len: usize,
}
impl SerializedDatabase {
/// Creates a new `SerializedDatabase` with the given data pointer and length.
///
/// SAFETY: The data pointer needs to be returned by sqlite
/// and the length must match the underlying buffer pointer
pub(crate) unsafe fn new(data: *mut u8, len: usize) -> Self {
Self { data, len }
}
/// Returns a slice of the serialized database.
pub fn as_slice(&self) -> &[u8] {
// The pointer is never null because we don't pass the NO_COPY flag
unsafe { std::slice::from_raw_parts(self.data, self.len) }
}
}
impl Deref for SerializedDatabase {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
impl Drop for SerializedDatabase {
/// Deallocates the memory of the serialized database when it goes out of scope.
fn drop(&mut self) {
unsafe {
ffi::sqlite3_free(self.data as _);
}
}
}