🔤 字符串处理
rust
use neon::prelude::*;
#[neon::export]
fn reverse_string(s: String) -> String {
s.chars().rev().collect()
}
#[neon::export]
fn count_words(s: String) -> usize {
s.split_whitespace().count()
}
🔢 数学计算
rust
use neon::prelude::*;
#[neon::export]
fn fibonacci(n: u32) -> u64 {
if n <= 1 {
return n as u64;
}
let mut a = 0u64;
let mut b = 1u64;
for _ in 2..=n {
let temp = a + b;
a = b;
b = temp;
}
b
}
#[neon::export]
fn is_prime(n: u64) -> bool {
if n < 2 {
return false;
}
for i in 2..=(n as f64).sqrt() as u64 {
if n % i == 0 {
return false;
}
}
true
}
📦 JSON 解析
rust
use neon::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Serialize, Deserialize)]
struct User {
name: String,
age: u32,
}
#[neon::export]
fn parse_user(json: String) -> Result {
serde_json::from_str(&json).map_err(|e| e.to_string())
}
#[neon::export(json)]
async fn fetch_json(url: String) -> Result {
let response = reqwest::get(&url).await.map_err(|e| e.to_string())?;
let json = response.json().await.map_err(|e| e.to_string())?;
Ok(json)
}
🔒 加密示例
rust
use neon::prelude::*;
use sha2::{Sha256, Digest};
#[neon::export]
fn sha256_hash(input: String) -> String {
let mut hasher = Sha256::new();
hasher.update(input.as_bytes());
let result = hasher.finalize();
format!("{:x}", result)
}
#[neon::export]
fn base64_encode(input: String) -> String {
use base64::{Engine as _, engine::general_purpose};
general_purpose::STANDARD.encode(input.as_bytes())
}
#[neon::export]
fn base64_decode(input: String) -> Result {
use base64::{Engine as _, engine::general_purpose};
let bytes = general_purpose::STANDARD.decode(&input).map_err(|e| e.to_string())?;
String::from_utf8(bytes).map_err(|e| e.to_string())
}
📁 文件处理
rust
use neon::prelude::*;
use std::fs;
use std::path::Path;
#[neon::export]
fn read_file(path: String) -> Result {
fs::read_to_string(&path).map_err(|e| e.to_string())
}
#[neon::export]
fn write_file(path: String, content: String) -> Result<(), String> {
fs::write(&path, &content).map_err(|e| e.to_string())
}
#[neon::export]
fn file_exists(path: String) -> bool {
Path::new(&path).exists()
}