File: custom_error_default.rs

package info (click to toggle)
rust-derive-builder 0.20.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 500 kB
  • sloc: makefile: 2
file content (49 lines) | stat: -rw-r--r-- 1,165 bytes parent folder | download | duplicates (15)
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
//! This test ensures custom errors don't need a conversion from `UninitializedFieldError`
//! if uninitialized fields are impossible.

#[macro_use]
extern crate derive_builder;

#[derive(Default, Builder)]
#[builder(default, build_fn(validate = "check_person", error = "Error"))]
struct Person {
    name: String,
    age: u16,
}

/// An error that deliberately doesn't have `impl From<UninitializedFieldError>`; as long
/// as `PersonBuilder` uses `Person::default` then missing field errors are never possible.
enum Error {
    UnpopularName(String),
    UnrealisticAge(u16),
}

fn check_age_realistic(age: u16) -> Result<(), Error> {
    if age > 150 {
        Err(Error::UnrealisticAge(age))
    } else {
        Ok(())
    }
}

fn check_name_popular(name: &str) -> Result<(), Error> {
    if name.starts_with('B') {
        Err(Error::UnpopularName(name.to_string()))
    } else {
        Ok(())
    }
}

fn check_person(builder: &PersonBuilder) -> Result<(), Error> {
    if let Some(age) = &builder.age {
        check_age_realistic(*age)?;
    }

    if let Some(name) = &builder.name {
        check_name_popular(name)?;
    }

    Ok(())
}

fn main() {}