Add vector/slice example
This commit is contained in:
parent
ca99358747
commit
14e0e85823
@ -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])
|
||||
|
||||
@ -41,6 +41,7 @@ common common
|
||||
mtl,
|
||||
process,
|
||||
text,
|
||||
vector,
|
||||
|
||||
library
|
||||
import: common
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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()
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user