derive_builder_fork_arti/
lib.rs

1//! Derive a builder for a struct
2//!
3//! ## **THIS IS A FORK**
4//!
5//! This version of `derive_builder` has an additional `sub_builder` feature,
6//! which [has not been accepted upstream](https://github.com/colin-kiegel/rust-derive-builder/issues/254).
7//! We may add further additional features.
8//!
9//! In other respects, this fork is likely to lag behind the upstream crate.
10//!
11//! This crate implements the [builder pattern] for you.
12//! Just apply `#[derive(Builder)]` to a struct `Foo`, and it will derive an additional
13//! struct `FooBuilder` with **setter**-methods for all fields and a **build**-method
14//! — the way you want it.
15//!
16//! # Quick Start
17//!
18//! Add `derive_builder` as a dependency to you `Cargo.toml`.
19//!
20//! ## What you write
21//!
22//! ```rust
23//! #[macro_use]
24//! extern crate derive_builder;
25//!
26//! #[derive(Builder)]
27//! struct Lorem {
28//!     ipsum: u32,
29//!     // ..
30//! }
31//! # fn main() {}
32//! ```
33//!
34//! ## What you get
35//!
36//! ```rust
37//! # #[macro_use]
38//! # extern crate derive_builder;
39//! # use derive_builder::UninitializedFieldError;
40//! #
41//! # struct Lorem {
42//! #     ipsum: u32,
43//! # }
44//! # fn main() {}
45//! #
46//! #[derive(Clone, Default)]
47//! struct LoremBuilder {
48//!     ipsum: Option<u32>,
49//! }
50//! # // bodge for testing:
51//! # type LoremBuilderError = UninitializedFieldError;
52//!
53//! #[allow(dead_code)]
54//! impl LoremBuilder {
55//!     pub fn ipsum(&mut self, value: u32) -> &mut Self {
56//!         let mut new = self;
57//!         new.ipsum = Some(value);
58//!         new
59//!     }
60//!
61//!     fn build(&self) -> Result<Lorem, LoremBuilderError> {
62//!         Ok(Lorem {
63//!             ipsum: Clone::clone(self.ipsum
64//!                 .as_ref()
65//!                 .ok_or(LoremBuilderError::from(UninitializedFieldError::new("ipsum")))?),
66//!         })
67//!     }
68//! }
69//! ```
70//!
71//! By default all generated setter-methods take and return `&mut self`
72//! (aka _non-conusuming_ builder pattern). Accordingly, the build method also takes a
73//! reference by default.
74//!
75//! You can easily opt into different patterns and control many other aspects.
76//!
77//! The build method returns `Result<T, E>`, where `T` is the struct you started with
78//! and E is a generated builder error type.
79//! It returns `Err` if you didn't initialize all fields and no default values were
80//! provided.
81//!
82//! # Builder Patterns
83//!
84//! Let's look again at the example above. You can now build structs like this:
85//!
86//! ```rust
87//! # #[macro_use] extern crate derive_builder;
88//! # #[derive(Builder)] struct Lorem { ipsum: u32 }
89//! # fn try_main() -> Result<(), Box<dyn std::error::Error>> {
90//! let x: Lorem = LoremBuilder::default().ipsum(42).build()?;
91//! # Ok(())
92//! # } fn main() { try_main().unwrap(); }
93//! ```
94//!
95//! Ok, _chaining_ method calls is nice, but what if `ipsum(42)` should only happen if `geek = true`?
96//!
97//! So let's make this call conditional
98//!
99//! ```rust
100//! # #[macro_use] extern crate derive_builder;
101//! # #[derive(Builder)] struct Lorem { ipsum: u32 }
102//! # fn try_main() -> Result<(), Box<dyn std::error::Error>> {
103//! # let geek = true;
104//! let mut builder = LoremBuilder::default();
105//! if geek {
106//!     builder.ipsum(42);
107//! }
108//! let x: Lorem = builder.build()?;
109//! # Ok(())
110//! # } fn main() { try_main().unwrap(); }
111//! ```
112//!
113//! Now it comes in handy that our setter methods take and return mutable references. Otherwise
114//! we would need to write something more clumsy like `builder = builder.ipsum(42)` to reassign
115//! the return value each time we have to call a setter conditionally.
116//!
117//! Setters with mutable references are therefore a convenient default for the builder
118//! pattern in Rust.
119//!
120//! But this is a free world and the choice is still yours!
121//!
122//! ## Owned, aka Consuming
123//!
124//! Precede your struct (or field) with `#[builder(pattern = "owned")]` to opt into this pattern.
125//! Builders generated with this pattern do not automatically derive `Clone`, which allows builders
126//! to be generated for structs with fields that do not derive `Clone`.
127//!
128//! * Setters take and return `self`.
129//! * PRO: Setter calls and final build method can be chained.
130//! * CON: If you don't chain your calls, you have to create a reference to each return value,
131//!   e.g. `builder = builder.ipsum(42)`.
132//!
133//! ## Mutable, aka Non-Consuming (recommended)
134//!
135//! This pattern is recommended and active by default if you don't specify anything else.
136//! You can precede your struct (or field) with `#[builder(pattern = "mutable")]`
137//! to make this choice explicit.
138//!
139//! * Setters take and return `&mut self`.
140//! * PRO: Setter calls and final build method can be chained.
141//! * CON: The build method must clone or copy data to create something owned out of a
142//!   mutable reference. Otherwise it could not be used in a chain. **(*)**
143//!
144//! ## Immutable
145//!
146//! Precede your struct (or field) with `#[builder(pattern = "immutable")]` to opt into this pattern.
147//!
148//! * Setters take and return `&self`.
149//! * PRO: Setter calls and final build method can be chained.
150//! * CON: If you don't chain your calls, you have to create a reference to each return value,
151//!   e.g. `builder = builder.ipsum(42)`.
152//! * CON: The build method _and each setter_ must clone or copy data to create something owned
153//!   out of a reference. **(*)**
154//!
155//! ## (*) Performance Considerations
156//!
157//! Luckily Rust is clever enough to optimize these clone-calls away in release builds
158//! for your every-day use cases. Thats quite a safe bet - we checked this for you. ;-)
159//! Switching to consuming signatures (=`self`) is unlikely to give you any performance
160//! gain, but very likely to restrict your API for non-chained use cases.
161//!
162//! # More Features
163//!
164//! ## Hidden Fields
165//!
166//! You can hide fields by skipping their setters on (and presence in) the builder struct.
167//!
168//! - Opt-out — skip setters via `#[builder(setter(skip))]` on individual fields.
169//! - Opt-in — set `#[builder(setter(skip))]` on the whole struct
170//!   and enable individual setters via `#[builder(setter)]`.
171//!
172//! The types of skipped fields must implement `Default`.
173//!
174//! ```rust
175//! # #[macro_use]
176//! # extern crate derive_builder;
177//! #
178//! #[derive(Builder)]
179//! struct HiddenField {
180//!     setter_present: u32,
181//!     #[builder(setter(skip))]
182//!     setter_skipped: u32,
183//! }
184//! # fn main() {}
185//! ```
186//!
187//! Alternatively, you can use the more verbose form:
188//!
189//! - `#[builder(setter(skip = true))]`
190//! - `#[builder(setter(skip = false))]`
191//!
192//! ## Custom setters (skip autogenerated setters)
193//!
194//! Similarly to `setter(skip)`, you can say that you will provide your own setter methods.
195//! This simply suppresses the generation of the setter, leaveing the field in the builder,
196//! as `Option<T>`.
197//!
198//! ```rust
199//! # #[macro_use]
200//! # extern crate derive_builder;
201//! #
202//! #[derive(Builder)]
203//! struct SetterOptOut {
204//!     #[builder(setter(custom))]
205//!     custom_setter: u32,
206//! }
207//! impl SetterOptOutBuilder {
208//!     fn custom_setter(&mut self, value: u32) {
209//!         self.custom_setter = Some(value);
210//!     }
211//! }
212//! # fn main() {}
213//! ```
214//!
215//! Again, the more verbose form is accepted:
216//!
217//! - `#[builder(setter(custom = true))]`
218//! - `#[builder(setter(custom = false))]`
219//!
220//! ## Setter Visibility
221//!
222//! Setters are public by default. You can precede your struct (or field) with `#[builder(public)]`
223//! to make this explicit.
224//!
225//! Otherwise precede your struct (or field) with `#[builder(private)]` to opt into private
226//! setters.
227//!
228//! ## Generated builder struct name
229//!
230//! By default, the builder struct for `struct Foo` is `FooBuilder`.
231//! You can override this:
232//!
233//! ```rust
234//! # #[macro_use]
235//! # extern crate derive_builder;
236//! #
237//! #[derive(Builder)]
238//! #[builder(name = "FooConstructor")]
239//! struct Foo { }
240//!
241//! # fn main() -> Result<(), FooConstructorError> {
242//! let foo: Foo = FooConstructor::default().build()?;
243//! # Ok(())
244//! # }
245//! ```
246//!
247//! ## Setter Name/Prefix
248//!
249//! Setter methods are named after their corresponding field by default.
250//!
251//! - You can customize the setter name via `#[builder(setter(name = "foo"))`.
252//! - Alternatively you can set a prefix via `#[builder(setter(prefix = "xyz"))`, which will change
253//!   the method name to `xyz_foo` if the field is named `foo`. Note that an underscore is
254//!   inserted, since Rust favors snake case here.
255//!
256//! Prefixes can also be defined on the struct level, but renames only work on fields. Renames
257//! take precedence over prefix definitions.
258//!
259//! ## Generic Setters
260//!
261//! You can make each setter generic over the `Into`-trait. It's as simple as adding
262//! `#[builder(setter(into))]` to either a field or the whole struct.
263//!
264//! ```rust
265//! # #[macro_use]
266//! # extern crate derive_builder;
267//! #
268//! #[derive(Builder, Debug, PartialEq)]
269//! struct Lorem {
270//!     #[builder(setter(into))]
271//!     pub ipsum: String,
272//! }
273//!
274//! fn main() {
275//!     // `"foo"` will be converted into a `String` automatically.
276//!     let x = LoremBuilder::default().ipsum("foo").build().unwrap();
277//!
278//!     assert_eq!(x, Lorem {
279//!         ipsum: "foo".to_string(),
280//!     });
281//! }
282//! ```
283//!
284//! ## Setters for Option
285//!
286//! You can avoid to user to wrap value into `Some(...)` for field of type `Option<T>`. It's as simple as adding
287//! `#[builder(setter(strip_option))]` to either a field or the whole struct.
288//!
289//! ```rust
290//! # #[macro_use]
291//! # extern crate derive_builder;
292//! #
293//! #[derive(Builder, Debug, PartialEq)]
294//! struct Lorem {
295//!     #[builder(setter(into, strip_option))]
296//!     pub ipsum: Option<String>,
297//!     #[builder(setter(into, strip_option), default)]
298//!     pub foo: Option<String>,
299//! }
300//!
301//! fn main() {
302//!     // `"foo"` will be converted into a `String` automatically.
303//!     let x = LoremBuilder::default().ipsum("foo").build().unwrap();
304//!
305//!     assert_eq!(x, Lorem {
306//!         ipsum: Some("foo".to_string()),
307//!         foo: None
308//!     });
309//! }
310//! ```
311//! If you want to set the value to None when unset, then enable `default` on this field (or do not use `strip_option`).
312//!
313//! Limitation: only the `Option` type name is supported, not type alias nor `std::option::Option`.
314//!
315//! ## Fallible Setters
316//!
317//! Alongside the normal setter methods, you can expose fallible setters which are generic over
318//! the `TryInto` trait. TryInto is a not-yet-stable trait
319//! (see rust-lang issue [#33417](https://github.com/rust-lang/rust/issues/33417)) similar to
320//! `Into` with the key distinction that the conversion can fail, and therefore produces a
321//! `Result`.
322//!
323//! You can only declare the `try_setter` attribute today if you're targeting nightly, and you have
324//! to add `#![feature(try_from)]` to your crate to use it.
325//!
326//! ```rust
327//! # #[macro_use]
328//! # extern crate derive_builder;
329//! #[derive(Builder, Debug, PartialEq)]
330//! #[builder(try_setter, setter(into))]
331//! struct Lorem {
332//!     pub name: String,
333//!     pub ipsum: u8,
334//! }
335//!
336//! #[derive(Builder, Debug, PartialEq)]
337//! struct Ipsum {
338//!     #[builder(try_setter, setter(into, name = "foo"))]
339//!     pub dolor: u8,
340//! }
341//!
342//! fn main() {
343//!    LoremBuilder::default()
344//!        .try_ipsum(1u16).unwrap()
345//!        .name("hello")
346//!        .build()
347//!        .expect("1 fits into a u8");
348//!
349//!    IpsumBuilder::default()
350//!        .try_foo(1u16).unwrap()
351//!        .build()
352//!        .expect("1 fits into a u8");
353//! }
354//! ```
355//!
356//! ## Default Values
357//!
358//! You can define default values for each field via annotation by `#[builder(default = "...")]`,
359//! where `...` stands for any Rust expression and must be string-escaped, e.g.
360//!
361//! * `#[builder(default = "42")]`
362//! * `#[builder(default)]` delegates to the [`Default`] trait of the base type.
363//!
364//! The expression will be evaluated with each call to `build`.
365//!
366//! ```rust
367//! # #[macro_use]
368//! # extern crate derive_builder;
369//! #
370//! #[derive(Builder, Debug, PartialEq)]
371//! struct Lorem {
372//!     #[builder(default = "42")]
373//!     pub ipsum: u32,
374//! }
375//!
376//! fn main() {
377//!     // If we don't set the field `ipsum`,
378//!     let x = LoremBuilder::default().build().unwrap();
379//!
380//!     // .. the custom default will be used for `ipsum`:
381//!     assert_eq!(x, Lorem {
382//!         ipsum: 42,
383//!     });
384//! }
385//! ```
386//!
387//! ### Tips on Defaults
388//!
389//! * The `#[builder(default)]` annotation can be used on the struct level, too. Overrides are
390//!   still possible.
391//! * Delegate to a private helper method on `FooBuilder` for anything fancy. This way
392//!   you will get _much better error diagnostics_ from the rust compiler and it will be _much
393//!   more readable_ for other human beings. :-)
394//! * Defaults will not work while using `#[builder(build_fn(skip))]`. In this case, you'll
395//!   need to handle default values yourself when converting from the builder, such as by
396//!   using `.unwrap_or()` and `.unwrap_or_else()`.
397//!
398//! [`Default`]: https://doc.rust-lang.org/std/default/trait.Default.html
399//!
400//! ```rust
401//! # #[macro_use]
402//! # extern crate derive_builder;
403//! #
404//! # #[derive(Builder, PartialEq, Debug)]
405//! struct Lorem {
406//!     ipsum: String,
407//!     // Custom defaults can delegate to helper methods
408//!     // and pass errors to the enclosing `build()` method via `?`.
409//!     #[builder(default = "self.default_dolor()?")]
410//!     dolor: String,
411//! }
412//!
413//! impl LoremBuilder {
414//!     // Private helper method with access to the builder struct.
415//!     fn default_dolor(&self) -> Result<String, String> {
416//!         match self.ipsum {
417//!             Some(ref x) if x.chars().count() > 3 => Ok(format!("dolor {}", x)),
418//!             _ => Err("ipsum must at least 3 chars to build dolor".to_string()),
419//!         }
420//!     }
421//! }
422//!
423//! # fn main() {
424//! #     let x = LoremBuilder::default()
425//! #         .ipsum("ipsum".to_string())
426//! #         .build()
427//! #         .unwrap();
428//! #
429//! #     assert_eq!(x, Lorem {
430//! #         ipsum: "ipsum".to_string(),
431//! #         dolor: "dolor ipsum".to_string(),
432//! #     });
433//! # }
434//! ```
435//!
436//! You can even reference other fields, but you have to remember that the builder struct
437//! will wrap every type in an Option ([as illustrated earlier](#what-you-get)).
438//!
439//! ## Generic Structs
440//!
441//! ```rust
442//! # #[macro_use]
443//! # extern crate derive_builder;
444//! #
445//! #[derive(Builder, Debug, PartialEq, Default, Clone)]
446//! struct GenLorem<T: Clone> {
447//!     ipsum: &'static str,
448//!     dolor: T,
449//! }
450//!
451//! fn main() {
452//!     let x = GenLoremBuilder::default().ipsum("sit").dolor(42).build().unwrap();
453//!     assert_eq!(x, GenLorem { ipsum: "sit".into(), dolor: 42 });
454//! }
455//! ```
456//!
457//! ## Build Method Customization
458//!
459//! You can rename or suppress the auto-generated build method, leaving you free to implement
460//! your own version. Suppression is done using `#[builder(build_fn(skip))]` at the struct level,
461//! and renaming is done with `#[builder(build_fn(name = "YOUR_NAME"))]`.
462//!
463//! ## Pre-Build Validation
464//!
465//! If you're using the provided `build` method, you can declare
466//! `#[builder(build_fn(validate = "path::to::fn"))]` to specify a validator function which gets
467//! access to the builder before construction. The path does not need to be fully-qualified, and
468//! will consider `use` statements made at module level. It must be accessible from the scope
469//! where the target struct is declared.
470//!
471//! The provided function must have the signature `(&FooBuilder) -> Result<_, String>`;
472//! the `Ok` variant is not used by the `build` method.
473//!
474//! ```rust
475//! # #[macro_use]
476//! # extern crate derive_builder;
477//! #
478//! #[derive(Builder, Debug, PartialEq)]
479//! #[builder(build_fn(validate = "Self::validate"))]
480//! struct Lorem {
481//!     pub ipsum: u8,
482//! }
483//!
484//! impl LoremBuilder {
485//!     /// Check that `Lorem` is putting in the right amount of effort.
486//!     fn validate(&self) -> Result<(), String> {
487//!         if let Some(ref ipsum) = self.ipsum {
488//!             match *ipsum {
489//!                 i if i < 20 => Err("Try harder".to_string()),
490//!                 i if i > 100 => Err("You'll tire yourself out".to_string()),
491//!                 _ => Ok(())
492//!             }
493//!         } else {
494//!             Ok(())
495//!         }
496//!     }
497//! }
498//!
499//! fn main() {
500//!     // If we're trying too hard...
501//!     let x = LoremBuilder::default().ipsum(120).build().unwrap_err();
502//!
503//!     // .. the build will fail:
504//!     assert_eq!(&x.to_string(), "You'll tire yourself out");
505//! }
506//! ```
507//!
508//! Note:
509//! * Default values are applied _after_ validation, and will therefore not be validated!
510//!
511//! ## Additional Trait Derivations
512//!
513//! You can derive additional traits on the builder, including traits defined by other crates:
514//!
515//! ```rust
516//! # #[macro_use]
517//! # extern crate derive_builder;
518//! #
519//! #[derive(Builder, Clone)]
520//! #[builder(derive(Debug, PartialEq, Eq))]
521//! pub struct Lorem {
522//!     foo: u8,
523//!     bar: String,
524//! }
525//!
526//! fn main() {
527//!    assert_eq!(LoremBuilder::default(), LoremBuilder::default());
528//! }
529//! ```
530//!
531//! Attributes declared for those traits are _not_ forwarded to the fields on the builder.
532//!
533//! ## Documentation Comments and Attributes
534//!
535//! `#[derive(Builder)]` copies doc comments and attributes (`#[...]`) from your fields
536//! to the according builder fields and setter-methods, if it is one of the following:
537//!
538//! * `/// ...`
539//! * `#[doc = ...]`
540//! * `#[cfg(...)]`
541//! * `#[allow(...)]`
542//!
543//! The whitelisting minimizes interference with other custom attributes like
544//! those used by Serde, Diesel, or others.
545//!
546//! ```rust
547//! # #[macro_use]
548//! # extern crate derive_builder;
549//! #
550//! #[derive(Builder)]
551//! struct Lorem {
552//!     /// `ipsum` may be any `String` (be creative).
553//!     ipsum: String,
554//!     #[doc = r"`dolor` is the estimated amount of work."]
555//!     dolor: i32,
556//!     // `#[derive(Builder)]` understands conditional compilation via cfg-attributes,
557//!     // i.e. => "no field = no setter".
558//!     #[cfg(target_os = "macos")]
559//!     #[allow(non_snake_case)]
560//!     Im_a_Mac: bool,
561//! }
562//! # fn main() {}
563//! ```
564//!
565//! ### Pass-through Attributes
566//!
567//! You can set attributes on elements of the builder using the `builder_*_attr` attributes:
568//!
569//! - `builder_struct_attr` adds attributes after `#[derive(...)]` on the builder struct.
570//! - `builder_impl_attr` adds attributes on the `impl` block
571//! - `builder_field_attr` adds attributes to field declarations in the builder struct.
572//! - `builder_setter_attr` adds attributes to the setter in the `impl` block.
573//!
574//! ```rust
575//! # #[macro_use]
576//! # extern crate derive_builder;
577//! #
578//! #[derive(Builder)]
579//! #[builder(derive(serde::Serialize))]
580//! #[builder_struct_attr(serde(rename_all = "camelCase"))]
581//! struct Lorem {
582//!     #[builder_field_attr(serde(rename="dolor"))]
583//!     ipsum: String,
584//! }
585//!
586//! # fn main() {
587//! let mut show = LoremBuilder::default();
588//! show.ipsum("sit".into());
589//! assert_eq!(serde_json::to_string(&show).unwrap(), r#"{"dolor":"sit"}"#);
590//! # }
591//! ```
592//!
593//! # Error return type from autogenerated `build` function
594//!
595//! By default, `build` returns an autogenerated error type:
596//!
597//! ```rust
598//! # extern crate derive_builder;
599//! # use derive_builder::{SubfieldBuildError, UninitializedFieldError};
600//! # use std::fmt::{self, Display};
601//! #
602//! #[doc="Error type for LoremBuilder"]
603//! #[derive(Debug)]
604//! #[non_exhaustive]
605//! pub enum LoremBuilderError { // where `LoremBuilder` is the name of the builder struct
606//!     /// Uninitialized field
607//!     UninitializedField(&'static str),
608//!     /// Custom validation error
609//!     ValidationError(String),
610//! }
611//!
612//! impl From<String> for LoremBuilderError {
613//!     fn from(s: String) -> Self { Self::ValidationError(s) }
614//! }
615//! impl From<UninitializedFieldError> for LoremBuilderError { // ...
616//! # fn from(s: UninitializedFieldError) -> Self { todo!() } }
617//! impl<E: std::error::Error> From<SubfieldBuildError<E>> for LoremBuilderError { // ...
618//! # fn from(s: SubfieldBuildError<E>) -> Self { todo!() } }
619//! impl Display for LoremBuilderError { // ...
620//! # fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { todo!() } }
621//! impl std::error::Error for LoremBuilderError {}
622//! ```
623//!
624//! Alternatively, you can specify your own error type:
625//! ```rust
626//! # #[macro_use]
627//! # extern crate derive_builder;
628//! # use derive_builder::UninitializedFieldError;
629//! #
630//! #[derive(Builder, Debug, PartialEq)]
631//! #[builder(build_fn(error = "OurLoremError"))]
632//! struct Lorem {
633//!     pub ipsum: u32,
634//! }
635//!
636//! struct OurLoremError(String);
637//!
638//! impl From<UninitializedFieldError> for OurLoremError {
639//!     fn from(ufe: UninitializedFieldError) -> OurLoremError { OurLoremError(ufe.to_string()) }
640//! }
641//!
642//! # fn main() {
643//! let err: OurLoremError = LoremBuilder::default().build().unwrap_err();
644//! assert_eq!(&err.0, "Field not initialized: ipsum");
645//! # }
646//! ```
647//!
648//! # Sub-fields with builders (nested builders)
649//!
650//! You can nest structs with builders.
651//! The super-struct's builder will contain an instance of the sub-struct's builder
652//! (not wrapped in `Option`).
653//! With the mutable pattern (which is recommended), an accessor method will be generated. instead of a setter.
654//!
655//! The sub-structure's `build` method will be called by the super-structure's `build`.
656//!
657//! ```rust
658//! // Definition
659//!
660//! # #[macro_use]
661//! # extern crate derive_builder;
662//! # use derive_builder::{UninitializedFieldError, SubfieldBuildError};
663//! #[derive(Debug, PartialEq, Default, Builder, Clone)]
664//! #[builder(build_fn(error="BuildError"))]
665//! struct Lorem {
666//!     #[builder(sub_builder)]
667//!     ipsum: Ipsum,
668//! }
669//!
670//! #[derive(Debug, PartialEq, Default, Builder, Clone)]
671//! #[builder(build_fn(error="BuildError"))]
672//! struct Ipsum {
673//!     i: usize,
674//! }
675//!
676//! #[derive(Debug)]
677//! struct BuildError { }
678//! impl From<UninitializedFieldError> for BuildError {
679//! # fn from(e: UninitializedFieldError) -> Self { BuildError { } } }
680//! impl<E> From<SubfieldBuildError<E>> for BuildError {
681//! # fn from(e: SubfieldBuildError<E>) -> Self { BuildError { } } }
682//!
683//! // Use
684//!
685//! # fn main() {
686//! let mut lorem = LoremBuilder::default();
687//! lorem.ipsum().i(42);
688//! let lorem = lorem.build().unwrap();
689//! assert_eq!(lorem,
690//!            Lorem { ipsum: Ipsum { i: 42 } });
691//! # }
692//! ```
693//!
694//! ## Errors from the sub-structure builder
695//!
696//! To allow reporting of which sub-structure failed to build,
697//! the error `E` from the sub-field's builder will be wrapped up with the field name into a [`SubfieldBuildError<E>`].
698//! That `SubfieldBuildError` must be convertible to the super-structure's builder error type (using `Into`).
699//!
700//! It can be helpful to specify a common error type for both the parent and sub-structures,
701//! and manually implement conversions from `SubfieldBuildError` and `UninitializedFieldError`,
702//! as shown in the example.
703//! See also
704//! [Error return type from autogenerated `build` function](#error-return-type-from-autogenerated-build-function).
705//!
706//! ## Adjusting the sub-structure builder name and build function
707//!
708//! ```rust
709//! # #[macro_use]
710//! # extern crate derive_builder;
711//! #[derive(Debug, PartialEq, Default, Builder, Clone)]
712//! struct Lorem {
713//!     #[builder(sub_builder(fn_name = "construct"), field(type = "IpsumConstructor"))]
714//!     ipsum: Ipsum,
715//! }
716//!
717//! #[derive(Debug, PartialEq, Default, Builder, Clone)]
718//! #[builder(name = "IpsumConstructor", build_fn(name = "construct"))]
719//! struct Ipsum {
720//!     i: usize,
721//! }
722//! # fn main() { }
723//! ```
724//!
725//! The default for the field level `builder(sub_builder(fn_name=...))`
726//! is the parent's `builder(build_fn(name=...))`.
727//!
728//! # Completely custom fields in the builder
729//!
730//! Instead of having an `Option`, you can have whatever type you like:
731//!
732//! ```rust
733//! # #[macro_use]
734//! # extern crate derive_builder;
735//! #[derive(Debug, PartialEq, Default, Builder, Clone)]
736//! #[builder(derive(Debug, PartialEq))]
737//! struct Lorem {
738//!     #[builder(setter(into), field(type = "u32"))]
739//!     ipsum: u32,
740//!
741//!     #[builder(field(type = "String", build = "()"))]
742//!     dolor: (),
743//!
744//!     #[builder(field(type = "&'static str", build = "self.amet.parse()?"))]
745//!     amet: u32,
746//! }
747//!
748//! impl From<std::num::ParseIntError> for LoremBuilderError { // ...
749//! #     fn from(e: std::num::ParseIntError) -> LoremBuilderError {
750//! #         e.to_string().into()
751//! #     }
752//! # }
753//!
754//! # fn main() {
755//! let mut builder = LoremBuilder::default();
756//! builder.ipsum(42u16).dolor("sit".into()).amet("12");
757//! assert_eq!(builder, LoremBuilder { ipsum: 42, dolor: "sit".into(), amet: "12" });
758//! let lorem = builder.build().unwrap();
759//! assert_eq!(lorem, Lorem { ipsum: 42, dolor: (), amet: 12 });
760//! # }
761//! ```
762//!
763//! The builder field type (`type =`) must implement `Default`.
764//!
765//! The argument to `build` must be a literal string containing Rust code for the contents of a block, which must evaluate to the type of the target field.
766//! It may refer to the builder struct as `self`, use `?`, etc.
767//!
768//! # **`#![no_std]`** Support (on Nightly)
769//!
770//! You can activate support for `#![no_std]` by adding `#[builder(no_std)]` to your struct
771//! and `#![feature(alloc)] extern crate alloc` to your crate.
772//!
773//! The latter requires the _nightly_ toolchain.
774//!
775//! # Troubleshooting
776//!
777//! ## Gotchas
778//!
779//! - Tuple structs and unit structs are not supported as they have no field
780//!   names.
781//! - Generic setters introduce a type parameter `VALUE: Into<_>`. Therefore you can't use
782//!  `VALUE` as a type parameter on a generic struct in combination with generic setters.
783//! - The `try_setter` attribute and `owned` builder pattern are not compatible in practice;
784//!   an error during building will consume the builder, making it impossible to continue
785//!   construction.
786//! - When re-exporting the underlying struct under a different name, the
787//!   auto-generated documentation will not match.
788//! - If derive_builder depends on your crate, and vice versa, then a cyclic
789//!   dependency would occur. To break it you could try to depend on the
790//!   [`derive_builder_core`] crate instead.
791//!
792//! ## Report Issues and Ideas
793//!
794//! [Open an issue on GitHub](https://github.com/colin-kiegel/rust-derive-builder/issues)
795//!
796//! If possible please try to provide the debugging info if you experience unexpected
797//! compilation errors (see above).
798//!
799//! [builder pattern]: https://web.archive.org/web/20170701044756/https://aturon.github.io/ownership/builders.html
800//! [`derive_builder_core`]: https://crates.io/crates/derive_builder_core
801
802#![deny(warnings)]
803#![cfg_attr(not(feature = "std"), no_std)]
804
805#[cfg(not(feature = "std"))]
806extern crate alloc;
807
808extern crate derive_builder_macro;
809
810mod error;
811
812pub use derive_builder_macro::Builder;
813
814#[doc(inline)]
815pub use error::{SubfieldBuildError, UninitializedFieldError};
816
817#[doc(hidden)]
818pub mod export {
819    pub mod core {
820        #[cfg(not(feature = "std"))]
821        pub use alloc::string;
822        #[cfg(not(feature = "std"))]
823        pub use core::*;
824        #[cfg(feature = "std")]
825        pub use std::*;
826    }
827}