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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
//! Validation for structs and enums: write rules on their fields, and get every problem back at once.
//!
//! [`Validate::validate`] checks a value. It returns `Ok(())`, or every [`Issue`] it found. Each issue is a
//! [`Problem`] and the [`Path`] where it was found. [`Validate::validate_fail_fast`] returns only the first issue,
//! which is the one `validate` would list first. Fields are reported under the names serde reads them by.
//!
//! With the `serde` feature, on by default, `#[derive(Deserialize)]` checks a struct while it is deserialized:
//!
//! - [`from_deserializer`] returns every missing field and broken rule together.
//! - serde's own `Deserialize` works too. For a struct that breaks its rules, it returns an error with every issue
//! in its message.
//!
//! The `json` feature adds [`json::from_str`] and [`json::from_slice`], which read JSON this way.
pub use ;
pub use DeserializeError;
pub use Location;
pub use ParamValue;
pub use ;
pub use ;
pub use Report;
pub use Rule;
pub use Validate;
/// Implements [`Validate`] from the `#[validate(...)]` rules on the fields of a struct, or of an enum's variants.
///
/// ```
/// use annotated::Validate;
///
/// #[derive(Validate)]
/// #[serde(rename_all = "camelCase")]
/// struct NewMember {
/// #[validate(required, length(max = 50))]
/// full_name: String,
/// }
///
/// let member = NewMember { full_name: " ".to_owned() };
///
/// assert_eq!(member.validate().unwrap_err().to_string(), "fullName: is required");
/// ```
///
/// # Writing rules
///
/// Each entry in `#[validate(...)]` is a rule, and a field's rules are checked in the order written.
///
/// - A single name is a built-in rule from [`rules`]: `required` becomes `annotated::rules::required()`.
/// - A named argument calls the builder method of that name: `length(max = 50)` becomes
/// `annotated::rules::length().max(50)`.
/// - `message = "..."` in a rule's arguments replaces its problem's message. `{param}` placeholders are filled from the
/// problem's parameters.
/// - `length` takes `unit = "chars"`, `"bytes"` or, with the `unicode` feature, `"graphemes"`. A unit on a collection
/// is a compile error.
/// - `pattern`, with the `regex` feature, takes its regular expression as a string literal. The expression is compiled
/// once, and one that doesn't parse is a compile error.
///
/// # How fields are checked
///
/// - Every field is checked. The first rule a field breaks stops that field's other rules. `#[validate(report_all)]` on
/// the struct reports every rule a field breaks instead.
/// - On an `Option` field, `required` checks the `Option` itself. Every other rule checks the value inside, and is
/// skipped when there is none.
/// - `nested` validates a field whose type implements [`Validate`], and reports under the field's name.
/// - `each(...)` applies its rules to every element of a collection, reported at its index, or to every value of a map,
/// reported at its key. It works on anything that implements [`rules::HasElements`]. `each(nested)` validates every
/// element.
/// - A field is reported under the name serde reads it by, from `#[serde(...)]` attributes such as `rename_all` and
/// `rename`. The struct doesn't need to derive serde's traits.
/// - A field with `#[serde(flatten)]` is reported at the struct's own location, since its keys sit in the struct's
/// map: issues inside a flattened `address` are at `street`, not `address.street`.
/// - [`Validate::validate_fail_fast`] checks the same rules in the same order, nested values and elements included, and
/// returns only the first issue, even under `report_all`. It stops right after that issue, with one
/// exception: when the issue is inside a `nested` value, or inside an element checked with `nested`, the struct
/// around it may check more before it stops. It records nothing more.
///
/// # Rules on the whole struct
///
/// `#[validate(custom(check))]` on the struct checks the whole struct with any `Fn(&Self) -> Result<(), Problem>`.
///
/// - It reports at the struct's own location: the root, or the field the struct is `nested` under.
/// `custom(check, field = name)` reports at that field instead, under its serde name.
/// - `message = "..."` replaces the problem's message.
/// - Struct-level rules are checked after every field, in the order written. They can share a `#[validate(...)]` with
/// `report_all`, or have one of their own.
/// - A rule with `field` counts as that field's last rule. It is skipped once the field has an issue, and once one
/// of them fails for a field, the later ones for that field are skipped. With `report_all` on the struct, none of
/// them is skipped.
/// - A rule without `field` always runs.
///
/// ```
/// use annotated::{Problem, Validate};
///
/// #[derive(Validate)]
/// #[serde(rename_all = "camelCase")]
/// #[validate(custom(passwords_match, field = repeated_password))]
/// struct NewPassword {
/// #[validate(length(min = 8))]
/// password: String,
/// repeated_password: String,
/// }
///
/// fn passwords_match(new_password: &NewPassword) -> Result<(), Problem> {
/// if new_password.repeated_password != new_password.password {
/// return Err(Problem::custom("passwords_differ", "must match the password"));
/// }
/// Ok(())
/// }
///
/// let new_password = NewPassword {
/// password: "correct horse battery staple".to_owned(),
/// repeated_password: "correct horse".to_owned(),
/// };
///
/// assert_eq!(new_password.validate().unwrap_err().to_string(), "repeatedPassword: must match the password");
/// ```
///
/// # Enums
///
/// On an enum, rules go on the fields of its variants, named or not, and the variant the value holds is checked.
///
/// - Each issue is at the path where serde reads its value, as the enum's `#[serde(...)]` lays the variant out: under
/// the variant's name by default (`card.number`), at the enum's own location with `tag` or `untagged`
/// (`number`), and under the content's name with `tag` and `content` (`data.number`). A variant with
/// `#[serde(untagged)]` is at the enum's own location too.
/// - A newtype variant's value is at the variant's location, and a tuple variant's elements at their index.
/// - `#[validate(...)]` on the enum takes `custom(check)` and `report_all`, as on a struct. A `custom` rule reports at
/// the enum's own location, after the variant's fields. It takes no `field`, since each field belongs to one variant.
///
/// ```
/// use annotated::Validate;
///
/// #[derive(Validate)]
/// #[serde(rename_all = "camelCase")]
/// enum Payment {
/// Card {
/// #[validate(length(min = 16))]
/// number: String,
/// },
/// BankTransfer(#[validate(required)] String),
/// }
///
/// let payment = Payment::Card { number: "4111".to_owned() };
///
/// assert_eq!(payment.validate().unwrap_err().to_string(), "card.number: must be at least 16 characters long");
/// ```
pub use Validate;
/// Implements [`Deserialize`](trait@Deserialize), and serde's own `Deserialize` through it, for a struct with named
/// fields or an enum. Deserializing it reports every missing field and broken rule together.
///
/// ```
/// use annotated::Deserialize;
///
/// #[derive(Deserialize, Debug)]
/// #[serde(rename_all = "camelCase")]
/// struct NewMember {
/// #[validate(required, length(max = 50))]
/// full_name: String,
/// #[validate(email)]
/// email: String,
/// }
///
/// let mut body = serde_json::Deserializer::from_str(r#"{ "fullName": " " }"#);
/// let error = annotated::from_deserializer::<NewMember, _>(&mut body).unwrap_err();
///
/// assert_eq!(error.to_string(), "fullName: is required\nemail: is missing");
/// ```
///
/// # Serde attributes
///
/// The struct is read as serde's derive would read it, by the names serde gives the struct and its fields.
///
/// - **Supported:** `rename_all`, `rename`, `deny_unknown_fields`, `expecting` and `default` on the struct, and
/// `rename`, `alias`, `default`, `skip_deserializing`, `skip`, `deserialize_with`, `with`, `borrow` and `flatten` on a
/// field.
/// - **Accepted and ignored:** attributes that only change serializing, so that the struct can derive serde's
/// `Serialize` too. These are `into` and `bound(serialize = "...")` on the struct, and `skip_serializing`,
/// `skip_serializing_if`, `serialize_with`, `getter` and `bound(serialize = "...")` on a field. When a `rename` or
/// `rename_all` gives separate names for serializing and deserializing, the deserializing name is the one read.
/// - **Compile errors:** any other serde attribute, and `flatten` in a struct with `deny_unknown_fields`.
///
/// A struct can have lifetime parameters, and its fields borrow from the input as with serde: a `&str` or `&[u8]`
/// field always, any other field with `#[serde(borrow)]`. A value the input can't lend, such as a JSON string with an
/// escape in it, is the format's error, or [`Problem::InvalidType`] under `collect_type_errors`.
///
/// # What ends deserialization
///
/// Unknown fields are ignored, unless the struct denies them. A field that appears twice, an unknown field the struct
/// denies, and a value of the wrong type are each the format's own error, which ends deserialization. A struct with
/// `#[annotated(collect_type_errors)]` reports values of the wrong type as issues instead.
///
/// # How fields are checked
///
/// Once the input is read to its end, every field is checked in the order the struct declares them:
///
/// - A field absent from the input is [`Problem::Missing`], at its name. An `Option` field is `None` instead, as with
/// serde, and `required` on it reports [`Problem::Required`].
/// - A field with `#[serde(default)]` or `#[serde(default = "path")]` takes its default when it is absent. With
/// either on the struct, an absent field without a default of its own takes its value in the struct's default.
/// Its rules check that value like a value read. A `nested` rule checks it with [`Validate`], so the nested type
/// must implement `Validate` too.
/// - A field with `#[serde(skip_deserializing)]` or `#[serde(skip)]` is never read. It takes its default, or
/// `Default::default()` when it has none, and its rules check that value the same way. A key with its name is an
/// unknown field.
/// - A field with `#[serde(deserialize_with = "path")]` or `#[serde(with = "module")]` is read by that function, and
/// its rules check the value the function returns. A `nested` rule checks it with [`Validate`]. As with serde, the
/// field is [`Problem::Missing`] when it is absent, even an `Option`, unless it has a default.
/// - A field with `#[serde(flatten)]` is read, as with serde, from the keys that aren't the struct's own fields, once
/// the input is read. Its issues are at the struct's own location, where its keys are in the input. A flattened
/// `Option` is `None` when its value can't be built from those keys, and the issues found trying are dropped. As
/// with serde, a struct with a flattened field can't be read from a sequence.
/// - A field that is present is checked by its `#[validate(...)]` rules exactly as [`Validate`] checks it. So for input
/// that has every field, the issues are the same, in the same order, as when deserializing with serde and then
/// validating.
/// - A field checked with `nested`, or with `each(...)` holding `nested`, is read through
/// [`Deserialize`](trait@Deserialize):
/// - A field missing inside it is reported at its full path.
/// - The issues inside it are listed where its `nested` rule comes among the field's rules, as [`Validate`]
/// lists them.
/// - Its type must implement `annotated::Deserialize`. The containers that hold such values do: `Option`, `Box`,
/// sequences and maps among them.
/// - When its value couldn't be built, its issues are reported and its other rules are skipped.
/// - A field's rules can name `nested` only once.
/// - Struct-level rules run last, as with [`Validate`], once every field was present and could be built. Otherwise they
/// are skipped, since there is no struct to check.
///
/// ```
/// use annotated::Deserialize;
///
/// #[derive(Deserialize, Debug)]
/// #[serde(rename_all = "camelCase")]
/// struct Address {
/// #[validate(required)]
/// street: String,
/// #[validate(length(min = 5))]
/// postal_code: String,
/// }
///
/// #[derive(Deserialize, Debug)]
/// struct Route {
/// #[validate(each(nested))]
/// stops: Vec<Address>,
/// }
///
/// let body = r#"{ "stops": [{ "street": "Gran Vía 1" }, { "street": "", "postalCode": "28013" }] }"#;
/// let mut body = serde_json::Deserializer::from_str(body);
/// let error = annotated::from_deserializer::<Route, _>(&mut body).unwrap_err();
///
/// assert_eq!(error.to_string(), "stops[0].postalCode: is missing\nstops[1].street: is required");
/// ```
///
/// # Failing fast
///
/// [`from_deserializer_fail_fast`] returns only the first issue, which is the one [`from_deserializer`] would list
/// first. The input is still read to its end, because a field is known to be missing only then. Once it is read, the
/// struct stops checking its fields at the first issue. A nested value is checked while it is read, so its rules
/// may still run.
///
/// # Values of the wrong type
///
/// `#[annotated(collect_type_errors)]` on the struct turns a value of the wrong type into one more issue,
/// [`Problem::InvalidType`] at the field, and deserialization goes on. To make that possible, each field is read in two
/// steps: first into a buffer that holds any well-formed value, then from the buffer as the field's type.
///
/// - The `expected` parameter is what serde says the type expects (`u8`, `a string`, `struct Address`). When serde
/// doesn't say, as when the type rejects the value with a message of its own, it is the type's name.
/// - The `found` parameter is the kind of value in the input (`string`, `integer`, `null`, …), never the value itself.
/// - A name that is no variant of an enum is a [`Problem::UnknownVariant`] instead, whose `expected` parameter lists
/// the names the enum accepts, never the one sent.
/// - A value of the wrong type is checked by no other rule, and the struct-level rules are skipped, as when a field is
/// missing.
/// - A nested struct that collects type errors too reports the ones inside it at their full paths.
/// - The buffer borrows the strings and bytes the format lends.
/// - It needs a self-describing format, such as JSON.
///
/// ```
/// use annotated::Deserialize;
///
/// #[derive(Deserialize, Debug)]
/// #[annotated(collect_type_errors)]
/// struct NewMember {
/// #[validate(email)]
/// email: String,
/// #[validate(range(min = 18))]
/// age: u8,
/// }
///
/// let mut body = serde_json::Deserializer::from_str(r#"{ "email": "lucia", "age": "twelve" }"#);
/// let error = annotated::from_deserializer::<NewMember, _>(&mut body).unwrap_err();
///
/// assert_eq!(error.to_string(), "email: must be an email address\nage: must be u8, found string");
/// ```
///
/// # Enums
///
/// An enum is read as serde reads it, and the variant read is checked as a struct's fields are. Each issue is at the
/// path where its value is in the input: under the variant's name by default, as in `card.number`, at the enum's own
/// location with `#[serde(tag = "type")]`, since the variant's fields sit beside the tag, and under the content's name
/// with `#[serde(tag = "type", content = "data")]`, as in `data.number`. An untagged variant's fields are at the
/// enum's own location. A newtype variant's value is where the variant's content is, and a tuple variant's elements
/// are at their index.
///
/// - The enum takes `tag`, `content`, `untagged`, `rename_all`, `rename_all_fields`, `rename`,
/// `deny_unknown_fields` and `expecting`, and a variant takes `rename`, `alias`, `rename_all`, `untagged`,
/// `skip_deserializing`, `skip`, `other`, `deserialize_with`, `with` and `borrow`, as with serde. A variant's fields
/// take what a struct's fields take. Any other serde attribute on the enum or a variant is a compile error.
/// - A skipped variant is never read: its name is unknown, and its fields need no `Deserialize`. A unit variant with
/// `other` is read for any tag that names no other variant. A variant with `deserialize_with` or `with` is read by
/// the function, and its fields' rules check what the function returns. A `nested` rule checks it with [`Validate`],
/// as for a field read by a function. `borrow` on a newtype variant borrows its value, as on a field.
/// - Without `tag`, a name that is no variant of the enum is the format's error. With `collect_type_errors` on the
/// enum, the enum is buffered whole first, so such a name is a [`Problem::UnknownVariant`] at the enum's location
/// instead, and a value that isn't the enum at all is a [`Problem::InvalidType`] there. A value of the wrong type in
/// a variant's field is an issue at its path, as in a struct.
/// - With `tag`, every key but the tag is buffered, as serde does, and the variant is read from them. A missing tag is
/// [`Problem::Missing`] at the tag's name, and a tag that names no variant is a [`Problem::UnknownVariant`] there,
/// with or without `collect_type_errors`, so reading goes on.
/// - With `tag` and `content`, the content is read straight from the input when the tag comes first, and buffered
/// when it comes after, as with serde. A missing tag, or one that names no variant, is reported at the tag's name as
/// with `tag` alone. Missing content is [`Problem::Missing`] at the content's name, unless the variant needs none: a
/// unit variant, or a newtype variant whose value is an `Option`, which is then `None`.
/// - With `untagged`, the value is buffered, as serde does, and the variants are tried in order. The value is the
/// first variant that can be built, with every field present and of the right type. Its broken rules are reported,
/// and the issues found trying the others are dropped. A value no variant fits is a [`Problem::InvalidType`] at the
/// enum's location, with or without `collect_type_errors`: its `expected` is the enum's `expecting`, or
/// `untagged enum Name`. Variants with `#[serde(untagged)]` in a tagged enum are tried the same way, after the
/// tagged ones.
/// - `#[validate(custom(check))]` on the enum runs after the variant's fields, once the variant could be built.
///
/// ```
/// use annotated::Deserialize;
///
/// #[derive(Deserialize, Debug)]
/// #[serde(rename_all = "camelCase")]
/// enum Payment {
/// Card {
/// #[validate(length(min = 16))]
/// number: String,
/// #[validate(required)]
/// holder: String,
/// },
/// Cash,
/// }
///
/// let mut body = serde_json::Deserializer::from_str(r#"{ "card": { "number": "4111" } }"#);
/// let error = annotated::from_deserializer::<Payment, _>(&mut body).unwrap_err();
///
/// assert_eq!(error.to_string(), "card.number: must be at least 16 characters long\ncard.holder: is missing");
/// ```
pub use Deserialize;
pub use Issue;
pub use Issues;