### Install Node.js Dependencies and Build Source: https://neon-rs.dev/docs/hello-world Installs the Node.js dependencies and builds the Neon project. 'npm install' triggers the build process, compiling the Rust code into a native Node.js module (index.node). This step is crucial before running the module. ```bash cd cpu-count npm install ``` -------------------------------- ### Configure Neon NAPI Version Source: https://neon-rs.dev/docs/hello-world Specifies the Node-API version for the Neon project in the Cargo.toml file. Adjusting the 'napi' feature allows targeting a specific Node.js version, ensuring compatibility. The default is the currently installed Node version. ```toml [dependencies.neon] features = ["napi-6"] ``` -------------------------------- ### Run Neon Module in Node.js Console Source: https://neon-rs.dev/docs/hello-world Tests the compiled Neon module by requiring it in the Node.js console and calling the exported 'get' function. This demonstrates that the Rust code is correctly integrated and callable from JavaScript, returning the number of CPUs detected on the system. ```javascript node> const cpuCount = require('.') node> cpuCount.get() 4 ``` -------------------------------- ### Initialize Neon CPU Count Project Source: https://neon-rs.dev/docs/hello-world Initializes a new Neon project for the 'cpu-count' module. This command sets up the basic file structure for a Neon project, which is both a Node package and a Rust crate. It typically creates files like Cargo.toml, README.md, package.json, and src/lib.rs. ```bash npm init neon cpu-count ``` -------------------------------- ### Export Rust Function in Neon Module Source: https://neon-rs.dev/docs/hello-world Exports the Rust function 'get_num_cpus' as a JavaScript function named 'get' within the Neon module. The #[neon::main] attribute marks the 'main' function as the module's entry point. This makes the Rust functionality accessible from Node.js. ```rust use neon::prelude::*; #[neon::main] fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("get", get_num_cpus)?; Ok(()) } ``` -------------------------------- ### Build Neon Module in Release Mode Source: https://neon-rs.dev/docs/hello-world Builds the Neon module with release optimizations. The '--release' flag instructs Cargo to perform optimizations for performance, resulting in a faster executable but a longer compilation time. This is typically done before deploying or for performance testing. ```bash npm run build -- --release ``` -------------------------------- ### Implement Rust Function to Get CPU Count Source: https://neon-rs.dev/docs/hello-world Implements the Rust function 'get_num_cpus' which returns the number of logical CPUs. It uses the 'num_cpus::get()' function and casts the result to a JavaScript number (f64) using cx.number(). The JsResult indicates a successful JavaScript number return or a thrown exception. ```rust use neon::prelude::*; fn get_num_cpus(mut cx: FunctionContext) -> JsResult { Ok(cx.number(num_cpus::get() as f64)) } ``` -------------------------------- ### Add Rust Dependency: num_cpus Source: https://neon-rs.dev/docs/hello-world Adds the 'num_cpus' crate as a dependency to the Rust project. This is declared in the Cargo.toml file, specifying the version range. Cargo will fetch and compile this crate during the build process, making its functionality available to the Neon module. ```toml [dependencies] num_cpus = "1" ``` -------------------------------- ### Clean Rust Build Artifacts Source: https://neon-rs.dev/docs/hello-world Cleans the build artifacts generated by the Rust build tool (Cargo). Running 'cargo clean' removes the contents of the 'target' directory, which includes compiled binaries and intermediate build files, freeing up disk space and ensuring a clean build on the next compilation. ```bash cargo clean ``` -------------------------------- ### Set and Get Indexed Array Properties in Rust (Neon) Source: https://neon-rs.dev/docs/arrays Shows how to set and get indexed properties of a JavaScript array using Neon's `Object::set()` and `Object::get()` methods. This mirrors direct array indexing in JavaScript. ```rust let a = cx.empty_array(); let s = cx.string("hello!"); a.set(&mut cx, 0, s)?; let v = a.get(&mut cx, 1)?; ``` -------------------------------- ### Get JavaScript Object Property in Neon Source: https://neon-rs.dev/docs/objects Accesses a property of a JavaScript object at runtime using the Object trait's get method. This example demonstrates property access that may involve the prototype chain. The method returns a Handle to a JsValue representing the property's value. ```rust // Create an empty object: let obj: Handle = cx.empty_object(); // Get the `toString` property of the object: let prop: Handle = obj.get(&mut cx, "toString")?; ``` -------------------------------- ### Set JavaScript Object Property in Neon Source: https://neon-rs.dev/docs/objects Sets a property of a JavaScript object at runtime using the Object trait's set method. The example shows setting a numeric value to an object property. The method requires a mutable context reference and returns a JsResult for error handling. ```rust let obj = cx.empty_object(); let age = cx.number(35); obj.set(&mut cx, "age", age)?; ``` -------------------------------- ### Handle optional arguments in Rust Source: https://neon-rs.dev/docs/functions Demonstrates handling optional arguments in a Neon function, including conditional logic based on argument presence. ```rust fn create_job(mut cx: FunctionContext) -> JsResult { let company = cx.argument::(0)?; let title = cx.argument::(1)?; let start_year = cx.argument::(2)?; let end_year = cx.argument_opt(3); let obj = cx.empty_object(); obj.set(&mut cx, "company", company)?; obj.set(&mut cx, "title", title)?; obj.set(&mut cx, "startYear", start_year)?; if let Some(end_year) = end_year { obj.set(&mut cx, "endYear", end_year)?; } else { let null = cx.null(); obj.set(&mut cx, "endYear", null)?; } Ok(obj) } ``` -------------------------------- ### Call a Neon function from JavaScript Source: https://neon-rs.dev/docs/functions Demonstrates how to import and call a Neon function in JavaScript, showing the interoperability between Rust and JavaScript. ```javascript const { hello } = require('./index'); console.log(hello()); // prints "hello"! ``` -------------------------------- ### Call JavaScript functions from Rust Source: https://neon-rs.dev/docs/functions Shows how to call JavaScript functions (like parseInt) from Rust, including argument passing and result handling. ```rust // Extract the parseInt function from the global object let parse_int: Handle = cx.global().get(&mut cx, "parseInt")?; // Call parseInt("42") let x: Handle = parse_int .call_with(&mut cx) .arg(cx.string("42")) .apply(&mut cx)?; ``` -------------------------------- ### Create Empty JavaScript Array in Rust (Neon) Source: https://neon-rs.dev/docs/arrays Demonstrates creating an empty JavaScript array using Neon's `Context::empty_array()` method. This is equivalent to initializing an empty array in JavaScript. ```rust let a: Handle = cx.empty_array(); ``` -------------------------------- ### Define a basic Neon function in Rust Source: https://neon-rs.dev/docs/functions Creates a simple Neon function that returns a string. Demonstrates the basic structure of a Neon function with a FunctionContext and JsResult return type. ```rust fn hello(mut cx: FunctionContext) -> JsResult { Ok(cx.string("hello")) } ``` -------------------------------- ### Call JavaScript Constructor with Arguments in Rust Source: https://neon-rs.dev/docs/functions Invokes a JavaScript constructor function (e.g., `URL`) from Rust using Neon. It retrieves the constructor from the global scope and then calls it with specified arguments, returning a new JavaScript object. Dependencies include the Neon crate and a JavaScript runtime context (`cx`). ```rust let url: Handle = cx.global().get(&mut cx, "URL")?; let obj = url .construct_with(&mut cx) .arg(cx.string("https://neon-bindings.com")) .apply(&mut cx)?; ``` -------------------------------- ### Access function arguments in Rust Source: https://neon-rs.dev/docs/functions Illustrates how to access and use arguments passed to a Neon function from JavaScript, including creating and returning a JavaScript object. ```rust fn create_pair(mut cx: FunctionContext) -> JsResult { let x: Handle = cx.argument(0)?; let y: Handle = cx.argument(1)?; let obj = cx.empty_object(); obj.set(&mut cx, "x", x)?; obj.set(&mut cx, "y", y)?; Ok(obj) } ``` -------------------------------- ### Create JavaScript Strings from Rust Source: https://neon-rs.dev/docs/primitive-types Constructs JavaScript String types from references to Rust strings using the Context::string() method. ```Rust let s: Handle = cx.string("foobar"); ``` -------------------------------- ### Export a Neon function from a Rust module Source: https://neon-rs.dev/docs/functions Shows how to export a Rust function to be callable from JavaScript using the ModuleContext. Includes error handling with NeonResult. ```rust #[neon::main] pub fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("hello", hello)?; Ok(()) } ``` -------------------------------- ### Generic Rust to JavaScript conversion method Source: https://neon-rs.dev/docs/objects Makes the conversion method generic to accept any Context implementation, not just FunctionContext. This allows the same method to be used in different contexts like ModuleContext. The generic approach increases code reusability while maintaining memory safety through lifetime parameters. ```rust impl Book { fn to_object<'a>(&self, cx: &mut impl Context<'a>) -> JsResult<'a, JsObject> { // same as before... }} ``` -------------------------------- ### Create JavaScript Numbers from Rust Source: https://neon-rs.dev/docs/primitive-types Constructs JavaScript Number types from Rust numbers compatible with f64. Supports integers and floats. Explicit casting with 'as' may be lossy; consider TryFrom for precision. ```Rust let i: Handle = cx.number(42); let f: Handle = cx.number(3.14); ``` ```Rust let size: usize = std::mem::size_of::(); let n = cx.number(size as f64); ``` -------------------------------- ### Create JavaScript Null from Rust Source: https://neon-rs.dev/docs/primitive-types Constructs a JavaScript null value using the Context::null() method. ```Rust let n: Handle = cx.null(); ``` -------------------------------- ### Create JavaScript Booleans from Rust Source: https://neon-rs.dev/docs/primitive-types Constructs JavaScript Boolean values from Rust booleans using the Context::boolean() method. ```Rust let b: Handle = cx.boolean(true); ``` -------------------------------- ### Check and cast argument types in Rust Source: https://neon-rs.dev/docs/functions Shows type checking and casting of function arguments in Rust, including error handling for incorrect types. ```rust fn create_book(mut cx: FunctionContext) -> JsResult { let title = cx.argument::(0)?; let author = cx.argument::(1)?; let year = cx.argument::(2)?; let obj = cx.empty_object(); obj.set(&mut cx, "title", title)?; obj.set(&mut cx, "author", author)?; obj.set(&mut cx, "year", year)?; Ok(obj) } ``` -------------------------------- ### Export Rust data to JavaScript module Source: https://neon-rs.dev/docs/objects Demonstrates exporting a Rust-converted JavaScript object from a Neon module. Creates a Book struct instance, converts it to a JavaScript object, and exports it as a module value. This is the final step in making Rust data available to JavaScript code. ```rust #[neon::main] pub fn main(mut cx: ModuleContext) -> NeonResult<()> { let book = Book { title: "Chadwick the Crab".to_string(), author: "Priscilla Cummings".to_string(), year: 2009, }; let obj = book.to_object(&mut cx)?; cx.export_value("chadwick", obj)?; Ok(())} ``` -------------------------------- ### Create JavaScript Undefined from Rust Source: https://neon-rs.dev/docs/primitive-types Constructs a JavaScript undefined value using the Context::undefined() method. ```Rust let u: Handle = cx.undefined(); ``` -------------------------------- ### Create new JavaScript Object in Neon Source: https://neon-rs.dev/docs/objects Creates a new empty JavaScript object using Neon's Context trait. This is the basic building block for constructing JavaScript objects in Rust. The method returns a Handle to the newly created JsObject which can be used for further property manipulation. ```rust let obj: Handle = cx.empty_object(); ``` -------------------------------- ### Convert Rust Vec to JavaScript Array in Rust (Neon) Source: https://neon-rs.dev/docs/arrays Provides a function `vec_to_array` that converts a Rust `Vec` into a JavaScript `JsArray` using Neon. It preallocates capacity with `JsArray::new()` and populates it by iterating through the vector. ```rust fn vec_to_array<'a, C: Context<'a>>(vec: &Vec, cx: &mut C) -> JsResult<'a, JsArray> { let a = JsArray::new(cx, vec.len() as u32); for (i, s) in vec.iter().enumerate() { let v = cx.string(s); a.set(cx, i as u32, v)?; } Ok(a) } ``` -------------------------------- ### Convert JavaScript Array to Rust Vec in Rust (Neon) Source: https://neon-rs.dev/docs/arrays Demonstrates the conversion of a JavaScript array (`JsArray`) to a Rust vector (`Vec>`) using Neon's `JsArray::to_vec()` method. ```rust let vec: Vec> = arr.to_vec(&mut cx); ``` -------------------------------- ### Extend JavaScript Array Length in Rust (Neon) Source: https://neon-rs.dev/docs/arrays Illustrates how to extend the length of a JavaScript array by adding a property at the next available index using `JsArray::len()` and `Object::set()`. This corresponds to appending elements in JavaScript. ```rust let len = array.len(&mut cx)?; array.set(&mut cx, len, value)?; ``` -------------------------------- ### Define Rust struct for JavaScript conversion Source: https://neon-rs.dev/docs/objects Defines a Rust struct that can be converted to a JavaScript object. This is a simple Book struct with title, author, and year fields. The struct serves as the basis for demonstrating data conversion between Rust and JavaScript in Neon applications. ```rust struct Book { pub title: String, pub author: String, pub year: u32,} ``` -------------------------------- ### Convert Rust struct to JavaScript Object with lifetime Source: https://neon-rs.dev/docs/objects Implements a method to convert a Rust struct to a JavaScript object using lifetime annotations for memory safety. The method creates an empty JavaScript object and sets properties based on the Rust struct's fields. Lifetime annotation ensures safe interaction with Node.js runtime managed values. ```rust impl Book { fn to_object<'a>(&self, cx: &mut FunctionContext<'a>) -> JsResult<'a, JsObject> { let obj = cx.empty_object(); let title = cx.string(&self.title); obj.set(cx, "title", title)?; let author = cx.string(&self.author); obj.set(cx, "author", author)?; let year = cx.number(self.year); obj.set(cx, "year", year)?; Ok(obj) }} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.