summaryrefslogtreecommitdiff
path: root/openssl/src/util.rs
diff options
context:
space:
mode:
authorStefan Bühler <stbuehler@web.de>2020-09-27 21:25:04 +0200
committerStefan Bühler <stbuehler@web.de>2020-09-27 21:32:24 +0200
commitb2caf477fdaa68887d9343e6d119d9312f40204c (patch)
treebdc31ef3f053726d44c0f9ff0fed8c9f28136437 /openssl/src/util.rs
parent32b1736368a8359baa098f7484f06a1a29fa396b (diff)
downloadrust-openssl-b2caf477fdaa68887d9343e6d119d9312f40204c.zip
Add and use ForeignTypeRefExt::from_const_ptr
1. `X::from_ptr(p as *mut _)` is dangerous, as it not only casts `*const X::CType` to `*mut X::CType`, but any `*const U` to `*mut X::CType`. Add and use a extension trait to provide `from_const_ptr`. 2. Often null pointers are returned as `Option<...>`; refactor the checks into `from_const_ptr_opt` for refs and `from_ptr_opt` for owned data. 3. `assert!(!p.is_null())` is easy to mistype as `assert!(p.is_null());`. Use `X::from(_const)?ptr_opt(...).expect("...")` instead.
Diffstat (limited to 'openssl/src/util.rs')
-rw-r--r--openssl/src/util.rs27
1 files changed, 27 insertions, 0 deletions
diff --git a/openssl/src/util.rs b/openssl/src/util.rs
index cda43755..c0c335a0 100644
--- a/openssl/src/util.rs
+++ b/openssl/src/util.rs
@@ -1,3 +1,4 @@
+use foreign_types::{ForeignType, ForeignTypeRef};
use libc::{c_char, c_int, c_void};
use std::any::Any;
use std::panic::{self, AssertUnwindSafe};
@@ -65,3 +66,29 @@ where
}
}
}
+
+pub trait ForeignTypeExt: ForeignType {
+ unsafe fn from_ptr_opt(ptr: *mut Self::CType) -> Option<Self> {
+ if ptr.is_null() {
+ None
+ } else {
+ Some(Self::from_ptr(ptr))
+ }
+ }
+}
+impl<FT: ForeignType> ForeignTypeExt for FT {}
+
+pub trait ForeignTypeRefExt: ForeignTypeRef {
+ unsafe fn from_const_ptr<'a>(ptr: *const Self::CType) -> &'a Self {
+ Self::from_ptr(ptr as *mut Self::CType)
+ }
+
+ unsafe fn from_const_ptr_opt<'a>(ptr: *const Self::CType) -> Option<&'a Self> {
+ if ptr.is_null() {
+ None
+ } else {
+ Some(Self::from_const_ptr(ptr as *mut Self::CType))
+ }
+ }
+}
+impl<FT: ForeignTypeRef> ForeignTypeRefExt for FT {}