Skip to content

Commit

Permalink
remove some unsafes by using atomics
Browse files Browse the repository at this point in the history
  • Loading branch information
WorldSEnder committed Dec 29, 2021
1 parent b886412 commit 1a11593
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 13 deletions.
9 changes: 4 additions & 5 deletions packages/yew/src/virtual_dom/listeners.rs
Expand Up @@ -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};
Expand All @@ -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.
///
Expand All @@ -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
Expand Down Expand Up @@ -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() {
Expand Down
12 changes: 4 additions & 8 deletions packages/yew/tests/use_state.rs
Expand Up @@ -84,18 +84,16 @@ 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 {}

impl FunctionProvider for UseStateFunction {
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);

Expand All @@ -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);
}

0 comments on commit 1a11593

Please sign in to comment.