Add Arbiter::get_value() helper method (#541)

This commit is contained in:
Nikolay Kim 2025-03-26 14:40:05 +01:00 committed by GitHub
parent 0d3f1293c9
commit eb4ec4b3e1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 28 additions and 4 deletions

View file

@ -40,7 +40,7 @@ ntex-util = "2.5"
ntex-tokio = { version = "0.5.3", optional = true }
ntex-compio = { version = "0.2.4", optional = true }
ntex-neon = { version = "0.1.10", optional = true }
ntex-neon = { version = "0.1.11", optional = true }
bitflags = { workspace = true }
cfg-if = { workspace = true }

View file

@ -1,5 +1,9 @@
# Changes
## [0.4.29] - 2025-03-26
* Add Arbiter::get_value() helper method
## [0.4.27] - 2025-03-14
* Add srbiters pings ttl

View file

@ -1,6 +1,6 @@
[package]
name = "ntex-rt"
version = "0.4.28"
version = "0.4.29"
authors = ["ntex contributors <team@ntex.rs>"]
description = "ntex runtime"
keywords = ["network", "framework", "async", "futures"]
@ -32,8 +32,8 @@ neon = ["ntex-neon"]
[dependencies]
async-channel = "2"
futures-timer = "3.0"
log = "0.4"
oneshot = "0.1"
log = "0.4"
compio-driver = { version = "0.6", optional = true }
compio-runtime = { version = "0.6", optional = true }
@ -42,7 +42,7 @@ tok-io = { version = "1", package = "tokio", default-features = false, features
"net",
], optional = true }
ntex-neon = { version = "0.1.1", optional = true }
ntex-neon = { version = "0.1.11", optional = true }
[dev-dependencies]
env_logger = "0.11"

View file

@ -286,6 +286,25 @@ impl Arbiter {
})
}
/// Get a type previously inserted to this runtime or create new one.
pub fn get_value<T, F>(f: F) -> T
where
T: Clone + 'static,
F: FnOnce() -> T,
{
STORAGE.with(move |cell| {
let mut st = cell.borrow_mut();
if let Some(boxed) = st.get(&TypeId::of::<T>()) {
if let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>() {
return val.clone();
}
}
let val = f();
st.insert(TypeId::of::<T>(), Box::new(val.clone()));
val
})
}
/// Wait for the event loop to stop by joining the underlying thread (if have Some).
pub fn join(&mut self) -> thread::Result<()> {
if let Some(thread_handle) = self.thread_handle.take() {
@ -355,6 +374,7 @@ mod tests {
assert!(Arbiter::get_item::<&'static str, _, _>(|s| *s == "test"));
assert!(Arbiter::get_mut_item::<&'static str, _, _>(|s| *s == "test"));
assert!(Arbiter::contains_item::<&'static str>());
assert!(Arbiter::get_value(|| 64u64) == 64);
assert!(format!("{:?}", Arbiter::current()).contains("Arbiter"));
}
}