1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
use std::cell::RefCell;
use std::ops::Deref;
use std::rc::Rc;
use std::task::Waker;
use cfg_if::cfg_if;
use wasm_bindgen::prelude::*;
#[cfg(test)]
pub(crate) async fn open_any_db() -> (crate::IdbDatabase, String) {
use crate::prelude::*;
let db = uuid::Uuid::new_v4().to_string();
let store = uuid::Uuid::new_v4().to_string();
let mut req = crate::IdbDatabase::open(&db).expect("db open");
let store_cloned = store.clone();
req.set_on_upgrade_needed(Some(move |evt: &IdbVersionChangeEvent| {
evt.db().create_object_store(&store_cloned)?;
Ok(())
}));
(req.into_future().await.expect("fut"), store)
}
#[inline]
pub(crate) fn safe_unwrap_option<T>(option: Option<T>) -> T {
cfg_if! {
if #[cfg(feature = "nightly")] {
unsafe { option.unwrap_unchecked() }
} else {
option.unwrap()
}
}
}
#[inline]
pub(crate) fn safe_unwrap_result<O, E: std::fmt::Debug>(result: Result<O, E>) -> O {
cfg_if! {
if #[cfg(feature = "nightly")] {
unsafe { result.unwrap_unchecked() }
} else {
result.unwrap()
}
}
}
pub(crate) fn wake(waker: &RefCell<Option<Waker>>) {
if let Some(w) = waker.borrow().deref() {
w.wake_by_ref();
}
}
#[inline]
pub(crate) fn optional_jsvalue_undefined(val: JsValue) -> Option<JsValue> {
if val.is_undefined() {
None
} else {
Some(val)
}
}
#[inline]
pub(crate) fn create_lazy_ref_cell<T>() -> Rc<RefCell<Option<T>>> {
Rc::new(RefCell::new(None))
}
pub(crate) fn arrayify_slice(slice: &[&str]) -> js_sys::Array {
slice.iter().map(jsvalue_from).collect()
}
#[inline]
fn jsvalue_from(v: &&str) -> JsValue {
JsValue::from_str(v)
}
#[cfg(test)]
pub mod test {
use super::*;
pub mod arrayify_slice {
use js_sys::Array;
test_mod_init!();
fn assert_array_eq(arr: &Array, slice: &[&str]) {
let arr_length = arr.length();
assert_eq!(arr.length() as usize, slice.len(), "Lengths");
for i in 0..arr_length {
assert_eq!(
arr.get(i),
JsValue::from_str(slice[i as usize]),
"Item at idx {}",
i
);
}
}
test_case!(empty_slice => {
assert_array_eq(&Array::new(), &[]);
});
test_case!(non_empty_slice => {
assert_array_eq(&Array::of2(&"foo".into(), &"bar".into()), &["foo", "bar"]);
});
}
pub mod optional_jsvalue_undefined {
test_mod_init!();
macro_rules! run_case {
($name: ident, $val: expr, $expect: literal) => {
test_case!($name => {
let val = optional_jsvalue_undefined($val).is_none();
assert_eq!(val, $expect);
});
};
}
run_case!(undefined, JsValue::undefined(), true);
run_case!(null, JsValue::null(), false);
run_case!(string, JsValue::from_str("foo"), false);
run_case!(num_0, JsValue::from(0), false);
run_case!(bool_false, JsValue::from(false), false);
}
}