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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
//! # Serializers
//!
//! Normally when using "serde_json" and `#[derive(Serialize)]` you only can have one JSON
//! representation for a type, however sometimes you might need another one which has more or less
//! data.
//!
//! This crate makes it easy to create "serializers" that take some value and turn it into JSON.
//! You get to decide for each serializer which type it serializes, and which fields and
//! associations it includes.
//!
//! ## Example
//!
//! ```
//! #[macro_use]
//! extern crate serializers;
//! #[macro_use]
//! extern crate serde_json;
//!
//! use serializers::*;
//!
//! struct User {
//!     id: u64,
//!     name: String,
//!     country: Country,
//!     friends: Vec<User>,
//! }
//!
//! #[derive(Clone)]
//! struct Country {
//!     id: u64,
//! }
//!
//! serializer! {
//!     #[derive(Debug)]
//!     struct UserSerializer<User> {
//!         attr(id)
//!         attr(name)
//!         has_one(country, CountrySerializer)
//!         has_many(friends, UserSerializer)
//!     }
//! }
//!
//! serializer! {
//!     #[derive(Debug)]
//!     struct CountrySerializer<Country> {
//!         attr(id)
//!     }
//! }
//!
//! fn main() {
//!     let denmark = Country {
//!         id: 1,
//!     };
//!
//!     let bob = User {
//!         id: 1,
//!         name: "Bob".to_string(),
//!         country: denmark.clone(),
//!         friends: vec![
//!             User {
//!                 id: 2,
//!                 name: "Alice".to_string(),
//!                 country: denmark.clone(),
//!                 friends: vec![],
//!             }
//!         ],
//!     };
//!
//!     // Serializing a single user
//!     let json: String = UserSerializer::serialize(&bob);
//!     assert_eq!(
//!         json,
//!         json!({
//!             "country": { "id": 1 },
//!             "friends": [
//!                 {
//!                     "country": { "id": 1 },
//!                     "friends": [],
//!                     "name": "Alice",
//!                     "id": 2
//!                 }
//!             ],
//!             "name": "Bob",
//!             "id": 1
//!         }).to_string(),
//!     );
//!
//!     // Serializing a vector of users
//!     let users = vec![bob];
//!     let json: String = UserSerializer::serialize_iter(&users);
//!     assert_eq!(
//!         json,
//!         json!([
//!             {
//!                 "country": { "id": 1 },
//!                 "friends": [
//!                     {
//!                         "country": { "id": 1 },
//!                         "friends": [],
//!                         "name": "Alice",
//!                         "id": 2
//!                     }
//!                 ],
//!                 "name": "Bob",
//!                 "id": 1
//!             }
//!         ]).to_string(),
//!     );
//! }
//! ```
//!
//! See the [macro docs](macro.serializer.html) for more information about the `serializer!` macro.
//!
//! ## No macros for me
//!
//! The easiest way to define serializers is using the `serializer!` macro, however if you don't
//! wish to do so you can define serializers like so:
//!
//! ```
//! # #[macro_use]
//! # extern crate serializers;
//! # use serializers::*;
//! #
//! # struct User {
//! #     id: u64,
//! #     name: String,
//! #     country: Country,
//! #     friends: Vec<User>,
//! # }
//! #
//! # struct Country {
//! #     id: u64,
//! # }
//! #
//! # serializer! {
//! #     struct CountrySerializer<Country> {
//! #         attr(id)
//! #     }
//! # }
//! #
//! struct UserSerializer;
//!
//! impl Serializer<User> for UserSerializer {
//!     fn serialize_into(&self, user: &User, b: &mut Builder) {
//!         b.attr("id", &user.id);
//!         b.attr("name", &user.name);
//!         b.has_one("country", &user.country, &CountrySerializer);
//!         b.has_many("friends", &user.friends, &UserSerializer);
//!     }
//! }
//! #
//! # fn main() {}
//! ```

#![deny(
    missing_docs,
    unused_imports,
    missing_debug_implementations,
    missing_copy_implementations,
    trivial_casts,
    trivial_numeric_casts,
    unsafe_code,
    unstable_features,
    unused_import_braces,
    unused_qualifications
)]
#![doc(html_root_url = "https://docs.rs/serializers/0.2.0")]

extern crate serde;
#[macro_use]
extern crate serde_json;

use serde::Serialize;
use serde_json::Value;
use std::collections::HashMap;

mod macros;

/// The trait you implement in order to make a serializer.
pub trait Serializer<T> {
    /// Add key-value pairs to the builder for the given object.
    ///
    /// You shouldn't have to call this method yourself. It'll be called by other method in this
    /// trait.
    fn serialize_into(&self, value: &T, builder: &mut Builder);

    /// Turn the given object into a `serde_json::Value`.
    fn to_value(&self, value: &T) -> Value {
        let mut builder = Builder::new();
        self.serialize_into(value, &mut builder);
        builder.to_value()
    }

    /// Turn the given object into a JSON string.
    fn serialize(&self, value: &T) -> String {
        self.to_value(value).to_string()
    }

    /// Turn the given iterable into JSON array. The main usecase for this is to turn `Vec`s into
    /// JSON arrays, but works for any iterator.
    fn serialize_iter<'a, I>(&self, values: I) -> String
    where
        I: IntoIterator<Item = &'a T>,
        T: 'a,
    {
        let acc: Vec<_> = values.into_iter().map(|v| self.to_value(&v)).collect();
        json!(acc).to_string()
    }
}

/// The struct responsible for gathering keys and values for the JSON.
///
/// This is the struct you interact with through the
/// [`serialize_into`](trait.Serializer.html#tymethod.serialize_into) method on the
/// [`Serializer`](trait.Serializer.html) trait.
#[derive(Debug)]
pub struct Builder {
    map: HashMap<String, Value>,
}

impl Builder {
    fn new() -> Self {
        Builder {
            map: HashMap::new(),
        }
    }

    fn to_value(&self) -> Value {
        json!(self.map)
    }

    /// Add a single key-value pair to the JSON.
    pub fn attr<K, V>(&mut self, key: K, value: &V) -> &mut Self
    where
        K: Into<String>,
        V: Serialize,
    {
        let key: String = key.into();
        let value: Value = json!(value);
        self.map.insert(key, value);
        self
    }

    /// Add an object to the JSON. The associated value will be serialized using the given
    /// serializer.
    pub fn has_one<K, V, S>(&mut self, key: K, value: &V, serializer: &S) -> &mut Self
    where
        K: Into<String>,
        S: Serializer<V>,
    {
        let key: String = key.into();
        let value: Value = serializer.to_value(value);
        self.map.insert(key, value);
        self
    }

    /// Add an array to the JSON. Each item in the iterable will be serialized using the given
    /// serializer.
    pub fn has_many<'a, K, V: 'a, S, I>(&mut self, key: K, values: I, serializer: &S) -> &mut Self
    where
        K: Into<String>,
        S: Serializer<V>,
        I: IntoIterator<Item = &'a V>,
    {
        let key: String = key.into();
        let value = values
            .into_iter()
            .map(|v| serializer.to_value(&v))
            .collect::<Vec<_>>();
        self.map.insert(key, json!(value));
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    macro_rules! test_user_serializer {
        {
            $($tokens:tt)*
        } => {
            struct User {
                id: u64,
            }

            serializer! {
                $($tokens)*
            }

            let bob = User { id: 1 };
            let json: String = UserSerializer::serialize(&bob);
            assert_eq!(json, json!({ "id": 1 }).to_string());
        };
    }

    #[test]
    fn test_pub_crate() {
        test_user_serializer! {
            pub(crate) struct UserSerializer<User> { attr(id) }
        };
    }

    #[test]
    fn test_pub() {
        test_user_serializer! {
            pub struct UserSerializer<User> { attr(id) }
        };
    }

    #[test]
    fn test_private() {
        test_user_serializer! {
            struct UserSerializer<User> { attr(id) }
        };
    }

    #[test]
    fn test_pub_crate_attrs() {
        test_user_serializer! {
            #[derive(PartialEq, Eq, Debug)]
            pub(crate) struct UserSerializer<User> { attr(id) }
        };
        assert_eq!(UserSerializer, UserSerializer);
    }

    #[test]
    fn test_pub_attrs() {
        test_user_serializer! {
            #[derive(PartialEq, Eq, Debug)]
            pub struct UserSerializer<User> { attr(id) }
        };
        assert_eq!(UserSerializer, UserSerializer);
    }

    #[test]
    fn test_private_attrs() {
        test_user_serializer! {
            #[derive(PartialEq, Eq, Debug)]
            struct UserSerializer<User> { attr(id) }
        };
        assert_eq!(UserSerializer, UserSerializer);
    }

    #[test]
    fn generated_associated_function() {
        struct User {
            id: u64,
        }

        serializer! {
            struct UserSerializer<User> {
                attr(id)
            }
        }

        let bob = User { id: 1 };
        let json: String = UserSerializer::serialize(&bob);
        assert_eq!(json, json!({ "id": 1 }).to_string());
    }
}