Lukas
Lukas5w ago

Instancing Rust Structs in JS and maintaining a list of them in Rust

I am struggling to create an extensions for deno_core that would allow me to create Rust Struct instances via JavaScript, but maintain those instances in Rust. What I mean is this: I have a Rust Struct called Rect that I use as a Resource in deno. For the sake of brevity I will reduce its fields in this example to two coordinates, top and left:
pub struct Rect {
pub top: Cell<u32>,
pub left: Cell<u32>,
}

impl Resource for Rect {
fn name(&self) -> Cow<str> {
Cow::Borrowed("rect")
}
}

impl GarbageCollected for Rect {}

#[op2]
impl Rect {
#[fast]
#[getter]
pub fn top(&self) -> u32 {
self.top.get()
}

#[fast]
#[getter]
pub fn left(&self) -> u32 {
self.left.get()
}
#[fast]
pub fn top(&self, top: u32) {
self.top.set(top);

}

#[fast]
pub fn sleft(&self, left: u32) {
self.left.set(left);
}
}
pub struct Rect {
pub top: Cell<u32>,
pub left: Cell<u32>,
}

impl Resource for Rect {
fn name(&self) -> Cow<str> {
Cow::Borrowed("rect")
}
}

impl GarbageCollected for Rect {}

#[op2]
impl Rect {
#[fast]
#[getter]
pub fn top(&self) -> u32 {
self.top.get()
}

#[fast]
#[getter]
pub fn left(&self) -> u32 {
self.left.get()
}
#[fast]
pub fn top(&self, top: u32) {
self.top.set(top);

}

#[fast]
pub fn sleft(&self, left: u32) {
self.left.set(left);
}
}
Now I have an op to create a rect and add it to a Vec, a List of Rects in Rust, for me to keep score and do stuff with those rects.
let rects: Vec<Arc<Mutex<Rect>>>

#[op2]
#[cppgc]
fn op_create_rect(
state: &mut OpState,
top: u32,
left: u32,
) -> Result<Arc<Mutex<Rect>>, JsErrorBox> {
let rect = Arc::new(Mutex::new(Rect {
top: Cell::new(top),
left: Cell::new(left),
}));

rects.push(rect.clone());

Ok(rect.clone())
}
let rects: Vec<Arc<Mutex<Rect>>>

#[op2]
#[cppgc]
fn op_create_rect(
state: &mut OpState,
top: u32,
left: u32,
) -> Result<Arc<Mutex<Rect>>, JsErrorBox> {
let rect = Arc::new(Mutex::new(Rect {
top: Cell::new(top),
left: Cell::new(left),
}));

rects.push(rect.clone());

Ok(rect.clone())
}
Now that does not really really work. op2 is missing GarbageCollected on the Arc Mutex, but I also (think I) need that because I will reference and mutate it in JS and also want to reference it in Rust. My goal is to have that Struct as object in JavaScript and be able to create and mutate it there while also be able to use all instances in Rust at any given time. Any help on how to do that is very appreaciated.
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?