3 #![allow(unused_must_use)]
5 #![allow(unused_imports)]
8 use std::io::prelude::*;
11 use std::marker::PhantomData;
17 trait Encodable<S: Encoder> {
18 fn encode(&self, s: &mut S) -> Result<(), S::Error>;
21 struct JsonEncoder<'a>(PhantomData<&'a mut ()>);
23 impl Encoder for JsonEncoder<'_> {
27 struct AsJson<'a, T> {
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 {
38 fn as_json<T>(t: &T) -> AsJson<'_, T> {
42 struct OpaqueEncoder(Vec<u8>);
44 impl Encoder for OpaqueEncoder {
53 impl<S: Encoder> Encodable<S> for Foo {
54 fn encode(&self, _s: &mut S) -> Result<(), S::Error> {
63 impl<S: Encoder> Encodable<S> for Bar {
64 fn encode(&self, _s: &mut S) -> Result<(), S::Error> {
75 fn encode_json<T: for<'a> Encodable<JsonEncoder<'a>>>(val: &T, wr: &mut Cursor<Vec<u8>>) {
76 write!(wr, "{}", as_json(val));
79 fn encode_opaque<T: Encodable<OpaqueEncoder>>(val: &T, wr: Vec<u8>) {
80 let mut encoder = OpaqueEncoder(wr);
81 val.encode(&mut encoder);
85 let target = Foo { baz: false };
86 let proto = WireProtocol::JSON;
88 WireProtocol::JSON => encode_json(&target, &mut Cursor::new(Vec::new())),
89 WireProtocol::Opaque => encode_opaque(&target, Vec::new()),