refined_type 0.5.2

A library for imbuing rules into types and elevating them to more robust types
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
# Refined-Type

**refined-type** is a library developed for Rust. It enhances your types, making them more robust and expanding the
range of guarantees your applications can statically ensure.

# Overview

You can create various rules for a certain type, such as phone numbers, addresses, times, and so on.
Once you have established the rules, you can easily combine them.
Specifically, if you create rules for 'non-empty strings' and 'strings composed only of alphabets,' you do not need to
redefine a new rule for 'non-empty strings composed only of alphabets'.
All rules can be arbitrarily combined and extended as long as the target type matches. Enjoy a wonderful type life!

# Example Usage

As an example, let's convert from JSON to a struct.

```rust
// define the constraints you expect by combining 'Refined' and 'Rule'.
type MyNonEmptyString = Refined<NonEmptyRule<String>>;
type MyNonEmptyVec<T> = Refined<NonEmptyRule<Vec<T>>>;

// define a struct for converting from JSON.
#[derive(Debug, Eq, PartialEq, Deserialize)]
struct Human {
    name: MyNonEmptyString,
    friends: MyNonEmptyVec<String>,
}

fn example_1() -> anyhow::Result<()> {
    let json = json! {{
        "name": "john",
        "friends": ["tom", "taro"]
    }}
        .to_string();

    let actual = serde_json::from_str::<Human>(&json)?;
    let expected = Human {
        name: MyNonEmptyString::new("john".to_string())?,
        friends: MyNonEmptyVec::new(vec!["tom".to_string(), "taro".to_string()])?,
    };
    assert_eq!(actual, expected);
    Ok(())
}

// In the second example, while `friends` meets the rule, `name` does not, causing the conversion from JSON to fail
fn example_2() -> anyhow::Result<()> {
    let json = json! {{
        "name": "",
        "friends": ["tom", "taro"]
    }}
        .to_string();

    // because `name` is empty
    assert!(serde_json::from_str::<Human>(&json).is_err());
    Ok(())
}

// In the third example, while `name` satisfies the rule, `friends` does not, causing the conversion from JSON to fail.
fn example_3() -> anyhow::Result<()> {
    let json = json! {{
        "name": "john",
        "friends": []
    }}
        .to_string();

    // because `friends` is empty
    assert!(serde_json::from_str::<Human>(&json).is_err());
    Ok(())
}
```

# Installation

```shell
cargo add refined_type
```

# Custom Rule

There are many situations where you may want to define custom rules.
To define rules for a specific target type, you first need to define a struct.
In the struct, define fields for specifying detailed conditions.
Once the definition is complete, all you need to do is implement the Rule trait.
Add your preferred conditions as you like.

```rust
fn example_4() -> anyhow::Result<()> {
    let non_empty_string_result = Refined::<NonEmptyStringRule>::new("Hello World".to_string())?;
    assert_eq!(non_empty_string_result.into_value(), "Hello World");

    let empty_string_result = Refined::<NonEmptyStringRule>::new("".to_string());
    assert!(empty_string_result.is_err())
    Ok(())
}
```

# Compose Rules

As mentioned earlier, it is possible to combine any rules as long as the target types match.
In the example below, there are standalone rules for 'strings containing Hello' and 'strings containing World'.
Since their target type is String, combining them is possible.
I have prepared something called Rule Composer (`And`, `Or`, `Not`).
By using Rule Composer, composite rules can be easily created.

### Original Rules

```rust
struct ContainsHelloRule;

struct ContainsWorldRule;

impl Rule for ContainsHelloRule {
    type Item = String;

    fn validate(target: &Self::Item) -> Result<(), Error> {
        if target.contains("Hello") {
            Ok(())
        } else {
            Err(Error::new(format!("{} does not contain `Hello`", target)))
        }
    }
}

impl Rule for ContainsWorldRule {
    type Item = String;

    fn validate(target: &Self::Item) -> Result<(), Error> {
        if target.contains("World") {
            Ok(())
        } else {
            Err(Error::new(format!("{} does not contain `World`", target)))
        }
    }
}
```

### 1: `And` Rule Composer

`And` Rule Composer is a rule that satisfies both of the two rules.
It is generally effective when you want to narrow down the condition range.

```rust
fn example_5() {
    type HelloAndWorldRule = And<ContainsHelloRule, ContainsWorldRule>;

    let rule_ok = Refined::<HelloAndWorldRule>::new("Hello! World!".to_string());
    assert!(rule_ok.is_ok());

    let rule_err = Refined::<HelloAndWorldRule>::new("Hello, world!".to_string());
    assert!(rule_err.is_err());
}
```

### 2: `Or` Rule Composer

`Or` Rule Composer is a rule that satisfies either of the two rules.
It is generally effective when you want to expand the condition range.

```rust
fn example_6() {
    type HelloOrWorldRule = Or<ContainsHelloRule, ContainsWorldRule>;

    let rule_ok_1 = Refined::<HelloOrWorldRule>::new("Hello! World!".to_string());
    assert!(rule_ok_1.is_ok());

    let rule_ok_2 = Refined::<HelloOrWorldRule>::new("hello World!".to_string());
    assert!(rule_ok_2.is_ok());

    let rule_err = Refined::<HelloOrWorldRule>::new("hello, world!".to_string());
    assert!(rule_err.is_err());
}
```

### 3: `Not` Rule Composer

`Not` Rule Composer is a rule that does not satisfy a specific condition.
It is generally effective when you want to discard only certain situations.

```rust
fn example_7() {
    type NotHelloRule = Not<ContainsHelloRule>;

    let rule_ok = Refined::<NotHelloRule>::new("hello! World!".to_string());
    assert!(rule_ok.is_ok());

    let rule_err = Refined::<NotHelloRule>::new("Hello, World!".to_string());
    assert!(rule_err.is_err());
}
```

### 4: Compose Rule Composer

Rule Composer is also a rule.
Therefore, it can be treated much like a composite function

```rust
struct StartsWithHelloRule;

struct StartsWithByeRule;

struct EndsWithJohnRule;

impl Rule for StartsWithHelloRule {
    type Item = String;

    fn validate(target: &Self::Item) -> Result<(), Error> {
        if target.starts_with("Hello") {
            Ok(())
        } else {
            Err(Error::new(format!("{} does not start with `Hello`", target)))
        }
    }
}

impl Rule for StartsWithByeRule {
    type Item = String;

    fn validate(target: &Self::Item) -> Result<(), Error> {
        if target.starts_with("Bye") {
            Ok(())
        } else {
            Err(Error::new(format!("{} does not start with `Bye`", target)))
        }
    }
}

impl Rule for EndsWithJohnRule {
    type Item = String;

    fn validate(target: &Self::Item) -> Result<(), Error> {
        if target.ends_with("John") {
            Ok(())
        } else {
            Err(Error::new(format!("{} does not end with `John`", target)))
        }
    }
}

fn example_8() {
    type GreetingRule = And<Or<StartsWithHelloRule, StartsWithByeRule>, EndsWithJohnRule>;

    assert!(GreetingRule::validate(&"Hello! Nice to meet you John".to_string()).is_ok());
    assert!(GreetingRule::validate(&"Bye! Have a good day John".to_string()).is_ok());
    assert!(GreetingRule::validate(&"How are you? Have a good day John".to_string()).is_err());
    assert!(GreetingRule::validate(&"Bye! Have a good day Tom".to_string()).is_err());
}
```

# JSON

`refined_type` is compatible with `serde_json`. This ensures type-safe communication and eliminates the need to write
new validation processes. All you need to do is implement a set of rules once and implement `serde`’s `Serialize`
and `Deserialize`.

### Serialize

```rust
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
struct Human2 {
    name: NonEmptyString,
    age: u8,
}

fn example_9() -> anyhow::Result<()> {
    let john = Human2 {
        name: NonEmptyString::new("john".to_string())?,
        age: 8,
    };

    let actual = json!(john);
    let expected = json! {{
        "name": "john",
        "age": 8
    }};
    assert_eq!(actual, expected);
    Ok(())
}
```

### Deserialize

```rust
fn example_10() -> anyhow::Result<()> {
    let json = json! {{
        "name": "john",
        "age": 8
    }}
        .to_string();

    let actual = serde_json::from_str::<Human2>(&json)?;

    let expected = Human2 {
        name: NonEmptyString::new("john".to_string())?,
        age: 8,
    };
    assert_eq!(actual, expected);
    Ok(())
}
```

# Number

You can also represent the size of numbers as types.
I have prepared macros that can easily define the size of numbers.
Let’s use them to define a `Age` type that is narrowed down to ages 18 to 80.

```rust
greater_rule!((18, u8));
less_rule!((80, u8));
equal_rule!((18, u8), (80, u8));

type Age = Refined<TargetAgeRule>;

// 18 <= age
type TargetAge18OrMore = Or<EqualRule18u8, GreaterRule18u8>;

// age <= 80
type TargetAge80OrLess = Or<EqualRule80u8, LessRule80u8>;

// 18 <= age <= 80
type TargetAgeRule = And<TargetAge18OrMore, TargetAge80OrLess>;
```

# Iterator

I have also prepared several useful refined types for Iterators.

## `ForAll`

`ForAll` is a rule that applies a specific rule to all elements in the Iterator.

```rust
fn example_11() -> anyhow::Result<()> {
    let vec = vec!["Hello".to_string(), "World".to_string()];
    let for_all_ok = ForAll::<NonEmptyStringRule, _>::new(vec.clone())?;
    assert_eq!(vec, for_all_ok.into_value());

    let vec = vec!["Hello".to_string(), "".to_string()];
    let for_all_err = ForAll::<NonEmptyStringRule, _>::new(vec.clone());
    assert!(for_all_err.is_err());
    Ok(())
}
```

## `Exists`

`Exists` is a rule that applies a specific rule to at least one element in the Iterator.

```rust
fn example_12() -> anyhow::Result<()> {
    let vec = vec!["Hello".to_string(), "".to_string()];
    let exists_ok = Exists::<NonEmptyStringRule, _>::new(vec.clone())?;
    assert_eq!(vec, exists_ok.into_value());

    let vec = vec!["".to_string(), "".to_string()];
    let exists_err = Exists::<NonEmptyStringRule, _>::new(vec.clone());
    assert!(exists_err.is_err());
    Ok(())
}
```

---

## `into_iter()` and `iter()`

The Iterator I’ve prepared has `into_iter` and `iter` implemented.
Therefore, you can easily map or convert it to a different Iterator using `collect`.
Feel free to explore the capabilities of the Iterator you’ve been given!

### `into_iter()`

```rust
fn example_11() -> anyhow::Result<()> {
    let ne_vec = NonEmptyVec::new(vec![1, 2, 3])?;
    let ne_vec: NonEmptyVec<i32> = ne_vec.into_iter().map(|n| n * 2).map(|n| n * 3).collect();
    assert_eq!(ne_vec.into_value(), vec![6, 12, 18]);
    Ok(())
}
```

### `iter()`

```rust
fn example_12() -> anyhow::Result<()> {
    let ne_vec = NonEmptyVec::new(vec![1, 2, 3])?;
    let ne_vec: NonEmptyVec<i32> = ne_vec.iter().map(|n| n * 2).map(|n| n * 3).collect();
    assert_eq!(ne_vec.into_value(), vec![6, 12, 18]);
    Ok(())
}
```

### `NonEmptyVec` to `NonEmptyVecDeque` using `collect()`

```rust
fn example_13() -> anyhow::Result<()> {
    let ne_vec = NonEmptyVec::new(vec![1, 2, 3])?;
    let ne_vec_deque: NonEmptyVecDeque<i32> = ne_vec.into_iter().collect();
    assert_eq!(ne_vec_deque.into_value(), vec![1, 2, 3]);
    Ok(())
}
```

# Add Trait

I have implemented the `Add` trait for a part of the `Refined` that I provided. Therefore, operations can be performed
without downgrading the type level.

### NonEmptyString

```rust
fn example_14() -> anyhow::Result<()> {
    let non_empty_string_1 = NonEmptyString::new("Hello".to_string())?;
    let non_empty_string_2 = NonEmptyString::new("World".to_string())?;
    let non_empty_string = non_empty_string_1 + non_empty_string_2; // This is also `NonEmptyString` type

    assert_eq!(non_empty_string.into_value(), "HelloWorld");
    Ok(())
}
```

### NonEmptyVec

```rust
fn example_15() -> anyhow::Result<()> {
    let ne_vec_1 = NonEmptyVec::new(vec![1, 2, 3])?;
    let ne_vec_2 = NonEmptyVec::new(vec![4, 5, 6])?;
    let ne_vec = ne_vec_1 + ne_vec_2; // This is also `NonEmptyVec` type

    assert_eq!(ne_vec.into_value(), vec![1, 2, 3, 4, 5, 6]);
    Ok(())
}
```

# Length

You can impose constraints on objects that have a length, such as `String` or `Vec`.

### String

```rust
fn example_16() -> Result<(), Error> {
    length_greater_than!(5);
    length_equal!(5, 10);
    length_less_than!(10);

    type Password = Refined<From5To10Rule<String>>;

    type From5To10Rule<T> = And<
        Or<LengthEqualRule5<T>, LengthGreaterThanRule5<T>>,
        Or<LengthLessThanRule10<T>, LengthEqualRule10<T>>,
    >;

    // length is 8. so, this is valid
    let raw_password = "password";
    let password = Password::new(raw_password.to_string())?;
    assert_eq!(password.into_value(), "password");

    // length is 4. so, this is invalid
    let raw_password = "pswd";
    let password = Password::new(raw_password.to_string());
    assert!(password.is_err());

    // length is 17. so, this is invalid
    let raw_password = "password password";
    let password = Password::new(raw_password.to_string());
    assert!(password.is_err());

    Ok(())
}
```

### Vec

```rust
#[test]
fn example_17() -> anyhow::Result<()> {
    length_greater_than!(5);
    length_equal!(5, 10);
    length_less_than!(10);

    type Friends = Refined<From5To10Rule<Vec<String>>>;

    type From5To10Rule<T> = And<
        Or<LengthEqualRule5<T>, LengthGreaterThanRule5<T>>,
        Or<LengthLessThanRule10<T>, LengthEqualRule10<T>>,
    >;

    // length is 6. so, this is valid
    let raw_friends = vec![
        "Tom".to_string(),
        "Taro".to_string(),
        "Jiro".to_string(),
        "Hanako".to_string(),
        "Sachiko".to_string(),
        "Yoshiko".to_string(),
    ];
    let friends = Friends::new(raw_friends.clone())?;
    assert_eq!(friends.into_value(), raw_friends);

    // length is 2. so, this is invalid
    let raw_friends = vec!["Tom".to_string(), "Taro".to_string()];
    let friends = Friends::new(raw_friends.clone());
    assert!(friends.is_err());

    // length is 11. so, this is invalid
    let raw_friends = vec![
        "Tom".to_string(),
        "Taro".to_string(),
        "Jiro".to_string(),
        "Hanako".to_string(),
        "Sachiko".to_string(),
        "Yuiko".to_string(),
        "Taiko".to_string(),
        "John".to_string(),
        "Jane".to_string(),
        "Jack".to_string(),
        "Jill".to_string(),
    ];
    let friends = Friends::new(raw_friends.clone());
    assert!(friends.is_err());

    Ok(())
}
```

### Custom Length

You can define a length for any type. Therefore, if you want to implement a length that is not provided
by `refined_type`, you can easily do so using `LengthDefinition`.

```rust
#[test]
fn example_18() -> anyhow::Result<()> {
    length_equal!(5);

    #[derive(Debug, PartialEq)]
    struct Hello;
    impl LengthDefinition for Hello {
        fn length(&self) -> usize {
            5
        }
    }

    let hello = Refined::<LengthEqualRule5<Hello>>::new(Hello)?;
    assert_eq!(hello.into_value(), Hello);
    Ok(())
}
```

# Tips

Directly writing `And`, `Or`, `Not` or `Refined` can often lead to a decrease in readability.
Therefore, using **type aliases** can help make your code clearer.

```rust
type ContainsHelloAndWorldRule = And<ContainsHelloRule, ContainsWorldRule>;

type ContainsHelloAndWorld = Refined<ContainsHelloAndWorldRule>;
```

# License

MIT License

Copyright (c) 2024 Tomoki Someya

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.