File: builder_field_custom.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 (51 lines) | stat: -rw-r--r-- 1,119 bytes parent folder | download | duplicates (2)
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
#[macro_use]
extern crate pretty_assertions;
#[macro_use]
extern crate derive_builder;

use std::num::ParseIntError;

#[derive(Debug, PartialEq, Default, Builder, Clone)]
pub struct Lorem {
    #[builder(field(ty = "Option<usize>", build = self.ipsum.unwrap_or(42) + 1))]
    ipsum: usize,

    #[builder(setter(into), field(ty = "String", build = self.dolor.parse()?))]
    dolor: u32,
}

impl From<ParseIntError> for LoremBuilderError {
    fn from(e: ParseIntError) -> LoremBuilderError {
        LoremBuilderError::ValidationError(e.to_string())
    }
}

#[test]
fn custom_fields() {
    let x = LoremBuilder::default().dolor("7").build().unwrap();

    assert_eq!(
        x,
        Lorem {
            ipsum: 43,
            dolor: 7,
        }
    );

    let x = LoremBuilder::default()
        .ipsum(Some(12))
        .dolor("66")
        .build()
        .unwrap();

    assert_eq!(
        x,
        Lorem {
            ipsum: 13,
            dolor: 66,
        }
    );

    let x = LoremBuilder::default().build().unwrap_err().to_string();
    assert_eq!(x, "cannot parse integer from empty string");
}