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
61
62
63
64
65

use graph::NodeIndex;
use rustc_serialize::{Encodable, Decodable, Encoder, Decoder};
use widget::WidgetId;


/// An index either given in the form of a publicly instantiated `Widget`'s `WidgetId`, or an
/// internally instantiated `Widget`'s `NodeIndex`,
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Index {
    /// A public identifier given by a user of a conrod library/widget, usually generated by the
    /// `widget_ids` macro.
    Public(WidgetId),
    /// An index to an internal widget, usually used to construct some other widget.
    Internal(NodeIndex),
}


impl From<WidgetId> for Index {
    fn from(id: WidgetId) -> Index {
        Index::Public(id)
    }
}

impl From<NodeIndex> for Index {
    fn from(idx: NodeIndex) -> Index {
        Index::Internal(idx)
    }
}

impl Encodable for Index {
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
        encoder.emit_enum("Index", |encoder| {
            match *self {
                Index::Public(id) =>
                    encoder.emit_enum_variant("Public", 0, 2, |encoder| {
                        encoder.emit_enum_variant_arg(0, |encoder| encoder.emit_usize(id))
                    }),
                Index::Internal(idx) =>
                    encoder.emit_enum_variant("Internal", 1, 2, |encoder| {
                        encoder.emit_enum_variant_arg(0, |encoder| encoder.emit_usize(idx.index()))
                    }),
            }
        })
    }
}

impl Decodable for Index {
    fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, D::Error> {
        decoder.read_enum("Index", |decoder| {
            decoder.read_enum_variant(&["Public", "Internal"], |decoder, i| {
                Ok(match i {
                    0 => Index::Public(try!(decoder.read_enum_variant_arg(0, |decoder| {
                        decoder.read_usize()
                    }))),
                    1 => Index::Internal(try!(decoder.read_enum_variant_arg(0, |decoder| {
                        Ok(NodeIndex::new(try!(decoder.read_usize())))
                    }))),
                    _ => unreachable!(),
                })
            })
        })
    }
}