]> git.lizzy.rs Git - rust.git/blob - tests/ui-fulldeps/issue-11881.rs
Fix problem noticed in PR106859 with char -> u8 suggestion
[rust.git] / tests / ui-fulldeps / issue-11881.rs
1 // run-pass
2
3 #![allow(unused_must_use)]
4 #![allow(dead_code)]
5 #![allow(unused_imports)]
6
7 use std::fmt;
8 use std::io::prelude::*;
9 use std::io::Cursor;
10 use std::slice;
11 use std::marker::PhantomData;
12
13 trait Encoder {
14     type Error;
15 }
16
17 trait Encodable<S: Encoder> {
18     fn encode(&self, s: &mut S) -> Result<(), S::Error>;
19 }
20
21 struct JsonEncoder<'a>(PhantomData<&'a mut ()>);
22
23 impl Encoder for JsonEncoder<'_> {
24     type Error = ();
25 }
26
27 struct AsJson<'a, T> {
28     inner: &'a T,
29 }
30
31 impl<'a, T: for<'r> Encodable<JsonEncoder<'r>>> fmt::Display for AsJson<'a, T> {
32     /// Encodes a json value into a string
33     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
34         Ok(())
35     }
36 }
37
38 fn as_json<T>(t: &T) -> AsJson<'_, T> {
39     AsJson { inner: t }
40 }
41
42 struct OpaqueEncoder(Vec<u8>);
43
44 impl Encoder for OpaqueEncoder {
45     type Error = ();
46 }
47
48
49 struct Foo {
50     baz: bool,
51 }
52
53 impl<S: Encoder> Encodable<S> for Foo {
54     fn encode(&self, _s: &mut S) -> Result<(), S::Error> {
55         Ok(())
56     }
57 }
58
59 struct Bar {
60     froboz: usize,
61 }
62
63 impl<S: Encoder> Encodable<S> for Bar {
64     fn encode(&self, _s: &mut S) -> Result<(), S::Error> {
65         Ok(())
66     }
67 }
68
69 enum WireProtocol {
70     JSON,
71     Opaque,
72     // ...
73 }
74
75 fn encode_json<T: for<'a> Encodable<JsonEncoder<'a>>>(val: &T, wr: &mut Cursor<Vec<u8>>) {
76     write!(wr, "{}", as_json(val));
77 }
78
79 fn encode_opaque<T: Encodable<OpaqueEncoder>>(val: &T, wr: Vec<u8>) {
80     let mut encoder = OpaqueEncoder(wr);
81     val.encode(&mut encoder);
82 }
83
84 pub fn main() {
85     let target = Foo { baz: false };
86     let proto = WireProtocol::JSON;
87     match proto {
88         WireProtocol::JSON => encode_json(&target, &mut Cursor::new(Vec::new())),
89         WireProtocol::Opaque => encode_opaque(&target, Vec::new()),
90     }
91 }