Skip to content

Commit

Permalink
feat: count-vowels-kvstore plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
bhelx committed Oct 2, 2023
1 parent ea71abc commit 01ffc7f
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 1 deletion.
9 changes: 9 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ members = [
"reflect",
"store_credit",
"loop_forever",
"count_vowels_kvstore",
]
resolver = "2"

Expand Down
1 change: 0 additions & 1 deletion count_vowels/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,3 @@ pub unsafe fn count_vowels(input: String) -> FnResult<Json<VowelReport>> {

Ok(Json(output))
}

14 changes: 14 additions & 0 deletions count_vowels_kvstore/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "count_vowels_kvstore"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow.workspace = true
serde.workspace = true
extism-pdk.workspace = true

[lib]
crate_type = ["cdylib"]
61 changes: 61 additions & 0 deletions count_vowels_kvstore/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use anyhow::Result;
use extism_pdk::*;
use serde::Serialize;

#[host_fn]
extern "ExtismHost" {
fn kv_read(key: String) -> Vec<u8>;
fn kv_write(key: String, value: Vec<u8>);
}

const VOWELS: &str = "aeiouAEIOU";
const KV_REPORT_KEY: &str = "count-vowels";

#[derive(Serialize)]
struct VowelReport {
pub count: u32,
pub total: u32,
pub vowels: String,
}

fn get_total() -> Result<u32> {
let v = unsafe { kv_read(KV_REPORT_KEY.into()) }?;
// assume it's the correct size
let array: [u8; 4] = [v[0], v[1], v[2], v[3]];
Ok(u32::from_le_bytes(array))
}

fn store_total(total: u32) -> Result<()> {
unsafe { kv_write(KV_REPORT_KEY.into(), total.to_le_bytes().into())? };
Ok(())
}

fn get_vowels() -> String {
match config::get("vowels") {
Some(v) => v,
None => VOWELS.to_string(),
}
}

#[plugin_fn]
pub unsafe fn count_vowels(input: String) -> FnResult<Json<VowelReport>> {
let mut count = 0;
let vowels = get_vowels();
for ch in input.chars() {
if vowels.contains(ch) {
count += 1;
}
}

let mut total = get_total()?;
total += count;
store_total(total)?;

let output = VowelReport {
count,
total,
vowels,
};

Ok(Json(output))
}

0 comments on commit 01ffc7f

Please sign in to comment.