quad_storage_sys/
lib.rs

1//! Provides access to the browser's local storage.
2//!
3//! Add file [`quad-storage/js/quad-storage.js`](https://github.com/optozorax/quad-storage/blob/master/js/quad-storage.js) to your project.
4//!
5//! Add file [`sapp-jsutils/js/sapp_jsutils.js`](https://github.com/not-fl3/sapp-jsutils/blob/master/js/sapp_jsutils.js) file to your project.
6//!
7//! Add this lines after loading of `gl.js` and before loading of your wasm in your `index.html`:
8//! ```html
9//! <script src="sapp_jsutils.js"></script>
10//! <script src="quad-storage.js"></script>
11//! ```
12//! Done! Now you can use this crate.
13
14use sapp_jsutils::{JsObject, JsObjectWeak};
15
16#[no_mangle]
17extern "C" fn quad_storage_crate_version() -> u32 {
18    let major = env!("CARGO_PKG_VERSION_MAJOR").parse::<u32>().unwrap();
19    let minor = env!("CARGO_PKG_VERSION_MINOR").parse::<u32>().unwrap();
20    let patch = env!("CARGO_PKG_VERSION_PATCH").parse::<u32>().unwrap();
21
22    (major << 24) + (minor << 16) + patch
23}
24
25extern "C" {
26    fn quad_storage_length() -> u32;
27    fn quad_storage_has_key(i: u32) -> u32;
28    fn quad_storage_key(i: u32) -> JsObject;
29    fn quad_storage_has_value(key: JsObjectWeak) -> u32;
30    fn quad_storage_get(key: JsObjectWeak) -> JsObject;
31    fn quad_storage_set(key: JsObjectWeak, value: JsObjectWeak);
32    fn quad_storage_remove(key: JsObjectWeak);
33    fn quad_storage_clear();
34}
35
36fn js_to_option_string(object: JsObject, has: u32) -> Option<String> {
37    if has == 1 {
38        let mut result = String::new();
39        object.to_string(&mut result);
40        Some(result)
41    } else {
42        None
43    }
44}
45
46/// Number of elements in the local storage.
47pub fn len() -> usize {
48    unsafe { quad_storage_length() as usize }
49}
50
51/// Get key by its position
52pub fn key(pos: usize) -> Option<String> {
53    js_to_option_string(unsafe { quad_storage_key(pos as u32) }, unsafe {
54        quad_storage_has_key(pos as u32)
55    })
56}
57
58/// Get entry by key, if any.
59pub fn get(key: &str) -> Option<String> {
60    let object = JsObject::string(key);
61    let weak_object = object.weak();
62    let result = js_to_option_string(unsafe { quad_storage_get(weak_object) }, unsafe {
63        quad_storage_has_value(weak_object)
64    });
65    drop(object);
66    result
67}
68
69pub fn set(key: &str, value: &str) {
70    unsafe {
71        quad_storage_set(JsObject::string(key).weak(), JsObject::string(value).weak());
72    }
73}
74
75/// Remove entry from the local storage.
76pub fn remove(key: &str) {
77    unsafe {
78        quad_storage_remove(JsObject::string(key).weak());
79    }
80}
81
82/// Remove all entries from local storage.
83pub fn clear() {
84    unsafe {
85        quad_storage_clear();
86    }
87}