From f42db5b4a2bbf2a22e79a5e18b5d447f0bb9bc29 Mon Sep 17 00:00:00 2001 From: Matthias Seitz Date: Wed, 15 Nov 2023 15:30:09 +0100 Subject: [PATCH] chore: put env types into container type (#5436) Co-authored-by: DaniPopes <57450786+DaniPopes@users.noreply.github.com> --- crates/storage/libmdbx-rs/src/environment.rs | 42 +++++++++++--------- 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/crates/storage/libmdbx-rs/src/environment.rs b/crates/storage/libmdbx-rs/src/environment.rs index 7315c9f082..e8ace3115f 100644 --- a/crates/storage/libmdbx-rs/src/environment.rs +++ b/crates/storage/libmdbx-rs/src/environment.rs @@ -70,8 +70,7 @@ pub struct Environment where E: EnvironmentKind, { - env: *mut ffi::MDBX_env, - txn_manager: Option>, + inner: EnvironmentInner, _marker: PhantomData, } @@ -102,7 +101,7 @@ where /// Requires [Mode::ReadWrite] and returns None otherwise. #[inline] pub(crate) fn txn_manager(&self) -> Option<&SyncSender> { - self.txn_manager.as_ref() + self.inner.txn_manager.as_ref() } /// Returns a raw pointer to the underlying MDBX environment. @@ -111,7 +110,7 @@ where /// environment. #[inline] pub fn env(&self) -> *mut ffi::MDBX_env { - self.env + self.inner.env } /// Create a read-only transaction for use with the environment. @@ -223,6 +222,24 @@ where } } +/// Container type for Environment internals. +/// +/// This holds the raw pointer to the MDBX environment and the transaction manager. +/// The env is opened via [mdbx_env_create](ffi::mdbx_env_create) and closed when this type drops. +struct EnvironmentInner { + env: *mut ffi::MDBX_env, + txn_manager: Option>, +} + +impl Drop for EnvironmentInner { + fn drop(&mut self) { + // Close open mdbx environment on drop + unsafe { + ffi::mdbx_env_close_ex(self.env, false); + } + } +} + /// Environment statistics. /// /// Contains information about the size and layout of an MDBX environment or database. @@ -338,18 +355,7 @@ where E: EnvironmentKind, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Environment").finish() - } -} - -impl Drop for Environment -where - E: EnvironmentKind, -{ - fn drop(&mut self) { - unsafe { - ffi::mdbx_env_close_ex(self.env, false); - } + f.debug_struct("Environment").finish_non_exhaustive() } } @@ -511,7 +517,7 @@ where } } - let mut env = Environment { env, txn_manager: None, _marker: PhantomData }; + let mut env = EnvironmentInner { env, txn_manager: None }; if let Mode::ReadWrite { .. } = self.flags.mode { let (tx, rx) = std::sync::mpsc::sync_channel(0); @@ -556,7 +562,7 @@ where env.txn_manager = Some(tx); } - Ok(env) + Ok(Environment { inner: env, _marker: Default::default() }) } /// Sets the provided options in the environment.