referrerpolicy=no-referrer-when-downgrade

sc_utils/notification/
registry.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use std::collections::HashSet;
19
20use crate::{
21	id_sequence::SeqID,
22	pubsub::{Dispatch, Subscribe, Unsubscribe},
23};
24
25/// The shared structure to keep track on subscribers.
26#[derive(Debug, Default)]
27pub(super) struct Registry {
28	pub(super) subscribers: HashSet<SeqID>,
29}
30
31impl Subscribe<()> for Registry {
32	fn subscribe(&mut self, _subs_key: (), subs_id: SeqID) {
33		self.subscribers.insert(subs_id);
34	}
35}
36impl Unsubscribe for Registry {
37	fn unsubscribe(&mut self, subs_id: SeqID) {
38		self.subscribers.remove(&subs_id);
39	}
40}
41
42impl<MakePayload, Payload, Error> Dispatch<MakePayload> for Registry
43where
44	MakePayload: FnOnce() -> Result<Payload, Error>,
45	Payload: Clone,
46{
47	type Item = Payload;
48	type Ret = Result<(), Error>;
49
50	fn dispatch<F>(&mut self, make_payload: MakePayload, mut dispatch: F) -> Self::Ret
51	where
52		F: FnMut(&SeqID, Self::Item),
53	{
54		if !self.subscribers.is_empty() {
55			let payload = make_payload()?;
56			for subs_id in &self.subscribers {
57				dispatch(subs_id, payload.clone());
58			}
59		}
60		Ok(())
61	}
62}