1 // Copyright (c) 2023 Huawei Device Co., Ltd. 2 // Licensed under the Apache License, Version 2.0 (the "License"); 3 // you may not use this file except in compliance with the License. 4 // You may obtain a copy of the License at 5 // 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 use std::mem::MaybeUninit; 15 use std::sync::Once; 16 17 use crate::sync::watch::{channel, Receiver, Sender}; 18 19 const EVENT_MAX_NUM: usize = 6; 20 21 pub(crate) struct Event { 22 inner: Sender<()>, 23 } 24 25 impl Default for Event { default() -> Self26 fn default() -> Self { 27 let (tx, _) = channel(()); 28 Self { inner: tx } 29 } 30 } 31 32 pub(crate) struct Registry { 33 events: Vec<Event>, 34 } 35 36 impl Default for Registry { default() -> Self37 fn default() -> Self { 38 Self { 39 events: (0..=EVENT_MAX_NUM).map(|_| Event::default()).collect(), 40 } 41 } 42 } 43 44 impl Registry { get_instance() -> &'static Registry45 pub(crate) fn get_instance() -> &'static Registry { 46 static mut REGISTRY: MaybeUninit<Registry> = MaybeUninit::uninit(); 47 static REGISTRY_ONCE: Once = Once::new(); 48 unsafe { 49 REGISTRY_ONCE.call_once(|| { 50 REGISTRY = MaybeUninit::new(Registry::default()); 51 }); 52 &*REGISTRY.as_ptr() 53 } 54 } 55 listen_to_event(&self, event_id: usize) -> Receiver<()>56 pub(crate) fn listen_to_event(&self, event_id: usize) -> Receiver<()> { 57 // Invalid signal kinds have been forbidden, the scope of signal kinds has been 58 // protected. 59 self.events 60 .get(event_id) 61 .unwrap_or_else(|| panic!("invalid event_id: {}", event_id)) 62 .inner 63 .subscribe() 64 } 65 broadcast(&self, event_id: usize) -> i3266 pub(crate) fn broadcast(&self, event_id: usize) -> i32 { 67 if let Some(event) = self.events.get(event_id) { 68 if event.inner.send(()).is_ok() { 69 return 1; 70 } 71 } 72 0 73 } 74 } 75