Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove some unsafes by using atomics #2186

Merged
merged 1 commit into from Dec 31, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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);
}