Решение на упр.09 задача 1 от Ивайло Иванов
Резултати
- 4 точки от тестове
- 0 бонус точки
- 4 точки общо
- 4 успешни тест(а)
- 1 неуспешни тест(а)
Код
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
pub struct Id {
id: u32,
}
struct Inner<S> {
next_id: u32,
listeners: HashMap<String, HashMap<u32, Box<dyn FnMut(&mut S) + Send>>>,
}
pub struct EventDispatcher<S> {
inner: Arc<Mutex<Inner<S>>>,
}
impl<S> EventDispatcher<S> {
pub fn new() -> Self {
EventDispatcher {
inner: Arc::new(Mutex::new(Inner {
next_id: 0,
listeners: HashMap::new(),
})),
}
}
pub fn on(
&self,
event: &str,
callback: Box<dyn FnMut(&mut S) + Send>,
) -> Id {
let mut inner = self.inner.lock().unwrap();
let id = inner.next_id;
inner.next_id += 1;
inner.listeners
.entry(event.to_string())
.or_insert_with(HashMap::new)
.insert(id, callback);
Id { id }
}
pub fn off(
&self,
id: Id,
) -> Option<Box<dyn FnMut(&mut S) + Send>> {
let mut inner = self.inner.lock().unwrap();
for listeners in inner.listeners.values_mut() {
if let Some(callback) = listeners.remove(&id.id) {
return Some(callback);
}
}
None
}
pub fn emit(&self, event: &str, state: &mut S) {
let mut inner = self.inner.lock().unwrap();
if let Some(listeners) = inner.listeners.get_mut(event) {
for callback in listeners.values_mut() {
callback(state);
}
}
}
}
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 quote v1.0.42
Compiling unicode-ident v1.0.22
Compiling futures-sink v0.3.31
Compiling futures-core v0.3.31
Compiling futures-channel v0.3.31
Compiling futures-task v0.3.31
Compiling pin-utils v0.1.0
Compiling syn v2.0.111
Compiling futures-io v0.3.31
Compiling memchr v2.7.6
Compiling pin-project-lite v0.2.16
Compiling slab v0.4.11
Compiling solution v0.1.0 (/tmp/d20251211-1757769-1qicbs0/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.03s
Running tests/solution_test.rs (target/debug/deps/solution_test-ee0783488e12dce9)
running 5 tests
test solution_test::test_basic_run2 ... ok
test solution_test::test_basic_run1 ... ok
test solution_test::test_multithreaded_run1 ... ok
test solution_test::test_multithreaded_run2 ... ok
test solution_test::test_reentrant_run ... FAILED
failures:
---- solution_test::test_reentrant_run stdout ----
thread 'solution_test::test_reentrant_run' panicked at tests/solution_test.rs:128:60:
test timeout
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
solution_test::test_reentrant_run
test result: FAILED. 4 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.00s
error: test failed, to rerun pass `--test solution_test`
