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
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
use std::fmt;

use super::Icon;
use serde::de;

/// Internal link(s) to related topics associated with abstract. A result could
/// either be a single `TopicResult`, or a `Topic` containing multiple
/// `TopicResult`s in a certain area of interest.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RelatedTopic {
    /// The link had a single topic.
    TopicResult(TopicResult),
    /// The link had a whole topic category.
    Topic(Topic),
}

impl<'de> de::Deserialize<'de> for RelatedTopic {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: de::Deserializer<'de>
    {
        deserializer.deserialize_map(Visitor)
    }
}

struct Visitor;

macro_rules! serialise {
    ($builder:ident, $visitor:ident) => {
        match &*$visitor.next_key::<String>().expect("valid key").expect("field") {
            "Icon" => {
                $builder.icon = $visitor.next_value()?;
            }
            "Result" => {
                $builder.result = $visitor.next_value()?;
            }
            "FirstURL" => {
                $builder.first_url = $visitor.next_value()?;
            }
            "Text" => {
                $builder.text = $visitor.next_value()?;
            }
            other => panic!("no struct has key `{}`", other),
        }
    }
}

impl<'de> de::Visitor<'de> for Visitor {
    type Value = RelatedTopic;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "a object containing with Topics, FirstURL, Result properties")
    }

    fn visit_map<V>(self, mut visitor: V) -> Result<RelatedTopic, V::Error>
        where V: de::MapAccess<'de>
        {
            let s: String = visitor.next_key()?.expect("got struct with no fields");
            let val = match &*s {
                "Topics" => {
                    Ok(RelatedTopic::Topic(Topic {
                        topics: visitor.next_value()?,
                        name: {
                            let s: String = visitor.next_key()?.expect("Name field");
                            assert_eq!(&s, "Name");
                            visitor.next_value()?
                        },
                    }))
                },

                "Name" => {
                    Ok(RelatedTopic::Topic(Topic {
                        name: visitor.next_value()?,
                        topics: {
                            let s: String = visitor.next_key()?.expect("Topics field");
                            assert_eq!(&s, "Topics");
                            visitor.next_value()?
                        },
                    }))
                },

                "FirstURL" => {
                    let mut builder = TopicResultBuilder::default();
                    let first_url = visitor.next_value()?;
                    serialise!(builder, visitor);
                    serialise!(builder, visitor);
                    serialise!(builder, visitor);

                    Ok(RelatedTopic::TopicResult(TopicResult {
                        first_url: first_url,
                        icon: builder.icon.expect("Icon field"),
                        result: builder.result.expect("Result field"),
                        text: builder.text.expect("Text field"),
                    }))
                },

                "Result" => {
                    let mut builder = TopicResultBuilder::default();
                    let result = visitor.next_value()?;
                    serialise!(builder, visitor);
                    serialise!(builder, visitor);
                    serialise!(builder, visitor);

                    Ok(RelatedTopic::TopicResult(TopicResult {
                        first_url: builder.first_url.expect("Result field"),
                        icon: builder.icon.expect("Icon field"),
                        result: result,
                        text: builder.text.expect("Text field"),
                    }))
                },

                "Icon" => {
                    let mut builder = TopicResultBuilder::default();
                    let icon = visitor.next_value()?;
                    serialise!(builder, visitor);
                    serialise!(builder, visitor);
                    serialise!(builder, visitor);

                    Ok(RelatedTopic::TopicResult(TopicResult {
                        first_url: builder.first_url.expect("Result field"),
                        icon: icon,
                        result: builder.result.expect("Icon field"),
                        text: builder.text.expect("Text field"),
                    }))
                },

                "Text" => {
                    let mut builder = TopicResultBuilder::default();
                    let text = visitor.next_value()?;
                    serialise!(builder, visitor);
                    serialise!(builder, visitor);
                    serialise!(builder, visitor);

                    Ok(RelatedTopic::TopicResult(TopicResult {
                        first_url: builder.first_url.expect("Result field"),
                        icon: builder.icon.expect("Icon field"),
                        result: builder.result.expect("Result field"),
                        text: text,
                    }))
                },

                other => panic!("no struct has field `{}`", other),
            };
            val
        }
}

/// An link associated with abstract.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct TopicResult {
    /// First URL for the Result.
    #[serde(rename="FirstURL")]
    pub first_url: String,
    /// Icon associated with `first_url`.
    #[serde(rename="Icon")]
    pub icon: Icon,
    /// HTML link(s) to external site(s).
    #[serde(rename="Result")]
    pub result: String,
    /// Text from `first_url`.
    #[serde(rename="Text")]
    pub text: String,
}

// Internal struct for handling non guarenteed order of TopicResult.
#[derive(Default)]
struct TopicResultBuilder {
    pub first_url: Option<String>,
    pub icon: Option<Icon>,
    pub result: Option<String>,
    pub text: Option<String>,
}


/// Name, and Vec of `TopicResult`s.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct Topic {
    /// vec of external links associated with abstract.
    #[serde(rename="Topics")]
    pub topics: Vec<RelatedTopic>,
    /// The name of the topic. for example if the query was Apple, it could be
    /// a topic about botany, or companies.
    #[serde(rename="Name")]
    pub name: String,
}