vertigo/dev/
callback_id.rs

1use std::{
2    rc::Rc,
3    sync::atomic::{AtomicU64, Ordering},
4};
5use vertigo_macro::store;
6
7use crate::{JsJson, JsJsonContext, JsJsonDeserialize, JsJsonNumber, JsJsonSerialize};
8
9#[derive(PartialEq, Eq, Hash, Clone, Debug, Copy)]
10pub struct CallbackId(u64);
11
12#[store]
13pub fn get_counter() -> Rc<AtomicU64> {
14    Rc::new(AtomicU64::new(1))
15}
16
17impl CallbackId {
18    #[allow(clippy::new_without_default)]
19    pub fn new() -> CallbackId {
20        CallbackId(get_counter().fetch_add(1, Ordering::Relaxed))
21    }
22
23    pub fn as_u64(&self) -> u64 {
24        self.0
25    }
26
27    pub fn from_u64(id: u64) -> Self {
28        Self(id)
29    }
30}
31
32impl JsJsonSerialize for CallbackId {
33    fn to_json(self) -> JsJson {
34        JsJson::Number(JsJsonNumber(self.0 as f64))
35    }
36}
37
38impl JsJsonDeserialize for CallbackId {
39    fn from_json(_context: JsJsonContext, json: JsJson) -> Result<Self, JsJsonContext> {
40        if let JsJson::Number(JsJsonNumber(value)) = json {
41            return Ok(CallbackId::from_u64(value as u64));
42        }
43
44        Err(JsJsonContext::new(format!(
45            "Expected Number, received={}",
46            json.typename()
47        )))
48    }
49}