Skip to content

Commit 8ac65af

Browse files
Implement Encodable and Decodable for Result.
1 parent 16212b9 commit 8ac65af

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/libserialize/serialize.rs

+48
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,54 @@ impl<T:Decodable> Decodable for Option<T> {
618618
}
619619
}
620620

621+
impl<T1: Encodable, T2: Encodable> Encodable for Result<T1, T2> {
622+
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
623+
s.emit_enum("Result", |s| {
624+
match *self {
625+
Ok(ref v) => {
626+
s.emit_enum_variant("Ok", 0, 1, |s| {
627+
s.emit_enum_variant_arg(0, |s| {
628+
v.encode(s)
629+
})
630+
})
631+
}
632+
Err(ref v) => {
633+
s.emit_enum_variant("Err", 1, 1, |s| {
634+
s.emit_enum_variant_arg(0, |s| {
635+
v.encode(s)
636+
})
637+
})
638+
}
639+
}
640+
})
641+
}
642+
}
643+
644+
impl<T1:Decodable, T2:Decodable> Decodable for Result<T1, T2> {
645+
fn decode<D: Decoder>(d: &mut D) -> Result<Result<T1, T2>, D::Error> {
646+
d.read_enum("Result", |d| {
647+
d.read_enum_variant(&["Ok", "Err"], |d, disr| {
648+
match disr {
649+
0 => {
650+
Ok(Ok(d.read_enum_variant_arg(0, |d| {
651+
T1::decode(d)
652+
})?))
653+
}
654+
1 => {
655+
Ok(Err(d.read_enum_variant_arg(0, |d| {
656+
T2::decode(d)
657+
})?))
658+
}
659+
_ => {
660+
panic!("Encountered invalid discriminant while \
661+
decoding `Result`.");
662+
}
663+
}
664+
})
665+
})
666+
}
667+
}
668+
621669
macro_rules! peel {
622670
($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
623671
}

0 commit comments

Comments
 (0)