on master help sign in
Merge pull request #4084 from asandroq/general-withalloc

Make type of `withAlloc` more general

commit17e684c7bc3bc6aa58a46894d2fd52dae482e99f authorNiklas Larsson <metaniklas@gmail.com> dateFri 22 Sep 2017, 14:49 (9 years ago) parent292fac7b927dd4
4 files changed+27−3
libs/contrib/CFFI/Memory.idr+3−2 test/ffi008/ffi008.c+12−1 test/ffi008/ffi008.h+2 test/ffi008/ffi008.idr+10
libs/contrib/CFFI/Memory.idr+3−2
@@ -40,10 +40,11 @@ free : CPtr -> IO ()
4040free (CPt p _ ) = mfree p
4141
4242||| Perform an IO action with memory that is freed afterwards
43−withAlloc : Composite -> (CPtr -> IO ()) -> IO ()
43+withAlloc : Composite -> (CPtr -> IO a) -> IO a
4444withAlloc t f = do m <- alloc t
45− f m
45+ r <- f m
4646 free m
47+ pure r
4748
4849infixl 1 ~~>
4950||| Perform an IO action with memory that is freed afterwards
test/ffi008/ffi008.c+12−1
@@ -1,5 +1,7 @@
1−#include "ffi008.h"
21#include <stdio.h>
2+#include <stdlib.h>
3+
4+#include "ffi008.h"
35
46int size1(void) {
57 return sizeof(struct test1);
@@ -12,3 +14,12 @@ int size2(void) {
1214void print_mystruct(void) {
1315 printf("a: %d b: %d\n", mystruct.a, mystruct.b);
1416}
17+
18+struct test2* calc_struct(struct test1 *in)
19+{
20+ struct test2 *out = malloc(sizeof(struct test2));
21+ out->a = in->a * in->a;
22+ out->b = in->b & 0x0000FFFF;
23+
24+ return out;
25+}
test/ffi008/ffi008.h+2
@@ -15,3 +15,5 @@ struct test2 mystruct;
1515int size1(void);
1616int size2(void);
1717void print_mystruct();
18+
19+struct test2* calc_struct(struct test1*);
test/ffi008/ffi008.idr+10
@@ -18,6 +18,9 @@ mystruct = foreign FFI_C "&mystruct" (IO Ptr)
1818print_mystruct : IO ()
1919print_mystruct = foreign FFI_C "print_mystruct" (IO ())
2020
21+calc_struct : Ptr -> IO Ptr
22+calc_struct = foreign FFI_C "calc_struct" (Ptr -> IO Ptr)
23+
2124test1 : Composite
2225test1 = STRUCT [I8, I64]
2326
@@ -46,3 +49,10 @@ main = do
4649 print !(peek I32 f1)
4750 withAlloc PTR $ \p =>
4851 poke PTR p fms
52+ res <- withAlloc test1 $ \p => do
53+ let f1 = (test1 # 0) p
54+ let f2 = (test1 # 1) p
55+ poke I8 f1 42
56+ poke I64 f2 1125899906842624
57+ calc_struct p
58+ free res