Skip to content

Instantly share code, notes, and snippets.

@dherman
Last active December 20, 2017 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dherman/d1d6d62e4e44ffbee1e1eebd51b53f06 to your computer and use it in GitHub Desktop.
Save dherman/d1d6d62e4e44ffbee1e1eebd51b53f06 to your computer and use it in GitHub Desktop.
classes 2.0
#[macro_use]
extern crate neon;
struct GreeterInternals {
greeting: String,
separator: String
};
classic_module! {
export class Greeter {
// the type of native instance data owned by the Greeter instance
self: GreeterInternals;
// initializes the native instance data
new(greeting: Option<String>, separator: Option<String>) {
Ok(GreeterInternals {
greeting: greeting.or_else(|| String::from("hello")),
separator: separator.or_else(|| String::from(", "))
})
}
// methods can take self directly to implicitly and
// conveniently freeze the VM and access instance internals
method greeting(&self) -> String {
Ok(self.greeting.clone())
}
// similarly they can get mutable access
method setGreeting(&mut self, greeting: String) {
self.greeting = greeting;
Ok(())
}
method separator(&self) -> String {
Ok(self.separator.clone())
}
method setSeparator(&mut self, separator: String) {
self.separator = separator;
Ok(())
}
method setHello(&self, to: String) -> String {
Ok(format!("{}{}{}", self.greeting, self.separator, to))
}
// methods that need to allocate on the JS
// heap can take a VM instead and manipulate
// it more directly
method both(mut vm) -> Handle<JsArray> {
let (g, s) = {
let this = vm.this();
let vm = vm.lock();
let internals = vm.inspect(this);
(internals.greeting.clone(),
internals.separator.clone())
};
let mut a = vm.array()?;
a.push(vm.string(g)?)?;
a.push(vm.string(s)?)?;
Ok(a)
}
}
export function add1(x: i32) -> i32 {
Ok(x + 1)
}
export function array(mut vm) -> Handle<JsArray> {
let mut a = vm.array()?;
let constructor = Greeter::constructor(&mut vm)?;
a.push(constructor)?;
Ok(a)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment