Skip to content

Commit cd3ea6a

Browse files
committed
add cpp_ref example
1 parent 8f0be78 commit cd3ea6a

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

examples/cpp_ref/cpp_ref.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
use std::ops::Receiver;
2+
3+
use field_projection::{
4+
compat::{ProjectableExt, Safe},
5+
marker::Field,
6+
ops::{Project, ProjectMut, Projectable, SafeProject},
7+
};
8+
9+
pub struct CppMutRef<T: ?Sized>(*mut T);
10+
11+
impl<T: ?Sized> CppMutRef<T> {
12+
pub fn write(&mut self, value: T)
13+
where
14+
T: Sized + Copy,
15+
{
16+
unsafe { self.0.write(value) }
17+
}
18+
}
19+
20+
impl<T: ?Sized> Receiver for CppMutRef<T> {
21+
type Target = T;
22+
}
23+
24+
impl<T: ?Sized> Projectable for CppMutRef<T> {
25+
type Inner = T;
26+
}
27+
28+
unsafe impl<T: ?Sized> SafeProject for CppMutRef<T> {}
29+
30+
unsafe impl<T: ?Sized> ProjectableExt for CppMutRef<T> {
31+
type Safety = Safe;
32+
}
33+
34+
unsafe impl<T, F> ProjectMut<F> for CppMutRef<T>
35+
where
36+
F: Field<Base = T>,
37+
F::Type: Sized,
38+
{
39+
type OutputMut<'a>
40+
= CppMutRef<F::Type>
41+
where
42+
Self: 'a;
43+
44+
unsafe fn project_mut<'a>(this: *mut Self) -> Self::OutputMut<'a>
45+
where
46+
Self: 'a,
47+
{
48+
CppMutRef(unsafe { <*mut T as Project<F>>::project(&raw const (*this).0) })
49+
}
50+
}

examples/cpp_ref/main.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#![feature(arbitrary_self_types)]
2+
3+
use field_projection::compat::{HasFields, p, start_proj};
4+
5+
mod cpp_ref;
6+
use cpp_ref::CppMutRef;
7+
8+
// Shared between C++ and Rust.
9+
#[derive(HasFields)]
10+
pub struct Point {
11+
pub x: i32,
12+
pub y: i32,
13+
}
14+
15+
impl Point {
16+
pub fn set_x(mut self: CppMutRef<Self>, value: i32) {
17+
start_proj!(mut self);
18+
p!(@mut self->x).write(value);
19+
}
20+
21+
pub fn set_y(mut self: CppMutRef<Self>, value: i32) {
22+
start_proj!(mut self);
23+
p!(@mut self->y).write(value);
24+
}
25+
}
26+
27+
fn main() {}

0 commit comments

Comments
 (0)