From 8f898a1f5461a7626e0854914125eeb9f97516b4 Mon Sep 17 00:00:00 2001 From: zephyr Date: Sun, 10 Apr 2022 23:12:18 +0900 Subject: [PATCH] add ref wrapper --- kaminari/Cargo.toml | 2 +- kaminari/src/lib.rs | 1 + kaminari/src/trick.rs | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 kaminari/src/trick.rs diff --git a/kaminari/Cargo.toml b/kaminari/Cargo.toml index 0643966..3487b62 100644 --- a/kaminari/Cargo.toml +++ b/kaminari/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kaminari" -version = "0.4.0" +version = "0.4.1" edition = "2021" authors = ["zephyr "] keywords = ["lightws", "network"] diff --git a/kaminari/src/lib.rs b/kaminari/src/lib.rs index cd34a5e..f402ab6 100644 --- a/kaminari/src/lib.rs +++ b/kaminari/src/lib.rs @@ -30,3 +30,4 @@ pub mod nop; pub mod tls; pub mod mix; pub mod opt; +pub mod trick; diff --git a/kaminari/src/trick.rs b/kaminari/src/trick.rs new file mode 100644 index 0000000..1adf45a --- /dev/null +++ b/kaminari/src/trick.rs @@ -0,0 +1,35 @@ +use core::ops::Deref; + +// Safety: +// pointer is not null once inited(comes from an immutable ref) +// pointee memory is always valid during the eventloop +pub struct Ref(*const T); + +unsafe impl Send for Ref {} +unsafe impl Sync for Ref {} + +impl Copy for Ref {} + +impl Clone for Ref { + fn clone(&self) -> Self { *self } +} + +impl Deref for Ref { + type Target = T; + + #[inline] + fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } +} + +impl AsRef for Ref { + #[inline] + fn as_ref(&self) -> &T { unsafe { &*self.0 } } +} + +impl From<&T> for Ref { + fn from(x: &T) -> Self { Ref(x as *const _) } +} + +impl Ref { + pub const fn new(x: &T) -> Self { Self(x as *const _) } +}