Решение на упр.09 задача 1 от Константин Илиев

Обратно към всички решения

Към профила на Константин Илиев

Резултати

  • 5 точки от тестове
  • 0 бонус точки
  • 5 точки общо
  • 5 успешни тест(а)
  • 0 неуспешни тест(а)

Код

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Id(usize);
type Callback<S> = Box<dyn FnMut(&mut S) + Send + 'static>;
struct Inner<S> {
handlers: HashMap<String, Vec<(Id, Callback<S>)>>,
next_id: usize,
}
pub struct EventDispatcher<S> {
inner: Arc<Mutex<Inner<S>>>,
}
impl<S> EventDispatcher<S> {
pub fn new() -> Self {
EventDispatcher {
inner: Arc::new(Mutex::new(Inner {
handlers: HashMap::new(),
next_id: 0,
})),
}
}
pub fn on(
&self,
event: &str,
callback: Box<dyn FnMut(&mut S) + Send + 'static>,
) -> Id {
let mut inner = self.inner.lock().unwrap();
let id = Id(inner.next_id);
inner.next_id += 1;
inner
.handlers
.entry(event.to_string())
.or_default()
.push((id, callback));
id
}
pub fn off(
&self,
id: Id,
) -> Option<Box<dyn FnMut(&mut S) + Send + 'static>> {
let mut inner = self.inner.lock().unwrap();
for callbacks in inner.handlers.values_mut() {
if let Some(pos) = callbacks.iter().position(|(handler_id, _)| *handler_id == id) {
return Some(callbacks.remove(pos).1);
}
}
None
}
pub fn emit(&self, event: &str, state: &mut S) {
let mut callbacks = {
let mut inner = self.inner.lock().unwrap();
match inner.handlers.remove(event) {
Some(cbs) => cbs,
None => return,
}
};
for (_, callback) in &mut callbacks {
callback(state);
}
let mut inner = self.inner.lock().unwrap();
match inner.handlers.remove(event) {
Some(mut new_callbacks) => {
callbacks.append(&mut new_callbacks);
inner.handlers.insert(event.to_string(), callbacks);
}
None => {
inner.handlers.insert(event.to_string(), callbacks);
}
}
}
}
impl<S> Clone for EventDispatcher<S> {
fn clone(&self) -> Self {
EventDispatcher {
inner: Arc::clone(&self.inner),
}
}
}

Лог от изпълнението

Updating crates.io index
     Locking 17 packages to latest compatible versions
   Compiling proc-macro2 v1.0.103
   Compiling unicode-ident v1.0.22
   Compiling quote v1.0.42
   Compiling futures-core v0.3.31
   Compiling futures-sink v0.3.31
   Compiling futures-channel v0.3.31
   Compiling memchr v2.7.6
   Compiling syn v2.0.111
   Compiling futures-io v0.3.31
   Compiling pin-utils v0.1.0
   Compiling futures-task v0.3.31
   Compiling pin-project-lite v0.2.16
   Compiling slab v0.4.11
   Compiling solution v0.1.0 (/tmp/d20251211-1757769-1vdwy4d/solution)
   Compiling futures-macro v0.3.31
   Compiling futures-util v0.3.31
   Compiling futures-executor v0.3.31
   Compiling futures v0.3.31
    Finished `test` profile [unoptimized + debuginfo] target(s) in 9.17s
     Running tests/solution_test.rs (target/debug/deps/solution_test-ee0783488e12dce9)

running 5 tests
test solution_test::test_basic_run1 ... ok
test solution_test::test_basic_run2 ... ok
test solution_test::test_multithreaded_run1 ... ok
test solution_test::test_multithreaded_run2 ... ok
test solution_test::test_reentrant_run ... ok

test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

История (1 версия и 0 коментара)

Константин качи първо решение на 10.12.2025 22:01 (преди около 2 месеца)