Skip to content

Commit 46c5f90

Browse files
committed
Marshal ForeignPtr into rust references
1 parent 275b8af commit 46c5f90

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/Language/Rust/Inline/Context.hs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,8 @@ foreignPointers =
319319
where
320320
rule (Ptr _ t _) context
321321
| First (Just (t', Nothing)) <- lookupRTypeInContext t context = pure ([t|ForeignPtr $t'|], Nothing)
322+
rule (Rptr _ _ t _) context
323+
| First (Just (t', Nothing)) <- lookupRTypeInContext t context = pure ([t|ForeignPtr $t'|], Nothing)
322324
rule (PathTy Nothing (Path False [PathSegment "ForeignPtr" (Just (AngleBracketed [] [t] [] _)) _] _) _) context
323325
| First (Just (t', Nothing)) <- lookupRTypeInContext t context = pure ([t|ForeignPtr $t'|], Nothing)
324326
rule _ _ = mempty
@@ -334,6 +336,10 @@ foreignPointers =
334336
[ "impl<T> MarshalInto<*const T> for *const T {"
335337
, " fn marshal(self) -> *const T { self }"
336338
, "}"
339+
, ""
340+
, "impl<'a, T> MarshalInto<&'a T> for &'a T {"
341+
, " fn marshal(self) -> &'a T { self }"
342+
, "}"
337343
]
338344

339345
mutPtr =
@@ -344,6 +350,7 @@ foreignPointers =
344350
, " ptr"
345351
, " }"
346352
, "}"
353+
, ""
347354
, "impl<T> MarshalInto<ForeignPtr<T>> for ForeignPtr<T> {"
348355
, " fn marshal(self) -> Self {"
349356
, " self"
@@ -363,6 +370,10 @@ foreignPointers =
363370
, "impl<T> MarshalInto<*mut T> for *mut T {"
364371
, " fn marshal(self) -> *mut T { self }"
365372
, "}"
373+
, ""
374+
, "impl<'a, T> MarshalInto<&'a mut T> for &'a mut T {"
375+
, " fn marshal(self) -> &'a mut T { self }"
376+
, "}"
366377
]
367378

368379
{- | This maps a Rust function type into the corresponding 'FunPtr' wrapped

tests/ForeignPtr.hs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,26 @@ foreignPtrTypes = describe "ForeignPtr types" $ do
2424
let read = [rust| u64 { unsafe { *$(p: *const u64) } } |]
2525
42 `shouldBe` read
2626

27+
it "Can marshal ForeignPtr arguments as references" $ do
28+
p <- mallocForeignPtr
29+
withForeignPtr p (`poke` 42)
30+
let read =
31+
[rust| u64 { *$(p: &u64) } |]
32+
42 `shouldBe` read
33+
34+
it "Can marshal ForeignPtr arguments as mutable references" $ do
35+
p <- mallocForeignPtr
36+
withForeignPtr p (`poke` 42)
37+
let prev =
38+
[rust| u64 {
39+
let p = $(p: &mut u64);
40+
let ret = *p;
41+
*p = 43;
42+
ret
43+
} |]
44+
prev `shouldBe` 42
45+
withForeignPtr p peek >>= (`shouldBe` 43)
46+
2747
it "Can mutate ForeignPtr arguments" $ do
2848
p <- mallocForeignPtr
2949
[rustIO| () {

0 commit comments

Comments
 (0)