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
66
67
68
69
70
71
72
73
74
75
76
77
78
use core::fmt;

use {Descriptor, Encoding};
use multi::Encodings;
use super::never::Never;

/// An encoding for a struct.
#[derive(Clone, Copy, Debug)]
pub struct Struct<S, T> where S: AsRef<str>, T: Encodings {
    name: S,
    fields: T,
}

impl<S, T> Struct<S, T> where S: AsRef<str>, T: Encodings {
    /// Constructs an encoding for a struct with the given name and
    /// fields with the given encodings.
    pub fn new(name: S, fields: T) -> Struct<S, T> {
        Struct { name: name, fields: fields }
    }

    fn name(&self) -> &str {
        self.name.as_ref()
    }
}

impl<S, T> Encoding for Struct<S, T> where S: AsRef<str>, T: Encodings {
    type PointerTarget = Never;
    type ArrayItem = Never;
    type StructFields = T;
    type UnionMembers = Never;

    fn descriptor(&self) -> Descriptor<Never, Never, T, Never> {
        Descriptor::Struct(self.name(), &self.fields)
    }
}

impl<S, T> fmt::Display for Struct<S, T> where S: AsRef<str>, T: Encodings {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        self.write(formatter)
    }
}

impl<S, T, E: ?Sized> PartialEq<E> for Struct<S, T>
        where S: AsRef<str>, T: Encodings, E: Encoding {
    fn eq(&self, other: &E) -> bool {
        self.eq_encoding(other)
    }
}

#[cfg(test)]
mod tests {
    use std::string::ToString;
    use encoding::Primitive;
    use parse::StrEncoding;
    use super::*;

    #[test]
    fn test_static_struct() {
        let f = (Primitive::Char, Primitive::Int);
        let s = Struct::new("CGPoint", f);
        assert_eq!(s.name(), "CGPoint");
        assert_eq!(s.to_string(), "{CGPoint=ci}");
    }

    #[test]
    fn test_eq_encoding() {
        let i = Primitive::Int;
        let c = Primitive::Char;

        let s = Struct::new("CGPoint", (c, i));
        assert!(s == s);
        assert!(s != i);

        let s2 = StrEncoding::new_unchecked("{CGPoint=ci}");
        assert!(s2 == s2);
        assert!(s == s2);
    }
}