about summary refs log tree commit diff
path: root/tests/ui/higher-ranked/higher-ranked-encoding.rs
blob: 463e0f50e5379f9bd5bbbf067f4d832304fc3501 (plain)
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
//! Regression test for https://github.com/rust-lang/rust/issues/15924

//@ run-pass

use std::marker::PhantomData;

trait Encoder {
    type Error;
}

trait Encodable<S: Encoder> {
    fn encode(&self, s: &mut S) -> Result<(), S::Error>;
}

impl<S: Encoder> Encodable<S> for i32 {
    fn encode(&self, _s: &mut S) -> Result<(), S::Error> {
        Ok(())
    }
}

struct JsonEncoder<'a>(PhantomData<&'a mut ()>);

impl Encoder for JsonEncoder<'_> {
    type Error = ();
}

// This function uses higher-ranked trait bounds, which previously caused ICE
fn encode_json<T: for<'r> Encodable<JsonEncoder<'r>>>(object: &T) -> Result<String, ()> {
    let s = String::new();
    {
        let mut encoder = JsonEncoder(PhantomData);
        object.encode(&mut encoder)?;
    }
    Ok(s)
}

// Structure with HRTB constraint that was problematic
struct Foo<T: for<'a> Encodable<JsonEncoder<'a>>> {
    v: T,
}

// Drop implementation that exercises the HRTB bounds
impl<T: for<'a> Encodable<JsonEncoder<'a>>> Drop for Foo<T> {
    fn drop(&mut self) {
        let _ = encode_json(&self.v);
    }
}

fn main() {
    let _ = Foo { v: 10 };
}