wary 0.0.3

A simple validation library
Documentation
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
# Wary

[![<https://img.shields.io/crates/v/wary>](https://img.shields.io/crates/v/wary)](https://crates.io/crates/wary)
[![<https://img.shields.io/docsrs/wary>](https://img.shields.io/docsrs/wary)](https://docs.rs/wary/latest/wary/)
[![ci status](https://github.com/matteopolak/wary/workflows/ci/badge.svg)](https://github.com/matteopolak/wary/actions)

An optionally `no_std` and `no_alloc` validation and transformation library.

- Basic usage
  - [Basic struct example]#basic-struct-example
  - [Basic enum example]#basic-enum-example
- [Accessing context]#context
- [Validation rules]#validation-rules
  - [Implementing custom `Rule`s]#rule-custom
  - [Implementing `Validate` manually]#manual-validate
- [Transformation rules]#transformation-rules
  - [Implementing custom `Modifier`s]#modifier-custom
  - [Implementing `Modify` manually]#manual-modify

### Basic struct example

```rust
use std::borrow::Cow;
use wary::Wary;

#[derive(Wary)]
struct Name<'n>(
  #[validate(alphanumeric, length(chars, 5..=20), equals(not, other = "john"))]
  Cow<'n, str>
);

#[derive(Wary)]
struct Person<'n> {
  #[validate(dive)]
  name: Name<'n>,
  #[validate(range(..=100))]
  age: u8,
}

let mut person = Person {
  name: Name(Cow::Borrowed("jane")),
  age: 25,
};

if let Err(report) = person.wary(&()) {
  eprintln!("invalid person: {report:?}");
}
```

### Basic enum example

```rust
use std::borrow::Cow;
use wary::Wary;

#[derive(Wary)]
struct Name<'n>(
  #[validate(alphanumeric, length(chars, 5..=20), equals(not, other = "john"))]
  #[modify(lowercase(ascii))]
  &'n mut str
);

// for length(bytes)
impl wary::AsRef<[u8]> for Name<'_> {
  fn as_ref(&self) -> &[u8] {
    self.0.as_bytes()
  }
}

#[derive(Wary)]
enum Person<'n> {
  Child {
    #[validate(dive)]
    name: Name<'n>,
    #[validate(range(..=17))]
    age: u8,
  },
  Adult {
    #[validate(dive, length(bytes, ..=32))]
    name: Name<'n>,
    #[validate(range(18..=100))]
    age: u8,
  },
}

let mut name = "Jane".to_string();
let mut person = Person::Adult {
  name: Name(&mut name),
  age: 25,
};

if let Err(report) = person.wary(&()) {
  eprintln!("invalid person: {report:?}");
} else {
  let Person::Adult { name, age } = person else {
    unreachable!();
  };

  assert_eq!(name.0, "jane");
}
```

## Accessing context <a id="context"></a>

```rust
use wary::Wary;
use wary::toolbox::rule::*;
use std::ops::Range;

// allows one context to be passed to all rules
#[derive(AsRef)]
struct Context {
  range: Range<u8>,
  #[as_ref(skip)]
  useless: bool,
}

struct RangeRule<C> {
  ctx: PhantomData<C>,
}

impl<C> RangeRule<C> {
  fn new() -> Self {
    Self {
      ctx: PhantomData,
    }
  }
}

impl<C> wary::Rule<u8> for RangeRule<C>
where
  C: AsRef<Range<u8>>,
{
  type Context = C;

  fn validate(&self, ctx: &Self::Context, item: &u8) -> Result<()> {
    if ctx.as_ref().contains(item) {
      Ok(())
    } else {
      Err(wary::Error::with_message("out_of_range", "The number is out of range"))
    }
  }
}

#[allow(non_camel_case_types)]
mod rule {
  pub type range<C> = super::RangeRule<C>;
}

#[derive(Wary)]
#[wary(context = Context)]
struct Age {
  #[validate(custom(range))]
  number: u8,
}

# fn main() {}
```

## Validation rules

Validation rules applied through the proc-macro `Wary` attribute are (for the most part) simply forwarded
directly to their respective builders inside the [`rule`](crate::options::rule) module. As a result of this
decision, all rules (except `and`, `or`, `inner`, and `dive`) will have auto-completion when writing macro attributes!

If you're providing no options to a rule, you can omit the parentheses. For example: `#[validate(alphanumeric)]`
and `#[validate(alphanumeric())]` are equivalent.

| rule | trait | feature |
| ---- | ----- | ------- |
| [`addr`]#rule-addr | [`AsRef<str>`]wary::AsRef | - |
| [`alphanumeric`]#rule-alphanumeric | [`AsRef<str>`]wary::AsRef | - |
| [`ascii`]#rule-ascii | [`AsRef<str>`]wary::AsRef | - |
| [`contains`]#rule-contains | [`AsSlice`]wary::AsSlice | - |
| [`custom`]#rule-custom | [`Rule<T>`]wary::Rule | - |
| [`dive`]#rule-dive | [`Validate`]wary::Validate | - |
| [`email`]#rule-email | [`AsRef<str>`]wary::AsRef | `email` |
| [`equals`]#rule-equals | [`std::cmp::PartialEq`]std::cmp::PartialEq | - |
| [`func`]#rule-func | `Fn(&T) -> Result<(), wary::Error>` | - |
| [`inner`]#rule-inner | [`AsSlice`]wary::AsSlice | - |
| [`length`]#rule-length | [`Length`]wary::Length | `graphemes` (optional, for `graphemes` length) |
| [`lowercase`]#rule-lowercase | [`AsRef<str>`]wary::AsRef | - |
| [`prefix`]#rule-prefix | [`AsSlice`]wary::AsSlice | - |
| [`range`]#rule-range | [`Range`]wary::Range | - |
| [`regex`]#rule-regex | [`AsRef<str>`]wary::AsRef | `regex` |
| [`required`]#rule-required | [`AsSlice`]wary::AsSlice | - |
| [`semver`]#rule-semver | [`AsRef<str>`]wary::AsRef | `semver` |
| [`suffix`]#rule-suffix | [`AsSlice`]wary::AsSlice | - |
| [`uppercase`]#rule-uppercase | [`AsRef<str>`]wary::AsRef | - |
| [`url`]#rule-url | [`AsRef<str>`]wary::AsRef | `url` |

### `addr`

Validates an address (currently only an IP).

```rust
use wary::Wary;

#[derive(Wary)]
struct Packet {
  #[validate(addr(ipv4))]
  src: String,
  #[validate(addr(ipv6))]
  dest: String,
  #[validate(addr(ip))]
  more: String,
}
```

### `alphanumeric`

Validates that the input is alphanumeric.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name {
  #[validate(alphanumeric)]
  left: String,
  #[validate(alphanumeric(ascii))]
  right: String,
}
```

### `ascii` <a id="rule-ascii"></a>

Validates that the input is ascii.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name(
  #[validate(ascii)]
  String
);
```

### `contains` <a id="rule-contains"></a>

Validates that the input contains a substring or subslice.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name(
  #[validate(contains(str = "hello"))]
  String
);
```

### `custom` <a id="rule-custom"></a>

Validates the input with a custom [`Rule`](wary::Rule).

```rust
use wary::Wary;
use wary::toolbox::rule::*;

struct SecretRule;

impl SecretRule {
  fn new() -> Self {
    Self
  }
}

impl<I> wary::Rule<I> for SecretRule
where
  I: AsRef<str>,
{
  type Context = ();

  fn validate(&self, _ctx: &Self::Context, item: &I) -> Result<()> {
    let string = item.as_ref();

    if string.contains("secret") {
      Err(Error::with_message("secret_found", "You cannot use the word 'secret'"))
    } else {
      Ok(())
    }
  }
}

#[allow(non_camel_case_types)]
mod rule {
  pub type secret = super::SecretRule;
}

#[derive(Wary)]
struct Person {
  #[validate(custom(secret))]
  name: String,
}

# fn main() {}
```

### `dive` <a id="rule-dive"></a>

Validates the inner fields of a struct or enum.

```rust
use wary::Wary;

#[derive(Wary)]
struct Item {
  #[validate(ascii)]
  name: &'static str,
}

#[derive(Wary)]
struct Name {
  #[validate(dive)]
  item: Item,
}
```

### `email` (requires feature `email`) <a id="rule-email"></a>

Validates that the input is an email.

```rust
use wary::Wary;

#[derive(Wary)]
struct Email(
  #[validate(email)]
  String
);
```

### `equals` <a id="rule-equals"></a>

Validates that the input is equal to a value. Currently does not support `self` fields.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name(
  #[validate(equals(other = "John"))]
  String
);
```

### `func` <a id="rule-func"></a>

Validates the input with a function.

```rust
use wary::{Wary, Error};

fn check(_ctx: &(), name: &str) -> Result<(), Error> {
  if name.len() > 5 {
    Ok(())
  } else {
    Err(Error::with_message("name_too_short", "Your name must be longer than 5 characters"))
  }
}

#[derive(Wary)]
struct Name {
  #[validate(func = |ctx: &(), name: &str| {
    if name.len() > 5 {
      Ok(())
    } else {
      Err(Error::with_message("name_too_short", "Your name must be longer than 5 characters"))
    }
  })]
  left: String,
  #[validate(func = check)]
  right: String,
}
```

### `inner` <a id="rule-inner"></a>

Validates the inner fields of a slice-like type.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name {
  #[validate(inner(ascii))]
  items: Vec<String>,
}
```

### `length` <a id="rule-length"></a>

Validates the length of the input.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name {
  // counts the length in bytes
  #[validate(length(bytes, 5..=20))]
  bytes: String,
  // counts the length in characters
  #[validate(length(chars, 5..=20))]
  chars: String,
  // counts the length in UTF-16 code units
  #[validate(length(code_units, 5..=20))]
  code_points: String,
  // counts the length in grapheme clusters
  #[validate(length(graphemes, 5..=20))]
  graphemes: String,
}
```

### `lowercase` <a id="rule-lowercase"></a>

Validates that the input is lowercase.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name {
  #[validate(lowercase)]
  left: String,
  #[validate(lowercase(ascii))]
  right: String,
}
```

### `prefix` <a id="rule-prefix"></a>

Validates that the input starts with a substring or subslice.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name(
  #[validate(prefix(str = "hello"))]
  String
);
```

### `range` <a id="rule-range"></a>

Validates that the input is within a range.

```rust
use wary::Wary;

#[derive(Wary)]
struct Age {
  #[validate(range(18..=100))]
  number: u8,
  #[validate(range('a'..='z'))]
  char: char,
  #[validate(range("hello".."world"))]
  string: String,
}
```

### `regex` (requires feature `regex`) <a id="rule-regex"></a>

Validates that the input matches a regex.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name(
  #[validate(regex(pat = "^[a-z]+$"))]
  String
);
```

### `required` <a id="rule-required"></a>

Validates that the input is not empty. For example, that an `Option` is `Some` or a `Vec` is not empty.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name {
  #[validate(required)]
  first: String,
  #[validate(required)]
  last: Option<String>,
}
```

### `semver` (requires feature `semver`) <a id="rule-semver"></a>

Validates that the input is a semver.

```rust
use wary::Wary;

#[derive(Wary)]
struct Version(
  #[validate(semver)]
  String
);
```

### `suffix` <a id="rule-suffix"></a>

Validates that the input ends with a substring or subslice.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name(
  #[validate(suffix(str = "hello"))]
  String
);
```

### `uppercase` <a id="rule-uppercase"></a>

Validates that the input is uppercase.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name {
  #[validate(uppercase)]
  left: String,
  #[validate(uppercase(ascii))]
  right: String,
}
```

### `url` (requires feature `url`) <a id="rule-url"></a>

Validates that the input is a url.

```rust
use wary::Wary;

#[derive(Wary)]
struct Url(
  #[validate(url)]
  String
);
```

### Implementing `Validate` manually <a id="manual-validate"></a>

In the rare case you need to manually implement `Validate`, you will need to keep in mind about reporting errors properly.

```rust
use wary::{Validate, Error, error::{Path, Report}};

struct Name {
  value: String,
}

impl Validate for Name {
  type Context = ();

  fn validate_into(&self, _ctx: &Self::Context, parent: &Path, report: &mut Report) {
    if self.value.len() < 5 {
      report.push(
        parent.append("value"),
        Error::with_message("name_too_short", "Your name must be longer than 5 characters"),
      );
    }
  }
}

let name = Name {
  value: "Jane".to_string(),
};

assert!(name.validate(&()).is_err());

let longer = Name {
  value: "Jane Doe".to_string(),
};

assert!(longer.validate(&()).is_ok());
```

## Transformation rules

Transformation rules are applied similarly to validation rules, but are implemented in the [`Modify`](wary::Modify) trait instead.

| rule | trait | feature |
| ---- | ----- | ------- |
| [`custom`]#modifier-custom | [`Modifier`]wary::Modifier | - |
| [`lowercase`]#modifier-lowercase | [`AsMut<str>`]wary::AsMut (for `ascii` only) | - |
| [`inner`]#modifier-inner | [`AsMutSlice`]wary::AsMutSlice | - |
| [`uppercase`]#modifier-uppercase | [`AsMut<str>`]wary::AsMut (for `ascii` only) | - |

### `custom` <a id="modifier-custom"></a>

Transforms the input with a custom [`Modifier`](wary::Modifier).

```rust
use wary::{Wary, Modifier};

struct SecretModifier;

impl SecretModifier {
  fn new() -> Self {
    Self
  }
}

impl Modifier<String> for SecretModifier {
  type Context = ();

  fn modify(&self, _ctx: &Self::Context, item: &mut String) {
    item.clear();
    item.push_str("secret");
  }
}

#[allow(non_camel_case_types)]
mod modifier {
  pub type secret = super::SecretModifier;
}

#[derive(Wary)]
struct Person {
  #[modify(custom(secret))]
  name: String,
}

# fn main() {}
```

### `lowercase` <a id="modifier-lowercase"></a>

Transforms the input to lowercase.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name {
  #[modify(lowercase)]
  left: String,
  #[modify(lowercase(ascii))]
  right: String,
}
```

### `inner` <a id="modifier-inner"></a>

Transforms the inner fields of a slice-like type.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name {
  #[modify(inner(lowercase))]
  items: Vec<String>,
}
```

### `uppercase` <a id="modifier-uppercase"></a>

Transforms the input to uppercase.

```rust
use wary::Wary;

#[derive(Wary)]
struct Name {
  #[modify(uppercase)]
  left: String,
  #[modify(uppercase(ascii))]
  right: String,
}
```

### Implementing `Modify` manually <a id="manual-modify"></a>

```rust
use wary::Modify;

struct Name {
  value: String,
}

impl Modify for Name {
  type Context = ();

  fn modify(&mut self, _ctx: &Self::Context) {
    self.value.make_ascii_lowercase();
  }
}

let mut name = Name {
  value: "Jane".to_string(),
};

name.modify(&());

assert_eq!(name.value, "jane");
```