Add vector/slice example

This commit is contained in:
George Thomas 2026-03-25 01:09:10 +00:00
parent 97e2fd8823
commit 6ec7bc004f
4 changed files with 14 additions and 0 deletions

View File

@ -1,5 +1,6 @@
module Main (main) where
import Data.Vector.Storable qualified as V
import GarnetRs.Wrapped
main :: IO ()
@ -11,3 +12,4 @@ main = do
helloShape $ Rectangle 10.0 5.0
putStrLn $ "3 + 4 = " <> show (add 3 4)
putStrLn $ "Tree sum: " <> show (sumTree (Fork (Fork (Leaf 1) (Fork (Leaf 2) (Leaf 3))) (Leaf 4)))
putStrLn $ "Slice sum: " <> show (sumSlice $ V.fromList [0 .. 5])

View File

@ -34,6 +34,7 @@ common common
mtl,
process,
text,
vector,
library
import: common

View File

@ -9,12 +9,14 @@ module GarnetRs.Wrapped (
helloShape,
add,
sumTree,
sumSlice,
) where
import Control.Monad.Cont
import Control.Monad.Trans
import Data.ByteString
import Data.Function
import Data.Vector.Storable qualified as V
import Data.Word
import Foreign
import Foreign.C
@ -67,3 +69,6 @@ add = Raw.add
sumTree :: BTree Int64 -> Int64
sumTree = unsafePerformIO . flip withBTree (flip with $ Raw.sum_tree . unsafeFromPtr)
sumSlice :: V.Vector Int64 -> Int64
sumSlice v = unsafePerformIO $ V.unsafeWith v \p -> Raw.sum_slice (unsafeFromPtr p) (fromIntegral $ V.length v)

View File

@ -3,6 +3,7 @@
use std::{
ffi::{CStr, c_char},
ops::Add,
slice,
};
fn say_hello(name: &str) {
@ -81,3 +82,8 @@ enum BTreeC {
extern "C" fn sum_tree(t: &BTreeC) -> i64 {
(unsafe { std::mem::transmute::<_, &BTree<i64>>(t) }).sum()
}
#[unsafe(no_mangle)]
extern "C" fn sum_slice(v: *const i64, s: usize) -> i64 {
unsafe { slice::from_raw_parts(v, s) }.iter().sum()
}