Решение на упр.09 задача 1 от Владимир Великов

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

Към профила на Владимир Великов

Резултати

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

Код

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Id {
id: usize,
event: String,
}
type Callback<S> = Box<dyn FnMut(&mut S) + Send + 'static>;
struct Listener<S> {
id: usize,
callback: Callback<S>,
}
struct Inner<S> {
listeners: HashMap<String, Arc<Mutex<Vec<Listener<S>>>>>,
next_id: usize,
}
struct EventDispatcher<S> {
inner: Arc<Mutex<Inner<S>>>,
}
impl<S> EventDispatcher<S> {
fn new() -> Self {
EventDispatcher {
inner: Arc::new(Mutex::new(Inner {
listeners: HashMap::new(),
next_id: 0,
})),
}
}
fn on(&self, event: &str, callback: Box<dyn FnMut(&mut S) + Send + 'static>) -> Id {
let (id_num, bucket) = {
let mut guard = self.inner.lock().unwrap();
let id = guard.next_id;
guard.next_id += 1;
let bucket = guard
.listeners
.entry(event.to_string())
.or_insert_with(|| Arc::new(Mutex::new(Vec::new())))
.clone();
(id, bucket)
};
let mut listeners = bucket.lock().unwrap();
listeners.push(Listener {
id: id_num,
callback,
});
Id {
id: id_num,
event: event.to_string(),
}
}
fn off(&self, id: Id) -> Option<Box<dyn FnMut(&mut S) + Send + 'static>> {
let bucket = {
let guard = self.inner.lock().unwrap();
guard.listeners.get(&id.event).cloned()
};
if let Some(bucket) = bucket {
let mut listeners = bucket.lock().unwrap();
if let Some(pos) = listeners.iter().position(|l| l.id == id.id) {
return Some(listeners.remove(pos).callback);
}
}
None
}
fn emit(&self, event: &str, state: &mut S) {
let bucket = {
let guard = self.inner.lock().unwrap();
guard.listeners.get(event).cloned()
};
if let Some(bucket) = bucket {
let mut listeners = bucket.lock().unwrap();
for listener in listeners.iter_mut() {
(listener.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 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 pin-utils v0.1.0
   Compiling futures-io v0.3.31
   Compiling pin-project-lite v0.2.16
   Compiling slab v0.4.11
   Compiling futures-task v0.3.31
   Compiling solution v0.1.0 (/tmp/d20251211-1757769-zwj7w2/solution)
warning: struct `Id` is never constructed
 --> src/lib.rs:5:8
  |
5 | struct Id {
  |        ^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: type alias `Callback` is never used
  --> src/lib.rs:10:6
   |
10 | type Callback<S> = Box<dyn FnMut(&mut S) + Send + 'static>;
   |      ^^^^^^^^

warning: struct `Listener` is never constructed
  --> src/lib.rs:12:8
   |
12 | struct Listener<S> {
   |        ^^^^^^^^

warning: struct `Inner` is never constructed
  --> src/lib.rs:17:8
   |
17 | struct Inner<S> {
   |        ^^^^^

warning: struct `EventDispatcher` is never constructed
  --> src/lib.rs:22:8
   |
22 | struct EventDispatcher<S> {
   |        ^^^^^^^^^^^^^^^

warning: associated items `new`, `on`, `off`, and `emit` are never used
  --> src/lib.rs:27:8
   |
26 | impl<S> EventDispatcher<S> {
   | -------------------------- associated items in this implementation
27 |     fn new() -> Self {
   |        ^^^
...
36 |     fn on(&self, event: &str, callback: Box<dyn FnMut(&mut S) + Send + 'static>) -> Id {
   |        ^^
...
64 |     fn off(&self, id: Id) -> Option<Box<dyn FnMut(&mut S) + Send + 'static>> {
   |        ^^^
...
81 |     fn emit(&self, event: &str, state: &mut S) {
   |        ^^^^

warning: `solution` (lib) generated 6 warnings
   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.51s
     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 ... ok

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

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

Владимир качи първо решение на 09.12.2025 22:36 (преди около 2 месеца)