From 59875d5997af91fbb171a336fb0ed7daa3c39b55 Mon Sep 17 00:00:00 2001 From: GrayJack Date: Sat, 20 Apr 2024 15:47:06 -0300 Subject: [PATCH] chore: Add Janet native module example --- Cargo.toml | 5 +++++ examples/janet_native_module.rs | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 examples/janet_native_module.rs diff --git a/Cargo.toml b/Cargo.toml index fcc9bdb28d..368cfe9c4c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -76,3 +76,8 @@ members = ["janetrs_macros", "janetrs_version"] [[example]] name = "hello_world" required-features = ["amalgation"] + +[[example]] +name = "janet_native_module" +crate-type = ["cdylib", "staticlib"] +required-features = ["amalgation"] diff --git a/examples/janet_native_module.rs b/examples/janet_native_module.rs new file mode 100644 index 0000000000..86043d2f0c --- /dev/null +++ b/examples/janet_native_module.rs @@ -0,0 +1,34 @@ +//! For a more complete example to create a Janet package with jpm, check out [this +//! template repository](https://github.com/GrayJack/rust-janet-module-template) + +use janetrs::{declare_janet_mod, janet_fn, jpanic, Janet, JanetTuple, TaggedJanet}; + +/// (template/hello) +/// +/// Rust say hello +#[janet_fn(arity(fix(0)))] +pub fn rust_hello(_args: &mut [Janet]) -> Janet { + println!("Hello from Rust!"); + Janet::nil() +} + +/// (template/chars) +/// +/// If the argument is a buffer or string, return a array or tuple of the chars of the +/// argument, else return nil +#[janet_fn(arity(fix(1)))] +pub fn chars(args: &mut [Janet]) -> Janet { + match args[0].unwrap() { + TaggedJanet::Buffer(b) => b.chars().collect::().into(), + TaggedJanet::String(s) => s.chars().collect::().into(), + _ => jpanic!( + "bad slot #0, expected string|buffer, got {}", + args[0].kind() + ), + } +} + +declare_janet_mod!("template"; + {"hello", rust_hello}, + {"chars", chars}, +);