summaryrefslogtreecommitdiff
path: root/rust/pin-init/examples/selfref.rs
blob: 5212b9255b750860e5233ee0e3423f3af1c4daa9 (plain) (blame)
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
57
58
59
60
// SPDX-License-Identifier: Apache-2.0 OR MIT

#![allow(clippy::disallowed_names)]

use pin_init::*;

#[pin_data]
struct SelfRef {
    #[uses('_: invariant)]
    not_cov: Box<dyn Fn(&'str str) -> bool + 'str>,

    part: &'str str,
    str: String,

    mut_part: &'mut_str mut str,
    #[borrowed(mut)]
    mut_str: String,
}

fn use_self_ref() {
    stack_pin_init!(let foo = pin_init!(SelfRef {
        str: "hello world".to_owned(),
        part: &str[..5],
        mut_str: "hello world".to_owned(),
        mut_part: &mut mut_str[..5],
        not_cov: Box::new(move |s| s == str),
    }));

    // Access via projection.
    println!("{}", foo.as_mut().project().part);

    // Access via accessor.
    println!("{}", foo.part());

    // Access via `with_project`, gives mutable reference.
    foo.as_mut().with_project(|proj| {
        *proj.part = &proj.str[5..];
    });

    println!("{}", foo.part());

    // Access fields that mutable borrow others are similar to those of shared borrow.
    println!("{}", foo.as_mut().project().mut_part);
    println!("{}", foo.mut_part());
    foo.as_mut().with_project(|proj| {
        proj.mut_part.make_ascii_uppercase();
    });

    // Access non-covariant type using `with_` accessor.
    foo.with_not_cov(|not_cov| {
        not_cov("");
    });

    // Access non-covariant type using `with_project`.
    foo.as_mut().with_project(|proj| (proj.not_cov)(proj.str));
}

fn main() {
    use_self_ref();
}