diff --git a/exe/Main.hs b/exe/Main.hs index 00dfc50..1fb2f8d 100644 --- a/exe/Main.hs +++ b/exe/Main.hs @@ -2,6 +2,7 @@ module Main (main) where import Data.Vector.Storable qualified as V import GarnetRs.Wrapped +import System.IO main :: IO () main = do @@ -13,3 +14,5 @@ main = do 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]) + putStrLn "Nothing." >> printOptional Nothing + putStr "Something: " >> hFlush stdout >> printOptional (Just 67) diff --git a/lib/GarnetRs/Wrapped.hs b/lib/GarnetRs/Wrapped.hs index c3a68b4..05070d0 100644 --- a/lib/GarnetRs/Wrapped.hs +++ b/lib/GarnetRs/Wrapped.hs @@ -10,6 +10,7 @@ module GarnetRs.Wrapped ( add, sumTree, sumSlice, + printOptional, ) where import Control.Monad.Cont @@ -72,3 +73,8 @@ sumTree = unsafePerformIO . flip withBTree (flip with $ Raw.sum_tree . unsafeFro sumSlice :: V.Vector Int64 -> Int64 sumSlice v = unsafePerformIO $ V.unsafeWith v \p -> Raw.sum_slice (unsafeFromPtr p) (fromIntegral $ V.length v) + +printOptional :: Maybe Int8 -> IO () +printOptional = \case + Nothing -> Raw.print_optional (unsafeFromPtr nullPtr) + Just t -> with t (Raw.print_optional . unsafeFromPtr) diff --git a/rust/lib.rs b/rust/lib.rs index 167f24c..5ae47be 100644 --- a/rust/lib.rs +++ b/rust/lib.rs @@ -87,3 +87,11 @@ extern "C" fn sum_tree(t: &BTreeC) -> i64 { extern "C" fn sum_slice(v: *const i64, s: usize) -> i64 { unsafe { slice::from_raw_parts(v, s) }.iter().sum() } + +#[unsafe(no_mangle)] +extern "C" fn print_optional(x: Option<&i8>) -> () { + match x { + Some(x) => println!("{}", x / 2), + None => {} + } +}