File: deriving-coerce-pointee.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 893,176 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; lisp: 29; perl: 29; ruby: 19; sql: 11
file content (56 lines) | stat: -rw-r--r-- 1,253 bytes parent folder | download | duplicates (14)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//@ run-pass
#![feature(derive_coerce_pointee, arbitrary_self_types)]

use std::marker::CoercePointee;

#[derive(CoercePointee)]
#[repr(transparent)]
struct MyPointer<'a, #[pointee] T: ?Sized> {
    ptr: &'a T,
}

impl<T: ?Sized> Copy for MyPointer<'_, T> {}
impl<T: ?Sized> Clone for MyPointer<'_, T> {
    fn clone(&self) -> Self {
        Self { ptr: self.ptr }
    }
}

impl<'a, T: ?Sized> core::ops::Deref for MyPointer<'a, T> {
    type Target = T;
    fn deref(&self) -> &'a T {
        self.ptr
    }
}

struct MyValue(u32);
impl MyValue {
    fn through_pointer(self: MyPointer<'_, Self>) -> u32 {
        self.ptr.0
    }
}

trait MyTrait {
    fn through_trait(&self) -> u32;
    fn through_trait_and_pointer(self: MyPointer<'_, Self>) -> u32;
}

impl MyTrait for MyValue {
    fn through_trait(&self) -> u32 {
        self.0
    }

    fn through_trait_and_pointer(self: MyPointer<'_, Self>) -> u32 {
        self.ptr.0
    }
}

pub fn main() {
    let v = MyValue(10);
    let ptr = MyPointer { ptr: &v };
    assert_eq!(v.0, ptr.through_pointer());
    assert_eq!(v.0, ptr.through_pointer());
    let dptr = ptr as MyPointer<dyn MyTrait>;
    assert_eq!(v.0, dptr.through_trait());
    assert_eq!(v.0, dptr.through_trait_and_pointer());
}