remove some unsafes by using atomics (#2186)

This commit is contained in:
WorldSEnder 2021-12-31 20:36:26 +01:00 committed by GitHub
parent a36ccfc843
commit c46cda1e6f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 13 deletions

View File

@ -3,6 +3,7 @@ use std::{
collections::{HashMap, HashSet},
ops::Deref,
rc::Rc,
sync::atomic::{AtomicBool, Ordering},
};
use wasm_bindgen::{prelude::*, JsCast};
use web_sys::{Element, Event};
@ -19,7 +20,7 @@ thread_local! {
}
/// Bubble events during delegation
static mut BUBBLE_EVENTS: bool = true;
static BUBBLE_EVENTS: AtomicBool = AtomicBool::new(true);
/// Set, if events should bubble up the DOM tree, calling any matching callbacks.
///
@ -32,9 +33,7 @@ static mut BUBBLE_EVENTS: bool = true;
///
/// This function should be called before any component is mounted.
pub fn set_event_bubbling(bubble: bool) {
unsafe {
BUBBLE_EVENTS = bubble;
}
BUBBLE_EVENTS.store(bubble, Ordering::Relaxed);
}
/// The [Listener] trait is an universal implementation of an event listener
@ -502,7 +501,7 @@ impl Registry {
run_handler(&target);
if unsafe { BUBBLE_EVENTS } {
if BUBBLE_EVENTS.load(Ordering::Relaxed) {
let mut el = target;
while !event.cancel_bubble() {
el = match el.parent_element() {

View File

@ -84,7 +84,8 @@ fn multiple_use_state_setters() {
#[wasm_bindgen_test]
fn use_state_eq_works() {
static mut RENDER_COUNT: usize = 0;
use std::sync::atomic::{AtomicUsize, Ordering};
static RENDER_COUNT: AtomicUsize = AtomicUsize::new(0);
struct UseStateFunction {}
@ -92,10 +93,7 @@ fn use_state_eq_works() {
type TProps = ();
fn run(_: &Self::TProps) -> Html {
// No race conditions will be caused since its only used in one place
unsafe {
RENDER_COUNT += 1;
}
RENDER_COUNT.fetch_add(1, Ordering::Relaxed);
let counter = use_state_eq(|| 0);
counter.set(1);
@ -114,7 +112,5 @@ fn use_state_eq_works() {
);
let result = obtain_result();
assert_eq!(result.as_str(), "1");
unsafe {
assert_eq!(RENDER_COUNT, 2);
}
assert_eq!(RENDER_COUNT.load(Ordering::Relaxed), 2);
}