typed-builder-0.23.2/.cargo_vcs_info.json 0000644 00000000136 00000000001 0013671 0 ustar {
"git": {
"sha1": "72f56530e905c31ccc7c2330481e9ba443b91ff0"
},
"path_in_vcs": ""
} typed-builder-0.23.2/.github/dependabot.yml 0000644 0000000 0000000 00000000362 10461020230 0016652 0 ustar 0000000 0000000 version: 2
updates:
- package-ecosystem: "cargo"
directory: "/"
schedule:
interval: "monthly"
open-pull-requests-limit: 10
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "monthly"
typed-builder-0.23.2/.github/workflows/ci.yml 0000644 0000000 0000000 00000011605 10461020230 0017177 0 ustar 0000000 0000000 name: CI
on:
pull_request:
push:
branches: [master]
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
checks: write
jobs:
ci:
name: CI
needs: [test, clippy, docs]
runs-on: ubuntu-latest
steps:
- name: Done
run: exit 0
test:
name: Tests
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
rust: [1.90.0, nightly]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- name: Install rust
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.rust }}
override: true
- name: Ready cache
if: matrix.os == 'ubuntu-latest'
run: sudo chown -R $(whoami):$(id -ng) ~/.cargo/
- name: Cache cargo
uses: actions/cache@v4
id: cache
with:
path: ~/.cargo
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Test typed-builder
uses: actions-rs/cargo@v1
with:
command: test
args: --all-targets
nostd-build:
name: nostd Build
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
rust: [nightly]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- name: Install rust
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.rust }}
override: true
target: aarch64-unknown-none
- name: Ready cache
if: matrix.os == 'ubuntu-latest'
run: sudo chown -R $(whoami):$(id -ng) ~/.cargo/
- name: Cache cargo
uses: actions/cache@v4
id: cache
with:
path: ~/.cargo
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Add rustup components
run: rustup component add rust-src --toolchain nightly-x86_64-unknown-linux-gnu
- name: Build with nostd
uses: actions-rs/cargo@v1
with:
command: build
args: -Zbuild-std=core --target aarch64-unknown-none
fmt:
name: Rustfmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
components: rustfmt
- name: Run fmt --all -- --check
uses: actions-rs/cargo@v1
with:
command: fmt
args: --all -- --check
clippy:
name: Clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
components: clippy
- name: Cache cargo
uses: actions/cache@v4
id: cache
with:
path: ~/.cargo
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Run clippy --all-targets --
uses: actions-rs/clippy-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --all-targets --
docs:
name: Docs
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
- name: Cache cargo
uses: actions/cache@v4
id: cache
with:
path: ~/.cargo
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Run doc tests
uses: actions-rs/cargo@v1
with:
command: test
args: --doc
- name: Check typed-builder docs
uses: actions-rs/cargo@v1
with:
command: doc
args: --no-deps
docs-ghpages:
name: Update Docs in GitHub Pages
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/master'
steps:
- uses: actions/checkout@v5
- name: Build docs
env:
GITHUB_REPO: ${{ github.repository }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |-
cargo doc --verbose &&
echo "" > target/doc/index.html
- name: Add read permissions
run: |-
chmod --recursive +r target/doc
- name: Upload artifact
uses: actions/upload-pages-artifact@v4
with:
path: target/doc
deploy-ghpages:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: docs-ghpages
if: github.ref == 'refs/heads/master'
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
typed-builder-0.23.2/.gitignore 0000644 0000000 0000000 00000000560 10461020230 0014452 0 ustar 0000000 0000000 # Generated by Cargo
# will have compiled files and executables
/target/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
Cargo.lock
# These are backup files generated by rustfmt
**/*.rs.bk
/target/
**/*.rs.bk
Cargo.lock
/typed-builder-macro/target/
typed-builder-0.23.2/CHANGELOG.md 0000644 0000000 0000000 00000032733 10461020230 0014302 0 ustar 0000000 0000000 # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
## 0.23.2 - 2025-11-19
### Fixed
- Clippy warnings for using `&Option<&T>` instead of `Option<&T>`.
## 0.23.1 - 2025-11-16
### Fixed
- Clippy warnings for unused variables in the new default implementation.
## 0.23.0 - 2025-10-20
### Changed
- Upgrae Rust edition to 2024.
- [**BREAKING**] When `default` is an expression that uses previous fields,
it'll receive them as reference.
### Added
- `default_where` option to add generic bounds on `default`.
- `builder_type(attributes(...))` for adding attributes to the builder type
(mainly for `derive`)
### Removed
- [**BREAKING**] The `Optional` trait. This is an internal implementation
detail, but some users may have relied on it for customized flows.
## 0.22.0 - 2025-09-08
### Added
- New optional alternate `transform` syntax using a full fn, to allow support for custom lifetimes, generics and a where clause to custom builder method.
Example:
```rust
#[derive(TypedBuilder)]
struct Foo {
#[builder(
setter(
fn transform<'a, M>(value: impl IntoValue<'a, String, M>) -> String
where
M: std::fmt::Display
{
value.into_value()
},
)
)]
s: String,
}
```
## 0.21.2 - 2025-08-21
### Fixed
- Recognize `TypeGroup` when checking for `Option`.
## 0.21.1 - 2025-08-12
### Fixed
- Strip raw ident prefix from base method name before assembling prefixed/suffixed fallback method names
## 0.21.0 - 2025-03-20
### Added
- Added `ignore_invalid` option to `strip_option` to skip stripping for non-Option fields
- Added `fallback_prefix` and `fallback_suffix` options to `strip_option` for customizing fallback method names
- Added support for field defaults with `strip_option` and its fallback options
### Changed
- Improved handling of `strip_option` to work better with field defaults
- Made `strip_option` more flexible with non-Option fields when `ignore_invalid` is set
## 0.20.1 - 2025-03-14
### Fixed
- Fix mutator with type parameter using associated type (see issue #157)
## 0.20.0 - 2024-08-22
### Added
- Add `#[builder(setter(strip_option(fallback = field_opt)))]` to add a fallback unstripped method to the builder struct.
- Add `#[builder(setter(strip_bool(fallback = field_bool)))]` to add a fallback setter that takes the `bool` value to the builder struct.
## 0.19.1 - 2024-07-14
### Fixed
- Fix mutators for generic fields (see issue #149)
## 0.19.0 - 2024-06-15
### Added
- Use fields' doc comments for the setters.
## 0.18.2 - 2024-04-16
### Fixed
- Also add the licenses to the macro crate.
## 0.18.1 - 2024-01-17
### Fixed
- Add `#[allow(clippy::no_effect_underscore_binding)]` to generated methods
that need to destructure intermediate builder state.
- Use a proper `OR` syntax for the dual license.
## 0.18.0 - 2023-10-19
### Fixed
- `?Sized` generic parameters are now supported.
## 0.17.0 - 2023-10-15
### Changed
- Internal refactor of attribute parsing - results in better error messages and
easier proces for adding new settings.
### Added
- `#[builder(mutators(...))]` to generate functions on builder to mutate fields
- `#[builder(via_mutator)]` on fields to allow defining fields initialized
during `::builder()` for use with `mutators`
- `mutable_during_default_resolution` to allow `default` expression mutate
previous fields.
### Fixed
- Add support for paths with angle brackets (see PR #122 )
## 0.16.2 - 2023-09-22
### Fixed
- Use generics with the constructor in `build` method (see issue #118)
## 0.16.1 - 2023-09-18
### Fixed
- Add `#[allow(clippy::exhaustive_enums)]` to generated empty enums used for
error "reporting" (see issue #112)
- Add `#[automatically_derived]` to generated `impl`s (see issue #114)
- Add `#[allow(clippy::used_underscore_binding)]` to build method and setter
methods (see issue #113)
## 0.16.0 - 2023-08-26
### Added
- `#[builder(crate_module_path = ...)]` for overcoming cases where the derive
macro is used in another crate's macro (see issue #109)
## 0.15.2 - 2023-08-03
### Fixed
- Fix const generics generating "empty" entries in some lists, resulting in
consecutive commas (see issue #106)
## 0.15.1 - 2023-07-10
### Fixed
- no-std build.
## 0.15.0 - 2023-07-06
### Changed
- [**BREAKING**] Split the derive macro out to [a separate procmacro
crate](https://crates.io/crates/typed-builder-macro). This is considered a
breaking change because reexporting and/or renmaing the crate can now prevent
the generated code from finding the types it needs (see issue #101)
### Fixed
- Marking a field as `#[deprecated]` now behaves properly - `TypedBuilder`
generated code itself does trigger the deprecation warning, and instead the
setter for that field now does.
- The "fake" `build` method when required fields are not provided now returns
the never type ("`!`"). Refer to PR #97 for more thorough explanation.
### Added
- Support for setter method prefixes and suffixes `#[builder(field_defaults(setter(prefix = "...", suffix = "...")))]`.
This either prepends or appends the provided string to the setter method. This allows method names like: `set_x()`,
`with_y()`, or `set_z_value()`.
## 0.14.0 - 2023-03-08
### Added
- `build_method(into)` and `build_method(into = ...)`.
## 0.13.0 - 2023-03-05
### Changed
y
- [**BREAKING**] Builder state parameter moved to the end of the generated builder type's parameters list.
- Generated builder type's builder state parameter now defaults to tuple of
empty tuples. This means the empty builder, where no parameter is yet set.
### Fixed
- `#[builder(build_method(...))]` now affects the fake `build` method that's
generated to add information to the compiler error.
## 0.12.0 - 2023-01-29
### Removed
- [**BREAKING**] `builder_method_doc = "..."`, `builder_type_doc = "..."` and
`build_method_doc = "..."` are replaced with `builder_method(doc = "...")`,
`builder_type(doc = "...")` and `build_method(doc = "...")`.
### Added
- `build_method(...)` now has a `doc` field.
- `builder_method(...)` and `builder_type(...)`, which are structured similarly to `build_method(...)`.
## 0.11.0 - 2022-10-29
### Added
- `#[builder(build_method(vis="pub", name=build))]` for customizing visibility and fn name of the final build method
(the default visibility is `pub`, and default build name is `build`)
## 0.10.0 - 2022-02-13
### Added
- `#[builder(setter(strip_bool))]` for making zero arguments setters for `bool` fields that just
set them to `true` (the `default` automatically becomes `false`)
## 0.9.1 - 2021-09-04
### Fixed
- Add `extern crate proc_macro;` to solve some weird problem (https://github.com/idanarye/rust-typed-builder/issues/57)
- Use unambiguous `::` prefixed absolute paths in generated code.
## 0.9.0 - 2021-01-31
### Added
- Builder type implements `Clone` when all set fields support clone.
- `#[builder(setter(transform = ...))]` attribute for running a transform on a
setter's argument to convert them to the field's type.
### Fixed
- Fix code generation for raw identifiers.
## 0.8.0 - 2020-12-06
### Changed
- Upgraded the Rust edition to 2018.
### Added
- `#[field_defaults(...)]` attribute for settings default attributes for all
the fields.
## 0.7.1 - 2020-11-20
### Fixed
- Fix lifetime bounds erroneously preserved in phantom generics.
## 0.7.0 - 2020-07-23
### Added
- Brought back `default_code`, because it needed to resolve conflict with other
custom derive proc-macro crates that try to parse `[#builder(default = ...)]`
attribute in order to decide if they are relevant to them - and fail because
the expect them to be simple literals.
## 0.6.0 - 2020-05-18
### Added
- Ability to use `into` and `strip_option` simultaneously for a field.
### Changed
- [**BREAKING**] Specifying `skip` twice in the same `builder(setter(...))` is
no longer supported. Then again, if you were doing that you probably deserve
having your code broken.
## 0.5.1 - 2020-01-26
### Fixed
- Prevent Clippy from warning about the `panic!()` in the faux build method.
## 0.5.0 - 2020-01-25
### Changed
- [**BREAKING**] Move `doc` and `skip` into a subsetting named `setter(...)`.
This means that `#[builder(doc = "...")]`, for example, should now be written
as `#[builder(setter(doc = "..."))]`.
- [**BREAKING**] Setter arguments by default are no longer automatically
converted to the target type with `into()`. If you want to automatically
convert them, use `#[builder(setter(into))]`. This new default enables rustc
inference for generic types and proper integer literal type detection.
- Improve build errors for incomplete `.build()` and repeated setters, by
creating faux methods with deprecation warnings.
### Added
- `#[builder(setter(strip_option))]` for making setters for `Option` fields
automatically wrap the argument with `Some(...)`. Note that this is a weaker
conversion than `#[builder(setter(into))]`, and thus can still support type
inference and integer literal type detection.
### Removed
- [**BREAKING**] Removed the `default_code` setting (`#[builder(default_code =
"...")]`) because it is no longer required now that Rust and `syn` support
arbitrary expressions in attributes.
## 0.4.1 - 2020-01-17
### Fixed
- [**BREAKING**] now state types are placed before original generic types.
Previously, all state types are appended to generic arguments. For example,
`Foo<'a, X, Y>` yields `FooBuilder<'a, X, Y, ((), ())>` **previously**, and
now it becomes `FooBuilder<'a, ((), ()), X, Y, >.`. This change fix compiler error
for struct with default type like `Foo<'a, X, Y=Bar>`. Rust only allow type
parameters with a default to be trailing.
## 0.4.0 - 2019-12-13
### Added
- `#![no_std]` is now supported out of the box. (You don't need to opt into any
features, it just works.)
- [**BREAKING**] a `default_code` expression can now refer to the values of
earlier fields by name (This is extremely unlikely to break your code, but
could in theory due to shadowing)
- `#[builder(skip)]` on fields, to not provide a method to set that field.
- Control of documentation:
- `#[builder(doc = "…")]` on fields, to document the field's method on the
builder. Unlike `#[doc]`, you can currently only have one value rather than
one attribute per line; but that's not a big deal since you don't get to
use the `///` sugar anyway. Just use a multiline string.
- `#[builder(doc, builder_method_doc = "…", builder_type_doc = "…",
build_method_doc = "…")]` on structs:
- `doc` unhides the builder type from the documentation.
- `builder_method_doc = "…"` replaces the default documentation that
will be generated for the builder() method of the type for which the
builder is being generated.
- `builder_type_doc = "…"` replaces the default documentation that will
be generated for the builder type. Implies `doc`.
- `build_method_doc = "…"` replaces the default documentation that will
be generated for the build() method of the builder type. Implies
`doc`.
### Changed
- [**BREAKING**] Renamed the generated builder type from
`TypedBuilder_BuilderFor_Foo` to `FooBuilder`, for improved ergonomics,
especially when you enable documentation of the builder type.
- Generic identifiers were also changed, from `TypedBuilder_genericType_x` to
`__x`. This is still expected to avoid all name collisions, but is easier
to read in the builder type docs if you enable them.
- Renamed the conversion helper trait for documentation purposes
(`TypedBuilder_conversionHelperTrait_Foo` to `FooBuilder_Optional`), and
its method name for simpler code.
- [**BREAKING**] `default_code` is now lazily evaluated instead of eagerly; any
side-effects that there might have been will no longer occur. As is usual in
this release, this is very unlikely to affect you.
- The restriction that there be only one `#[builder]` attribute per field has
been lifted. You can now write `#[builder(skip)] #[builder(default)]` instead
of `#[builder(skip, default)]` if you want to. As was already the case,
latest definition wins.
- [**BREAKING**] Use a single generic parameter to represent the builder type's
state (see issue #21). Previously we would use a parameter for each field.
### Changed
- Move to dual license - MIT/Apache-2.0. Previously this project was just MIT.
## 0.3.0 - 2019-02-19
### Added
- `#[builder(default_code = "...")]` syntax for defaults that cannot be parsed
as attributes no matter what.
### Changed
- Move the docs from the crate to the custom derive proc macro.
## 0.2.0 - 2019-02-06
### Changed
- Upgraded `syn` version to support Rust 2018.
- [**BREAKING**] Changed attribute style to `#[builder(...)]`:
- `#[default]` -> `#[builder(default)]`
- `#[default=...]` -> `#[builder(default=...)]`
- [**BREAKING**] `default` no longer needs to be a string.
- But you need to change your code anyways because the attribute style was changed.
## 0.1.1 - 2018-07-24
### Fixed
- Allow missing docs in structs that derive `TypedBuilder`.
## 0.1.0 - 2017-10-05
### Added
- Custom derive for generating the builder pattern.
- All setters are accepting `Into` values.
- Compile time verification that all fields are set before calling `.build()`.
- Compile time verification that no field is set more than once.
- Ability to annotate fields with `#[default]` to make them optional and specify a default value when the user does not set them.
- Generates simple documentation for the `.builder()` method.
typed-builder-0.23.2/Cargo.lock 0000644 00000002525 00000000001 0011650 0 ustar # This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "proc-macro2"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
dependencies = [
"proc-macro2",
]
[[package]]
name = "syn"
version = "2.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e96b79aaa137db8f61e26363a0c9b47d8b4ec75da28b7d1d614c2303e232408b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "typed-builder"
version = "0.23.2"
dependencies = [
"typed-builder-macro",
]
[[package]]
name = "typed-builder-macro"
version = "0.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "076a02dc54dd46795c2e9c8282ed40bcfb1e22747e955de9389a1de28190fb26"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
typed-builder-0.23.2/Cargo.toml 0000644 00000003105 00000000001 0011666 0 ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
name = "typed-builder"
version = "0.23.2"
authors = [
"IdanArye ",
"Chris Morgan ",
]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Compile-time type-checked builder derive"
documentation = "https://idanarye.github.io/rust-typed-builder/"
readme = "README.md"
keywords = ["builder"]
categories = ["rust-patterns"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/idanarye/rust-typed-builder"
[lib]
name = "typed_builder"
path = "src/lib.rs"
[[example]]
name = "complicate_build"
path = "examples/complicate_build.rs"
[[example]]
name = "example"
path = "examples/example.rs"
[[example]]
name = "example_for_linting"
path = "examples/example_for_linting.rs"
[[example]]
name = "example_prefix_suffix"
path = "examples/example_prefix_suffix.rs"
[[test]]
name = "no_std"
path = "tests/no_std.rs"
[[test]]
name = "no_type_leakage"
path = "tests/no_type_leakage.rs"
[[test]]
name = "tests"
path = "tests/tests.rs"
[dependencies.typed-builder-macro]
version = "=0.23.2"
typed-builder-0.23.2/Cargo.toml.orig 0000644 0000000 0000000 00000001551 10461020230 0015352 0 ustar 0000000 0000000 [workspace]
members = [".", "./typed-builder-macro"]
[workspace.package]
description = "Compile-time type-checked builder derive"
version = "0.23.2"
authors = ["IdanArye ", "Chris Morgan "]
edition = "2024"
license = "MIT OR Apache-2.0"
repository = "https://github.com/idanarye/rust-typed-builder"
documentation = "https://idanarye.github.io/rust-typed-builder/"
readme = "README.md"
keywords = ["builder"]
categories = ["rust-patterns"]
[package]
name = "typed-builder"
description.workspace = true
version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
documentation.workspace = true
readme.workspace = true
keywords.workspace = true
categories.workspace = true
[dependencies]
typed-builder-macro = { path = "typed-builder-macro", version = "=0.23.2" }
typed-builder-0.23.2/LICENSE-APACHE 0000644 0000000 0000000 00000025137 10461020230 0014415 0 ustar 0000000 0000000 Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
typed-builder-0.23.2/LICENSE-MIT 0000644 0000000 0000000 00000001777 10461020230 0014131 0 ustar 0000000 0000000 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.
typed-builder-0.23.2/README.md 0000644 0000000 0000000 00000007556 10461020230 0013755 0 ustar 0000000 0000000 [](https://github.com/idanarye/rust-typed-builder/actions)
[](https://crates.io/crates/typed-builder)
[](https://idanarye.github.io/rust-typed-builder/)
# Rust Typed Builder
Creates a compile-time verified builder:
```rust
use typed_builder::TypedBuilder;
#[derive(TypedBuilder)]
struct Foo {
// Mandatory Field:
x: i32,
// #[builder(default)] without parameter - use the type's default
// #[builder(setter(strip_option))] - wrap the setter argument with `Some(...)`
#[builder(default, setter(strip_option))]
y: Option,
// Or you can set the default
#[builder(default=20)]
z: i32,
}
```
Build in any order:
```rust
Foo::builder().x(1).y(2).z(3).build();
Foo::builder().z(1).x(2).y(3).build();
```
Omit optional fields(the one marked with `#[default]`):
```rust
Foo::builder().x(1).build()
```
But you can't omit non-optional arguments - or it won't compile:
```rust
Foo::builder().build(); // missing x
Foo::builder().x(1).y(2).y(3); // y is specified twice
```
## Features
* Custom derive for generating the builder pattern.
* Ability to annotate fields with `#[builder(setter(into))]` to make their setters accept `Into` values.
* Compile time verification that all fields are set before calling `.build()`.
* Compile time verification that no field is set more than once.
* Ability to annotate fields with `#[builder(default)]` to make them optional and specify a default value when the user does not set them.
* Generates simple documentation for the `.builder()` method.
* Customizable method name and visibility of the `.build()` method.
## Limitations
* The build errors when you neglect to set a field or set a field describe the actual problem as a deprecation warning, not as the main error.
* The generated builder type has ugly internal name and many generic parameters. It is not meant for passing around and doing fancy builder tricks - only for nicer object creation syntax(constructor with named arguments and optional arguments).
* For the that reason, all builder methods are call-by-move and the builder is not cloneable. Saves the trouble of determining if the fields are cloneable...
* If you want a builder you can pass around, check out [derive-builder](https://crates.io/crates/derive_builder). It's API does not conflict with typed-builder's so you can be able to implement them both on the same type.
## Conflicts
* `TypedBuilder` accepts arbitrary Rust code for `#[builder(default = ...)]`, but other custom derive proc-macro crates may try to parse them using the older restrictions that allow only literals. To solve this, use `#[builder(default_code = "...")]` instead.
## Alternatives - and why typed-builder is better
* [derive-builder](https://crates.io/crates/derive_builder) - does all the checks in runtime, returning a `Result` you need to unwrap.
* [safe-builder-derive](https://crates.io/crates/safe-builder-derive) - this one does compile-time checks - by generating a type for each possible state of the builder. Rust can remove the dead code, but your build time will still be exponential. typed-builder is encoding the builder's state in the generics arguments - so Rust will only generate the path you actually use.
## License
Licensed under either of
* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
additional terms or conditions.
typed-builder-0.23.2/examples/complicate_build.rs 0000644 0000000 0000000 00000003431 10461020230 0020145 0 ustar 0000000 0000000 #![allow(clippy::disallowed_names)]
mod scope {
use typed_builder::TypedBuilder;
#[derive(Debug, PartialEq, TypedBuilder)]
#[builder(build_method(vis="", name=__build))]
pub struct Foo {
// Mandatory Field:
x: i32,
// #[builder(default)] without parameter - use the type's default
// #[builder(setter(strip_option))] - wrap the setter argument with `Some(...)`
#[builder(default, setter(strip_option))]
y: Option,
// Or you can set the default
#[builder(default = 20)]
z: i32,
}
// Customize build method to add complicated logic.
//
// The signature might be frightening at first glance,
// but we don't need to infer this whole ourselves.
//
// We can use `cargo expand` to show code expanded by `TypedBuilder`,
// copy the generated `__build` method, and modify the content of the build method.
#[allow(non_camel_case_types)]
impl<__z, __y> FooBuilder<((i32,), __y, __z)>
where
for<'a> Foo: typed_builder::NextFieldDefault<(&'a i32, __y), Output = Option>,
for<'a> Foo: typed_builder::NextFieldDefault<(&'a i32, &'a Option, __z), Output = i32>,
{
pub fn build(self) -> Bar {
let foo = self.__build();
Bar {
x: foo.x + 1,
y: foo.y.map(|y| y + 1),
z: foo.z + 1,
}
}
}
#[derive(Debug, PartialEq)]
pub struct Bar {
pub x: i32,
pub y: Option,
pub z: i32,
}
}
use scope::{Bar, Foo};
fn main() {
assert_eq!(Foo::builder().x(1).y(2).z(3).build(), Bar { x: 2, y: Some(3), z: 4 });
// This will not compile - because `__build` is a private method
// Foo::builder().x(1).y(2).z(3).__build()
}
typed-builder-0.23.2/examples/example.rs 0000644 0000000 0000000 00000002074 10461020230 0016303 0 ustar 0000000 0000000 use typed_builder::TypedBuilder;
#[derive(Debug, PartialEq, TypedBuilder)]
struct Foo {
/// `x` value.
///
/// This field is mandatory.
x: i32,
// #[builder(default)] without parameter - use the type's default
// #[builder(setter(strip_option))] - wrap the setter argument with `Some(...)`
#[builder(
default,
setter(strip_option, doc = "Set `y`. If you don't specify a value it'll default to no value.",)
)]
y: Option,
// Or you can set the default
#[builder(default = 20)]
z: i32,
}
fn main() {
assert_eq!(Foo::builder().x(1).y(2).z(3).build(), Foo { x: 1, y: Some(2), z: 3 });
// Change the order of construction:
assert_eq!(Foo::builder().z(1).x(2).y(3).build(), Foo { x: 2, y: Some(3), z: 1 });
// Optional fields are optional:
assert_eq!(Foo::builder().x(1).build(), Foo { x: 1, y: None, z: 20 });
// This will not compile - because we did not set x:
// Foo::builder().build();
// This will not compile - because we set y twice:
// Foo::builder().x(1).y(2).y(3);
}
typed-builder-0.23.2/examples/example_for_linting.rs 0000644 0000000 0000000 00000001214 10461020230 0020670 0 ustar 0000000 0000000 #![deny(clippy::all, clippy::pedantic)]
//! This example is mainly to make sure `TypedBuilder` does not do anything that triggers Clippy
//! warnings. It's not for checking behavior.
use typed_builder::TypedBuilder;
#[derive(TypedBuilder)]
struct BigStruct<'a> {
option_with_ref: Option<&'a str>,
#[builder(default = None)]
option_with_default: Option<()>,
}
fn main() {
#[allow(unused)]
let BigStruct {
option_with_ref: option_with_str,
option_with_default: skipped_option,
} = BigStruct::builder()
.option_with_ref(Some("option with string"))
.option_with_default(None)
.build();
}
typed-builder-0.23.2/examples/example_prefix_suffix.rs 0000644 0000000 0000000 00000002231 10461020230 0021237 0 ustar 0000000 0000000 use typed_builder::TypedBuilder;
#[derive(Debug, PartialEq, TypedBuilder)]
#[builder(field_defaults(setter(prefix = "with_", suffix = "_value")))]
struct Foo {
// Mandatory Field:
x: i32,
// #[builder(default)] without parameter - use the type's default
// #[builder(setter(strip_option))] - wrap the setter argument with `Some(...)`
#[builder(default, setter(strip_option))]
y: Option,
// Or you can set the default
#[builder(default = 20)]
z: i32,
}
fn main() {
assert_eq!(
Foo::builder().with_x_value(1).with_y_value(2).with_z_value(3).build(),
Foo { x: 1, y: Some(2), z: 3 }
);
// Change the order of construction:
assert_eq!(
Foo::builder().with_z_value(1).with_x_value(2).with_y_value(3).build(),
Foo { x: 2, y: Some(3), z: 1 }
);
// Optional fields are optional:
assert_eq!(Foo::builder().with_x_value(1).build(), Foo { x: 1, y: None, z: 20 });
// This will not compile - because we did not set x:
// Foo::builder().build();
// This will not compile - because we set y twice:
// Foo::builder().with_x_value(1).with_y_value(2).with_y_value(3);
}
typed-builder-0.23.2/run-retrospective-crate-version-tagging.sh 0000755 0000000 0000000 00000000336 10461020230 0022717 0 ustar 0000000 0000000 #!/bin/bash
(
retrospective-crate-version-tagging detect \
--crate-name typed-builder \
--changelog-path CHANGELOG.md \
--tag-prefix v \
) | retrospective-crate-version-tagging create-releases
typed-builder-0.23.2/rustfmt.toml 0000644 0000000 0000000 00000000020 10461020230 0015052 0 ustar 0000000 0000000 max_width = 130
typed-builder-0.23.2/src/lib.rs 0000644 0000000 0000000 00000043127 10461020230 0014373 0 ustar 0000000 0000000 #![no_std]
/// `TypedBuilder` is not a real type - deriving it will generate a `::builder()` method on your
/// struct that will return a compile-time checked builder. Set the fields using setters with the
/// same name as the struct's fields and call `.build()` when you are done to create your object.
///
/// Trying to set the same fields twice will generate a compile-time error. Trying to build without
/// setting one of the fields will also generate a compile-time error - unless that field is marked
/// as `#[builder(default)]`, in which case the `::default()` value of it's type will be picked. If
/// you want to set a different default, use `#[builder(default=...)]`.
///
/// # Examples
///
/// ```
/// use typed_builder::TypedBuilder;
///
/// #[derive(PartialEq, TypedBuilder)]
/// struct Foo {
/// // Mandatory Field:
/// x: i32,
///
/// // #[builder(default)] without parameter - use the type's default
/// // #[builder(setter(strip_option))] - wrap the setter argument with `Some(...)`
/// #[builder(default, setter(strip_option))]
/// y: Option,
///
/// // Or you can set the default
/// #[builder(default=20)]
/// z: i32,
/// }
///
/// assert!(
/// Foo::builder().x(1).y(2).z(3).build()
/// == Foo { x: 1, y: Some(2), z: 3, });
///
/// // Change the order of construction:
/// assert!(
/// Foo::builder().z(1).x(2).y(3).build()
/// == Foo { x: 2, y: Some(3), z: 1, });
///
/// // Optional fields are optional:
/// assert!(
/// Foo::builder().x(1).build()
/// == Foo { x: 1, y: None, z: 20, });
///
/// // This will not compile - because we did not set x:
/// // Foo::builder().build();
///
/// // This will not compile - because we set y twice:
/// // Foo::builder().x(1).y(2).y(3);
/// ```
///
/// # Customization with attributes
///
/// In addition to putting `#[derive(TypedBuilder)]` on a type, you can specify a `#[builder(...)]`
/// attribute on the type, and on any fields in it.
///
/// On the **type**, the following values are permitted:
///
/// - `doc`: enable documentation of the builder type. By default, the builder type is given
/// `#[doc(hidden)]`, so that the `builder()` method will show `FooBuilder` as its return type,
/// but it won't be a link. If you turn this on, the builder type and its `build` method will get
/// sane defaults. The field methods on the builder will be undocumented by default.
///
/// - `crate_module_path`: This is only needed when `typed_builder` is reexported from another
/// crate - which usually happens when another macro uses it. In that case, it is the
/// reponsibility of that macro to set the `crate_module_path` to the _unquoted_ module path from
/// which the `typed_builder` crate can be accessed, so that the `TypedBuilder` macro will be
/// able to access the typed declared in it.
///
/// Defaults to `#[builder(crate_module_path=::typed_builder)]`.
///
/// - The following subsections:
/// - `builder_method(...)`: customize the builder method that creates the builder type
/// - `builder_type(...)`: customize the builder type
/// - `build_method(...)`: customize the final build method
///
/// All have the same fields:
/// - `vis = "..."`: sets the visibility of the build method, default is `pub`
/// - `name = ...`: sets the fn name of the build method, default is `build`
/// - `doc = "..."` replaces the default documentation that will be generated for the
/// `build()` method of the builder type. Setting this implies `doc`.
///
///
/// - The `build_method(...)` subsection also has:
/// - `into` or `into = ...`: change the output type of the builder. When a specific value/type
/// is set via the assignment, this will be the output type of the builder. If no specific
/// type is set, but `into` is specified, the return type will be generic and the user can
/// decide which type shall be constructed. In both cases an [`Into`] conversion is required to
/// be defined from the original type to the target type.
///
/// - The `builder_type(...)` subsection also has:
/// - `attributes` - for adding attributes to the builder type. Note that the full attribute
/// syntax is required **inside** this section -
/// ```ignore
/// #[builder(builder_type(attributes(
/// #[derive(...)]
/// #[some_other_attribute]
/// )))]
/// ```
///
/// Example:
///
/// ```
/// use typed_builder::TypedBuilder;
///
/// #[derive(TypedBuilder)]
/// #[builder(builder_type(attributes(#[derive(Debug)])))]
/// struct Foo {
/// x: i32,
/// }
/// ```
///
/// - `field_defaults(...)` is structured like the `#[builder(...)]` attribute you can put on the
/// fields and sets default options for fields of the type. If specific field need to revert some
/// options to the default defaults they can prepend `!` to the option they need to revert, and
/// it would ignore the field defaults for that option in that field.
///
/// ```
/// use typed_builder::TypedBuilder;
///
/// #[derive(TypedBuilder)]
/// #[builder(field_defaults(default, setter(strip_option)))]
/// struct Foo {
/// // Defaults to None, options-stripping is performed:
/// x: Option,
///
/// // Defaults to 0, option-stripping is not performed:
/// #[builder(setter(!strip_option))]
/// y: i32,
///
/// // Defaults to Some(13), option-stripping is performed:
/// #[builder(default = Some(13))]
/// z: Option,
///
/// // Accepts params `(x: f32, y: f32)`
/// #[builder(setter(!strip_option, transform = |x: f32, y: f32| Point { x, y }))]
/// w: Point,
/// }
///
/// #[derive(Default)]
/// struct Point { x: f32, y: f32 }
/// ```
///
/// - `mutators(...)` takes functions, that can mutate fields inside of the builder.
/// See [mutators](#mutators) for details.
///
/// On each **field**, the following values are permitted:
///
/// - `default`: make the field optional, defaulting to `Default::default()`. This requires that
/// the field type implement `Default`. Mutually exclusive with any other form of default.
///
/// - `default = ...`: make the field optional, defaulting to the expression `...`.
///
/// - `default_where(...)`: add trait bounds to the default. This means that the `default`
/// expression (or type default) is allowed to rely on these bounds, but the field will not have
/// a default if these trait bounds are not fulfilled.
///
/// Example:
///
/// ```
/// use typed_builder::TypedBuilder;
///
/// #[derive(TypedBuilder)]
/// struct Foo {
/// #[builder(default, default_where(T: Default))]
/// bar: T,
/// }
/// ```
///
/// - `default_code = "..."`: make the field optional, defaulting to the expression `...`. Note that
/// you need to enclose it in quotes, which allows you to use it together with other custom
/// derive proc-macro crates that complain about "expected literal". Note that if `...` contains
/// a string, you can use raw string literals to avoid escaping the double quotes - e.g.
/// `#[builder(default_code = r#""default text".to_owned()"#)]`.
///
/// - `via_mutators`: initialize the field when constructing the builder, useful in combination
/// with [mutators](#mutators).
///
/// - `via_mutators = ...` or `via_mutators(init = ...)`: initialies the field with the expression `...`
/// when constructing the builder, useful in combination with [mutators](#mutators).
///
/// - `mutators(...)` takes functions, that can mutate fields inside of the builder.
/// Mutators specified on a field, mark this field as required, see [mutators](#mutators) for details.
///
/// - `setter(...)`: settings for the field setters. The following values are permitted inside:
///
/// - `doc = "..."`: sets the documentation for the field's setter on the builder type. This will be
/// of no value unless you enable docs for the builder type with `#[builder(doc)]` or similar on
/// the type.
///
/// - `skip`: do not define a method on the builder for this field. This requires that a default
/// be set.
///
/// - `into`: automatically convert the argument of the setter method to the type of the field.
/// Note that this conversion interferes with Rust's type inference and integer literal
/// detection, so this may reduce ergonomics if the field type is generic or an unsigned integer.
///
/// - `strip_option`: for `Option<...>` fields only, this makes the setter wrap its argument with
/// `Some(...)`, relieving the caller from having to do this. Note that with this setting on
/// one cannot set the field to `None` with the setter - so the only way to get it to be `None`
/// is by using `#[builder(default)]` and not calling the field's setter.
///
/// - `strip_option(fallback = field_opt)`: for `Option<...>` fields only. As above this
/// still wraps the argument with `Some(...)`. The name given to the fallback method adds
/// another method to the builder without wrapping the argument in `Some`. You can now call
/// `field_opt(Some(...))` instead of `field(...)`.
///
/// The `setter(strip_option)` attribute supports several `field_defaults` features:
///
/// - `ignore_invalid`: Skip stripping for non-Option fields instead of causing a compile error
/// - `fallback_prefix`: Add a prefix to every fallback method name
/// - `fallback_suffix`: Add a suffix to every fallback method name
///
/// Example:
///
/// ```
/// use typed_builder::TypedBuilder;
///
/// #[derive(TypedBuilder)]
/// #[builder(field_defaults(setter(strip_option(
/// ignore_invalid,
/// fallback_prefix = "opt_",
/// fallback_suffix = "_val"
/// ))))]
/// struct Foo {
/// x: Option, // Can use .x(42) or .opt_x_val(None)
/// y: i32, // Uses .y(42) only since it's not an Option
/// }
/// ```
///
/// - `strip_bool`: for `bool` fields only, this makes the setter receive no arguments and simply
/// set the field's value to `true`. When used, the `default` is automatically set to `false`.
///
/// - `strip_bool(fallback = field_bool)`: for `bool` fields only. As above this allows passing
/// the boolean value. The name given to the fallback method adds another method to the builder
/// without where the bool value can be specified.
///
/// - `transform = |param1: Type1, param2: Type2 ...| expr`: this makes the setter accept
/// `param1: Type1, param2: Type2 ...` instead of the field type itself. The parameters are
/// transformed into the field type using the expression `expr`. The transformation is performed
/// when the setter is called. `transform` can also be provided in full `fn` syntax,
/// to allow custom lifetimes, a generic and a where clause.
/// Example:
/// ```rust
/// #[builder(
/// setter(
/// fn transform<'a, M>(value: impl IntoValue<'a, String, M>) -> String
/// where
/// M: 'a,
/// {
/// value.into_value()
/// },
/// )
/// )]
/// ```
///
/// - `prefix = "..."` prepends the setter method with the specified prefix. For example, setting
/// `prefix = "with_"` results in setters like `with_x` or `with_y`. This option is combinable
/// with `suffix = "..."`.
///
/// - `suffix = "..."` appends the setter method with the specified suffix. For example, setting
/// `suffix = "_value"` results in setters like `x_value` or `y_value`. This option is combinable
/// with `prefix = "..."`.
///
/// - `mutable_during_default_resolution`: when expressions in `default = ...` field attributes
/// are evaluated, this field will be mutable, allowing earlier-defined fields to be mutated by
/// later-defined fields.
/// **Warning** - Use this feature with care! If the field that mutates the previous field in
/// its `default` expression is set via a setter, that mutation will not happen.
///
/// # Mutators
/// Set fields can be mutated using mutators, these can be defind via `mutators(...)`.
///
/// Fields annotated with `#[builder(via_mutators)]` are always available to mutators. Additional fields,
/// that the mutator accesses need to be delcared using `#[mutator(requires = [field1, field2, ...])]`.
/// The mutator will only be availible to call when they are set.
///
/// Mutators on a field, result in them automatically making the field required, i.e., it needs to be
/// marked as `via_mutators`, or its setter be called. Appart from that, they behave identically.
///
/// ```
/// use typed_builder::TypedBuilder;
///
/// #[derive(PartialEq, Debug, TypedBuilder)]
/// #[builder(mutators(
/// // Mutator has only acces to fields marked as `via_mutators`.
/// fn inc_a(&mut self, a: i32){
/// self.a += a;
/// }
/// // Mutator has access to `x` additionally.
/// #[mutator(requires = [x])]
/// fn x_into_b(&mut self) {
/// self.b.push(self.x)
/// }
/// ))]
/// struct Struct {
/// // Does not require explicit `requires = [x]`, as the field
/// // the mutator is specifed on, is required implicitly.
/// #[builder(mutators(
/// fn x_into_b_field(self) {
/// self.b.push(self.x)
/// }
/// ))]
/// x: i32,
/// #[builder(via_mutators(init = 1))]
/// a: i32,
/// #[builder(via_mutators)]
/// b: Vec
/// }
///
/// // Mutators do not enforce only being called once
/// assert_eq!(
/// Struct::builder().x(2).x_into_b().x_into_b().x_into_b_field().inc_a(2).build(),
/// Struct {x: 2, a: 3, b: vec![2, 2, 2]});
/// ```
pub use typed_builder_macro::TypedBuilder;
#[doc(hidden)]
pub trait NextFieldDefault {
type Output;
fn resolve(input: TypedBuilderExistingFields) -> Self::Output;
}
// It'd be nice for the compilation tests to live in tests/ with the rest, but short of pulling in
// some other test runner for that purpose (e.g. compiletest_rs), rustdoc compile_fail in this
// crate is all we can use.
#[doc(hidden)]
/// When a property is non-default, you can't ignore it:
///
/// ```compile_fail
/// use typed_builder::TypedBuilder;
///
/// #[derive(TypedBuilder)]
/// struct Foo {
/// x: i8,
/// }
///
/// let _ = Foo::builder().build();
/// ```
///
/// When a property is skipped, you can't set it:
/// (“method `y` not found for this”)
///
/// ```compile_fail
/// use typed_builder::TypedBuilder;
///
/// #[derive(PartialEq, TypedBuilder)]
/// struct Foo {
/// #[builder(default, setter(skip))]
/// y: i8,
/// }
///
/// let _ = Foo::builder().y(1i8).build();
/// ```
///
/// But you can build a record:
///
/// ```
/// use typed_builder::TypedBuilder;
///
/// #[derive(PartialEq, TypedBuilder)]
/// struct Foo {
/// #[builder(default, setter(skip))]
/// y: i8,
/// }
///
/// let _ = Foo::builder().build();
/// ```
///
/// `skip` without `default` is disallowed:
/// (“error: #[builder(skip)] must be accompanied by default”)
///
/// ```compile_fail
/// use typed_builder::TypedBuilder;
///
/// #[derive(PartialEq, TypedBuilder)]
/// struct Foo {
/// #[builder(setter(skip))]
/// y: i8,
/// }
/// ```
///
/// `clone` does not work if non-Clone fields have already been set
///
/// ```compile_fail
/// use typed_builder::TypedBuilder;
///
/// #[derive(Default)]
/// struct Uncloneable;
///
/// #[derive(TypedBuilder)]
/// struct Foo {
/// x: Uncloneable,
/// y: i32,
/// }
///
/// let _ = Foo::builder().x(Uncloneable).clone();
/// ```
///
/// Same, but with generics
///
/// ```compile_fail
/// use typed_builder::TypedBuilder;
///
/// #[derive(Default)]
/// struct Uncloneable;
///
/// #[derive(TypedBuilder)]
/// struct Foo {
/// x: T,
/// y: i32,
/// }
///
/// let _ = Foo::builder().x(Uncloneable).clone();
/// ```
///
/// Handling deprecated fields:
///
/// ```compile_fail
/// use typed_builder::TypedBuilder;
///
/// #[derive(TypedBuilder)]
/// struct Foo {
/// #[deprecated = "Don't use this!"]
/// #[allow(dead_code)]
/// value: i32,
/// }
///
/// #[deny(deprecated)]
/// Foo::builder().value(42).build();
/// ```
///
/// Handling invalid property for `strip_option`
///
/// ```compile_fail
/// use typed_builder::TypedBuilder;
///
/// #[derive(TypedBuilder)]
/// struct Foo {
/// #[builder(setter(strip_option(invalid_field = "should_fail")))]
/// value: Option,
/// }
/// ```
///
/// Handling multiple properties for `strip_option`
///
/// ```compile_fail
/// use typed_builder::TypedBuilder;
///
/// #[derive(TypedBuilder)]
/// struct Foo {
/// #[builder(setter(strip_option(fallback = value_opt, fallback = value_opt2)))]
/// value: Option,
/// }
/// ```
///
/// Handling alternative properties for `strip_option`
///
/// ```compile_fail
/// use typed_builder::TypedBuilder;
///
/// #[derive(TypedBuilder)]
/// struct Foo {
/// #[builder(setter(strip_option(type = value_opt, fallback = value_opt2)))]
/// value: Option,
/// }
/// ```
///
/// Handling invalid property for `strip_bool`
///
/// ```compile_fail
/// use typed_builder::TypedBuilder;
///
/// #[derive(TypedBuilder)]
/// struct Foo {
/// #[builder(setter(strip_bool(invalid_field = should_fail)))]
/// value: bool,
/// }
/// ```
///
/// Handling multiple propertes for `strip_bool`
///
/// ```compile_fail
/// use typed_builder::TypedBuilder;
///
/// #[derive(TypedBuilder)]
/// struct Foo {
/// #[builder(setter(strip_bool(fallback = value_bool, fallback = value_bool2)))]
/// value: bool,
/// }
/// ```
///
/// Handling alternative propertes for `strip_bool`
///
/// ```compile_fail
/// use typed_builder::TypedBuilder;
///
/// #[derive(TypedBuilder)]
/// struct Foo {
/// #[builder(setter(strip_bool(invalid = value_bool, fallback = value_bool2)))]
/// value: bool,
/// }
/// ```
fn _compile_fail_tests() {}
typed-builder-0.23.2/tests/no_std.rs 0000644 0000000 0000000 00000010712 10461020230 0015460 0 ustar 0000000 0000000 #![warn(clippy::pedantic)]
#![no_std]
use typed_builder::TypedBuilder;
#[test]
fn test_simple() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
x: i32,
y: i32,
}
assert!(Foo::builder().x(1).y(2).build() == Foo { x: 1, y: 2 });
assert!(Foo::builder().y(1).x(2).build() == Foo { x: 2, y: 1 });
}
#[test]
fn test_lifetime() {
#[derive(PartialEq, TypedBuilder)]
struct Foo<'a, 'b> {
x: &'a i32,
y: &'b i32,
}
assert!(Foo::builder().x(&1).y(&2).build() == Foo { x: &1, y: &2 });
}
#[test]
fn test_generics() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
x: S,
y: T,
}
assert!(Foo::builder().x(1).y(2).build() == Foo { x: 1, y: 2 });
}
#[test]
fn test_into() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(setter(into))]
x: i32,
}
assert!(Foo::builder().x(1_u8).build() == Foo { x: 1 });
}
#[test]
fn test_default() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
/// x value.
#[builder(default, setter(strip_option))]
x: Option,
#[builder(default = 10)]
/// y value.
y: i32,
/// z value.
#[builder(default = [20, 30, 40])]
z: [i32; 3],
}
assert!(
Foo::builder().build()
== Foo {
x: None,
y: 10,
z: [20, 30, 40]
}
);
assert!(
Foo::builder().x(1).build()
== Foo {
x: Some(1),
y: 10,
z: [20, 30, 40]
}
);
assert!(
Foo::builder().y(2).build()
== Foo {
x: None,
y: 2,
z: [20, 30, 40]
}
);
assert!(
Foo::builder().x(1).y(2).build()
== Foo {
x: Some(1),
y: 2,
z: [20, 30, 40]
}
);
assert!(
Foo::builder().z([1, 2, 3]).build()
== Foo {
x: None,
y: 10,
z: [1, 2, 3]
}
);
}
#[test]
fn test_field_dependencies_in_build() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(default, setter(strip_option))]
x: Option,
#[builder(default = 10)]
y: i32,
#[builder(default = [*y, 30, 40])]
z: [i32; 3],
}
assert!(
Foo::builder().build()
== Foo {
x: None,
y: 10,
z: [10, 30, 40]
}
);
assert!(
Foo::builder().x(1).build()
== Foo {
x: Some(1),
y: 10,
z: [10, 30, 40]
}
);
assert!(
Foo::builder().y(2).build()
== Foo {
x: None,
y: 2,
z: [2, 30, 40]
}
);
assert!(
Foo::builder().x(1).y(2).build()
== Foo {
x: Some(1),
y: 2,
z: [2, 30, 40]
}
);
assert!(
Foo::builder().z([1, 2, 3]).build()
== Foo {
x: None,
y: 10,
z: [1, 2, 3]
}
);
}
#[test]
fn test_default_with_generic_bounds() {
#[derive(Debug, PartialEq, TypedBuilder)]
struct Foo {
#[builder(default, default_where(T: Default))]
x: T,
}
#[derive(Debug, PartialEq)]
struct HasNoDefault {
y: i32,
}
assert_eq!(Foo::builder().build(), Foo { x: 0 });
assert_eq!(
Foo::builder().x(HasNoDefault { y: 7 }).build(),
Foo {
x: HasNoDefault { y: 7 }
}
);
}
#[test]
fn test_custom_default_with_generic_bounds() {
use core::fmt::Debug;
use core::str::FromStr;
#[derive(Debug, PartialEq, TypedBuilder)]
struct Foo {
x: &'static str,
#[builder(default = x.parse().unwrap(), default_where(T: FromStr, ::Err : Debug))]
y: T,
}
assert_eq!(Foo::builder().x("42").build(), Foo { x: "42", y: 42 });
}
#[test]
fn test_builder_type_with_derive_attribute() {
#[derive(TypedBuilder)]
#[builder(builder_type(attributes(#[derive(PartialEq, Debug)])))]
#[allow(dead_code)]
struct Foo {
x: i32,
y: i32,
}
assert_eq!(Foo::builder().x(1), Foo::builder().x(1));
assert_ne!(Foo::builder().x(1), Foo::builder().x(2));
}
typed-builder-0.23.2/tests/no_type_leakage.rs 0000644 0000000 0000000 00000000777 10461020230 0017332 0 ustar 0000000 0000000 // As long as this test compiles, it passes (test does not occur at runtime)
use typed_builder::TypedBuilder;
#[derive(PartialEq, TypedBuilder)]
#[builder(
build_method(vis="pub", into=Bar),
builder_method(vis=""),
builder_type(vis="pub", name=BarBuilder),
)]
struct Foo {
x: i32,
}
#[allow(unused)]
pub struct Bar(Foo);
impl Bar {
pub fn builder() -> BarBuilder {
Foo::builder()
}
}
impl From for Bar {
fn from(wrapped: Foo) -> Self {
Bar(wrapped)
}
}
typed-builder-0.23.2/tests/tests.rs 0000644 0000000 0000000 00000070343 10461020230 0015342 0 ustar 0000000 0000000 #![warn(clippy::pedantic)]
#![allow(clippy::disallowed_names, clippy::type_complexity)]
use typed_builder::TypedBuilder;
#[test]
fn test_simple() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
x: i32,
y: i32,
}
assert!(Foo::builder().x(1).y(2).build() == Foo { x: 1, y: 2 });
assert!(Foo::builder().y(1).x(2).build() == Foo { x: 2, y: 1 });
}
#[test]
fn test_lifetime() {
#[derive(PartialEq, TypedBuilder)]
struct Foo<'a, 'b> {
x: &'a i32,
y: &'b i32,
}
assert!(Foo::builder().x(&1).y(&2).build() == Foo { x: &1, y: &2 });
}
#[test]
fn test_lifetime_bounded() {
#[derive(PartialEq, TypedBuilder)]
struct Foo<'a, 'b: 'a> {
x: &'a i32,
y: &'b i32,
}
assert!(Foo::builder().x(&1).y(&2).build() == Foo { x: &1, y: &2 });
}
#[test]
fn test_mutable_borrows() {
#[derive(PartialEq, TypedBuilder)]
struct Foo<'a, 'b> {
x: &'a mut i32,
y: &'b mut i32,
}
let mut a = 1;
let mut b = 2;
{
let foo = Foo::builder().x(&mut a).y(&mut b).build();
*foo.x *= 10;
*foo.y *= 100;
}
assert!(a == 10);
assert!(b == 200);
}
#[test]
fn test_generics() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
x: S,
y: T,
}
assert!(Foo::builder().x(1).y(2).build() == Foo { x: 1, y: 2 });
}
#[test]
fn test_2d_const_generics() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
data: [[u32; NUM_ROWS]; NUM_COLS],
}
assert!(Foo::builder().data([[]]).build() == Foo { data: [[]] });
}
#[test]
fn test_multiple_const_generics() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
data: [u32; A],
data2: [u32; B],
data3: [u32; C],
}
assert!(
Foo::builder().data([1]).data2([2, 3]).data3([]).build()
== Foo {
data: [1],
data2: [2, 3],
data3: []
}
);
}
#[test]
fn test_const_generics_with_other_generics() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
data: [B; A],
data2: [B; 3],
}
assert!(
Foo::builder().data([3]).data2([0, 1, 2]).build()
== Foo {
data: [3],
data2: [0, 1, 2]
}
);
}
#[test]
fn test_into() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(setter(into))]
x: i32,
}
assert!(Foo::builder().x(1_u8).build() == Foo { x: 1 });
}
#[test]
fn test_strip_option_with_into() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(setter(strip_option, into))]
x: Option,
}
assert!(Foo::builder().x(1_u8).build() == Foo { x: Some(1) });
}
#[test]
fn test_into_with_strip_option() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(setter(into, strip_option))]
x: Option,
}
assert!(Foo::builder().x(1_u8).build() == Foo { x: Some(1) });
}
#[test]
fn test_strip_option_with_fallback() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(setter(strip_option(fallback = x_opt)))]
x: Option,
}
assert!(Foo::builder().x(1).build() == Foo { x: Some(1) });
assert!(Foo::builder().x_opt(Some(1)).build() == Foo { x: Some(1) });
}
#[test]
fn test_into_with_strip_option_with_fallback() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(setter(into, strip_option(fallback = x_opt)))]
x: Option,
}
assert!(Foo::builder().x(1_u8).build() == Foo { x: Some(1) });
assert!(Foo::builder().x_opt(Some(1)).build() == Foo { x: Some(1) });
}
#[test]
fn test_strip_bool() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(setter(into, strip_bool))]
x: bool,
}
assert!(Foo::builder().x().build() == Foo { x: true });
assert!(Foo::builder().build() == Foo { x: false });
}
#[test]
fn test_strip_bool_with_fallback() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(setter(into, strip_bool(fallback = x_bool)))]
x: bool,
}
assert!(Foo::builder().x().build() == Foo { x: true });
assert!(Foo::builder().x_bool(false).build() == Foo { x: false });
assert!(Foo::builder().build() == Foo { x: false });
}
#[test]
fn test_default() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(default, setter(strip_option))]
x: Option,
#[builder(default = 10)]
y: i32,
#[builder(default = vec![20, 30, 40])]
z: Vec,
}
assert!(
Foo::builder().build()
== Foo {
x: None,
y: 10,
z: vec![20, 30, 40]
}
);
assert!(
Foo::builder().x(1).build()
== Foo {
x: Some(1),
y: 10,
z: vec![20, 30, 40]
}
);
assert!(
Foo::builder().y(2).build()
== Foo {
x: None,
y: 2,
z: vec![20, 30, 40]
}
);
assert!(
Foo::builder().x(1).y(2).build()
== Foo {
x: Some(1),
y: 2,
z: vec![20, 30, 40]
}
);
assert!(
Foo::builder().z(vec![1, 2, 3]).build()
== Foo {
x: None,
y: 10,
z: vec![1, 2, 3]
}
);
}
#[test]
fn test_field_dependencies_in_build() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(default, setter(strip_option))]
x: Option,
#[builder(default = 10)]
y: i32,
#[builder(default = vec![*y, 30, 40])]
z: Vec,
}
assert!(
Foo::builder().build()
== Foo {
x: None,
y: 10,
z: vec![10, 30, 40]
}
);
assert!(
Foo::builder().x(1).build()
== Foo {
x: Some(1),
y: 10,
z: vec![10, 30, 40]
}
);
assert!(
Foo::builder().y(2).build()
== Foo {
x: None,
y: 2,
z: vec![2, 30, 40]
}
);
assert!(
Foo::builder().x(1).y(2).build()
== Foo {
x: Some(1),
y: 2,
z: vec![2, 30, 40]
}
);
assert!(
Foo::builder().z(vec![1, 2, 3]).build()
== Foo {
x: None,
y: 10,
z: vec![1, 2, 3]
}
);
}
// compile-fail tests for skip are in src/lib.rs out of necessity. These are just the bland
// successful cases.
#[test]
fn test_skip() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(default, setter(skip))]
x: i32,
#[builder(setter(into))]
y: i32,
#[builder(default = y + 1, setter(skip))]
z: i32,
}
assert!(Foo::builder().y(1_u8).build() == Foo { x: 0, y: 1, z: 2 });
}
#[test]
fn test_docs() {
#[derive(TypedBuilder)]
#[builder(
builder_method(doc = "Point::builder() method docs"),
builder_type(doc = "PointBuilder type docs"),
build_method(doc = "PointBuilder.build() method docs")
)]
struct Point {
#[allow(dead_code)]
x: i32,
#[builder(
default = *x,
setter(
doc = "Set `z`. If you don't specify a value it'll default to the value specified for `x`.",
),
)]
#[allow(dead_code)]
y: i32,
}
let _ = Point::builder();
}
#[test]
fn test_builder_name() {
#[derive(TypedBuilder)]
struct Foo {}
let _: FooBuilder<_> = Foo::builder();
}
// NOTE: `test_builder_type_stability` and `test_builder_type_stability_with_other_generics` are
// meant to ensure we don't break things for people that use custom `impl`s on the builder
// type before the tuple field generic param transformation traits are in.
// See:
// - https://github.com/idanarye/rust-typed-builder/issues/22
// - https://github.com/idanarye/rust-typed-builder/issues/23
#[test]
fn test_builder_type_stability() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
x: i32,
y: i32,
z: i32,
}
impl FooBuilder<((), Y, ())> {
fn xz(self, x: i32, z: i32) -> FooBuilder<((i32,), Y, (i32,))> {
self.x(x).z(z)
}
}
assert!(Foo::builder().xz(1, 2).y(3).build() == Foo { x: 1, y: 3, z: 2 });
assert!(Foo::builder().xz(1, 2).y(3).build() == Foo::builder().x(1).z(2).y(3).build());
assert!(Foo::builder().y(1).xz(2, 3).build() == Foo { x: 2, y: 1, z: 3 });
assert!(Foo::builder().y(1).xz(2, 3).build() == Foo::builder().y(1).x(2).z(3).build());
}
#[test]
fn test_builder_type_stability_with_other_generics() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
x: X,
y: Y,
}
impl FooBuilder {
fn x_default(self) -> FooBuilder {
self.x(X::default())
}
}
assert!(Foo::builder().x_default().y(1.0).build() == Foo { x: 0, y: 1.0 });
assert!(
Foo::builder().y("hello".to_owned()).x_default().build()
== Foo {
x: "",
y: "hello".to_owned()
}
);
}
#[test]
#[allow(clippy::items_after_statements)]
fn test_builder_type_with_default_on_generic_type() {
#[derive(PartialEq, TypedBuilder)]
struct Types {
x: X,
y: Y,
}
assert!(Types::builder().x(()).y(()).build() == Types { x: (), y: () });
#[derive(PartialEq, TypedBuilder)]
struct TypeAndLifetime<'a, X, Y: Default, Z = usize> {
x: X,
y: Y,
z: &'a Z,
}
let a = 0;
assert!(TypeAndLifetime::builder().x(()).y(0).z(&a).build() == TypeAndLifetime { x: (), y: 0, z: &0 });
#[derive(PartialEq, TypedBuilder)]
struct Foo<'a, X, Y: Default, Z: Default = usize, M = ()> {
x: X,
y: &'a Y,
z: Z,
m: M,
}
impl<'a, X, Y: Default, M, X_, Y_, M_> FooBuilder<'a, X, Y, usize, M, (X_, Y_, (), M_)> {
fn z_default(self) -> FooBuilder<'a, X, Y, usize, M, (X_, Y_, (usize,), M_)> {
self.z(usize::default())
}
}
impl<'a, X, Y: Default, Z: Default, X_, Y_, Z_> FooBuilder<'a, X, Y, Z, (), (X_, Y_, Z_, ())> {
fn m_default(self) -> FooBuilder<'a, X, Y, Z, (), (X_, Y_, Z_, ((),))> {
self.m(())
}
}
// compile test if rustc can infer type for `z` and `m`
Foo::<(), _, _, f64>::builder().x(()).y(&a).z_default().m(1.0).build();
Foo::<(), _, _, _>::builder().x(()).y(&a).z_default().m_default().build();
assert!(
Foo::builder().x(()).y(&a).z_default().m(1.0).build()
== Foo {
x: (),
y: &0,
z: 0,
m: 1.0
}
);
assert!(
Foo::builder().x(()).y(&a).z(9).m(1.0).build()
== Foo {
x: (),
y: &0,
z: 9,
m: 1.0
}
);
}
#[test]
fn test_builder_type_skip_into() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
x: X,
}
// compile test if rustc can infer type for `x`
Foo::builder().x(()).build();
assert!(Foo::builder().x(()).build() == Foo { x: () });
}
#[test]
fn test_default_code() {
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(default_code = "\"text1\".to_owned()")]
x: String,
#[builder(default_code = r#""text2".to_owned()"#)]
y: String,
}
assert!(
Foo::builder().build()
== Foo {
x: "text1".to_owned(),
y: "text2".to_owned()
}
);
}
#[test]
fn test_field_defaults_default_value() {
#[derive(PartialEq, TypedBuilder)]
#[builder(field_defaults(default = 12))]
struct Foo {
x: i32,
#[builder(!default)]
y: String,
#[builder(default = 13)]
z: i32,
}
assert!(
Foo::builder().y("bla".to_owned()).build()
== Foo {
x: 12,
y: "bla".to_owned(),
z: 13
}
);
}
#[test]
fn test_field_defaults_setter_options() {
#[derive(PartialEq, TypedBuilder)]
#[builder(field_defaults(setter(strip_option)))]
struct Foo {
x: Option,
#[builder(setter(!strip_option))]
y: i32,
}
assert!(Foo::builder().x(1).y(2).build() == Foo { x: Some(1), y: 2 });
}
#[test]
fn test_field_defaults_strip_option_ignore_invalid() {
#[derive(TypedBuilder)]
#[builder(field_defaults(setter(strip_option(ignore_invalid))))]
struct Foo {
x: Option,
y: i32,
#[builder(default = Some(13))]
z: Option,
}
let foo = Foo::builder().x(42).y(10).build();
assert_eq!(foo.x, Some(42));
assert_eq!(foo.y, 10);
assert_eq!(foo.z, Some(13));
}
#[test]
fn test_field_defaults_strip_option_fallback_suffix() {
#[derive(TypedBuilder)]
#[builder(field_defaults(setter(strip_option(fallback_suffix = "_opt"))))]
struct Foo {
x: Option,
#[builder(default = Some(13))]
z: Option,
}
let foo1 = Foo::builder().x(42).build();
let foo2 = Foo::builder().x_opt(None).build();
assert_eq!(foo1.x, Some(42));
assert_eq!(foo1.z, Some(13));
assert_eq!(foo2.x, None);
assert_eq!(foo2.z, Some(13));
}
#[test]
fn test_field_defaults_strip_option_fallback_prefix() {
#[derive(TypedBuilder)]
#[builder(field_defaults(setter(strip_option(fallback_prefix = "opt_"))))]
struct Foo {
x: Option,
#[builder(default = Some(13))]
z: Option,
}
let foo1 = Foo::builder().x(42).build();
let foo2 = Foo::builder().opt_x(None).build();
assert_eq!(foo1.x, Some(42));
assert_eq!(foo1.z, Some(13));
assert_eq!(foo2.x, None);
assert_eq!(foo2.z, Some(13));
}
#[test]
fn test_field_defaults_strip_option_fallback_prefix_and_suffix() {
#[derive(TypedBuilder)]
#[builder(field_defaults(setter(strip_option(fallback_prefix = "opt_", fallback_suffix = "_val"))))]
struct Foo {
x: Option,
#[builder(default = Some(13))]
z: Option,
}
let foo1 = Foo::builder().x(42).build();
let foo2 = Foo::builder().opt_x_val(None).build();
assert_eq!(foo1.x, Some(42));
assert_eq!(foo1.z, Some(13));
assert_eq!(foo2.x, None);
assert_eq!(foo2.z, Some(13));
}
#[test]
fn test_clone_builder() {
#[derive(PartialEq, Default)]
struct Uncloneable;
#[derive(PartialEq, TypedBuilder)]
struct Foo {
x: i32,
y: i32,
#[builder(default)]
z: Uncloneable,
}
let semi_built = Foo::builder().x(1);
assert!(
semi_built.clone().y(2).build()
== Foo {
x: 1,
y: 2,
z: Uncloneable
}
);
assert!(
semi_built.y(3).build()
== Foo {
x: 1,
y: 3,
z: Uncloneable
}
);
}
#[test]
#[allow(clippy::items_after_statements)]
fn test_clone_builder_with_generics() {
#[allow(dead_code)]
#[derive(PartialEq, Default)]
struct Uncloneable;
#[derive(PartialEq, TypedBuilder)]
struct Foo {
x: T,
y: i32,
}
let semi_built1 = Foo::builder().x(1);
assert!(semi_built1.clone().y(2).build() == Foo { x: 1, y: 2 });
assert!(semi_built1.y(3).build() == Foo { x: 1, y: 3 });
let semi_built2 = Foo::builder().x("four");
assert!(semi_built2.clone().y(5).build() == Foo { x: "four", y: 5 });
assert!(semi_built2.y(6).build() == Foo { x: "four", y: 6 });
// Just to make sure it can build with generic bounds
#[allow(dead_code)]
#[derive(TypedBuilder)]
struct Bar
where
T: std::fmt::Display,
{
x: T,
}
}
#[test]
fn test_builder_on_struct_with_keywords() {
#[allow(non_camel_case_types)]
#[derive(PartialEq, TypedBuilder)]
struct r#struct {
r#fn: u32,
#[builder(default, setter(strip_option))]
r#type: Option,
#[builder(default = Some(()), setter(skip))]
r#enum: Option<()>,
#[builder(setter(into))]
r#union: String,
}
assert!(
r#struct::builder().r#fn(1).r#union("two").build()
== r#struct {
r#fn: 1,
r#type: None,
r#enum: Some(()),
r#union: "two".to_owned(),
}
);
}
#[test]
fn test_builder_on_struct_with_keywords_prefix_suffix() {
#[allow(non_camel_case_types)]
#[derive(PartialEq, TypedBuilder)]
#[builder(field_defaults(setter(prefix = "set_", suffix = "_value")))]
struct r#struct {
r#fn: u32,
#[builder(default, setter(strip_option))]
r#type: Option,
#[builder(default = Some(()), setter(skip))]
r#enum: Option<()>,
#[builder(setter(into))]
r#union: String,
}
assert!(
r#struct::builder().r#set_fn_value(1).r#set_union_value("two").build()
== r#struct {
r#fn: 1,
r#type: None,
r#enum: Some(()),
r#union: "two".to_owned(),
}
);
}
#[test]
fn test_unsized_generic_params() {
use std::marker::PhantomData;
#[derive(TypedBuilder)]
struct GenericStructure
where
K: ?Sized,
{
key: PhantomData,
value: PhantomData,
}
}
#[test]
fn test_field_setter_transform_closure() {
#[derive(PartialEq)]
struct Point {
x: i32,
y: i32,
}
#[derive(PartialEq, TypedBuilder)]
struct Foo {
#[builder(setter(transform = |x: i32, y: i32| Point { x, y }))]
point: Point,
}
assert!(
Foo::builder().point(1, 2).build()
== Foo {
point: Point { x: 1, y: 2 }
}
);
}
#[test]
fn test_field_setter_transform_fn() {
struct MBaseCase;
struct MClosure;
// Lifetime is not needed, just added to test.
trait IntoValue<'a, T, M> {
fn into_value(self) -> T;
}
impl IntoValue<'_, T, MBaseCase> for I
where
I: Into,
{
fn into_value(self) -> T {
self.into()
}
}
impl IntoValue<'_, T, MClosure> for F
where
F: FnOnce() -> T,
{
fn into_value(self) -> T {
self()
}
}
#[derive(TypedBuilder)]
struct Foo {
#[builder(
setter(
fn transform<'a, M>(value: impl IntoValue<'a, String, M>)
where
M: 'a,
{
value.into_value()
},
)
)]
s: String,
}
// Check where clause and return type
#[derive(TypedBuilder)]
struct Bar {
#[builder(
setter(
fn transform(value: A) -> String
where
A: std::fmt::Display,
{
value.to_string()
},
)
)]
s: String,
}
assert_eq!(Foo::builder().s("foo").build().s, "foo".to_owned());
assert_eq!(Foo::builder().s(|| "foo".to_owned()).build().s, "foo".to_owned());
assert_eq!(Bar::builder().s(42).build().s, "42".to_owned());
}
#[test]
fn test_build_method() {
#[derive(PartialEq, TypedBuilder)]
#[builder(build_method(vis="", name=__build))]
struct Foo {
x: i32,
}
assert!(Foo::builder().x(1).__build() == Foo { x: 1 });
}
#[test]
fn test_builder_method() {
#[derive(PartialEq, TypedBuilder)]
#[builder(builder_method(vis="", name=__builder))]
struct Foo {
x: i32,
}
assert!(Foo::__builder().x(1).build() == Foo { x: 1 });
}
#[test]
fn test_builder_type() {
#[derive(PartialEq, TypedBuilder)]
#[builder(builder_type(vis="", name=__FooBuilder))]
struct Foo {
x: i32,
}
let builder: __FooBuilder<_> = Foo::builder();
assert!(builder.x(1).build() == Foo { x: 1 });
}
#[test]
fn test_default_builder_type() {
#[derive(Debug, PartialEq, TypedBuilder)]
#[builder(builder_method(vis = ""), builder_type(name = InnerBuilder), build_method(into = Outer))]
struct Inner {
a: i32,
b: i32,
}
#[derive(Debug, PartialEq)]
struct Outer(Inner);
impl Outer {
pub fn builder() -> InnerBuilder {
Inner::builder()
}
}
impl From for Outer {
fn from(value: Inner) -> Self {
Self(value)
}
}
let outer = Outer::builder().a(3).b(5).build();
assert_eq!(outer, Outer(Inner { a: 3, b: 5 }));
}
#[test]
fn test_into_set_generic_impl_from() {
#[derive(TypedBuilder)]
#[builder(build_method(into))]
struct Foo {
value: i32,
}
#[derive(Debug, PartialEq)]
struct Bar {
value: i32,
}
impl From for Bar {
fn from(value: Foo) -> Self {
Self { value: value.value }
}
}
let bar: Bar = Foo::builder().value(42).build();
assert_eq!(bar, Bar { value: 42 });
}
#[test]
fn test_into_angle_bracket_type() {
#[derive(Debug, PartialEq, TypedBuilder)]
#[builder(build_method(into = std::sync::Arc))]
struct Foo {
value: i32,
}
let foo: std::sync::Arc = Foo::builder().value(42).build();
assert_eq!(*foo, Foo { value: 42 });
}
#[test]
fn test_into_set_generic_impl_into() {
#[derive(TypedBuilder)]
#[builder(build_method(into))]
struct Foo {
value: i32,
}
#[derive(Debug, PartialEq)]
struct Bar {
value: i32,
}
impl From for Bar {
fn from(val: Foo) -> Self {
Self { value: val.value }
}
}
let bar: Bar = Foo::builder().value(42).build();
assert_eq!(bar, Bar { value: 42 });
}
#[test]
fn test_prefix() {
#[derive(Debug, PartialEq, TypedBuilder)]
#[builder(field_defaults(setter(prefix = "with_")))]
struct Foo {
x: i32,
y: i32,
}
let foo = Foo::builder().with_x(1).with_y(2).build();
assert_eq!(foo, Foo { x: 1, y: 2 });
}
#[test]
fn test_suffix() {
#[derive(Debug, PartialEq, TypedBuilder)]
#[builder(field_defaults(setter(suffix = "_value")))]
struct Foo {
x: i32,
y: i32,
}
let foo = Foo::builder().x_value(1).y_value(2).build();
assert_eq!(foo, Foo { x: 1, y: 2 });
}
#[test]
fn test_prefix_and_suffix() {
#[derive(Debug, PartialEq, TypedBuilder)]
#[builder(field_defaults(setter(prefix = "with_", suffix = "_value")))]
struct Foo {
x: i32,
y: i32,
}
let foo = Foo::builder().with_x_value(1).with_y_value(2).build();
assert_eq!(foo, Foo { x: 1, y: 2 });
}
#[test]
fn test_issue_118() {
#[derive(TypedBuilder)]
#[builder(build_method(into=Bar))]
struct Foo {
#[builder(default, setter(skip))]
#[allow(dead_code)]
foo: Option,
}
struct Bar;
impl From> for Bar {
fn from(_value: Foo) -> Self {
Self
}
}
let _ = Foo::::builder().build();
}
#[test]
fn test_mutable_defaults() {
#[derive(TypedBuilder, PartialEq, Debug)]
struct Foo {
#[builder(default, mutable_during_default_resolution, setter(strip_option))]
x: Option,
#[builder(default = if let Some(x) = x.as_mut() {
*x *= 2;
*x
} else {
Default::default()
})]
y: i32,
}
let foo = Foo::builder().x(5).build();
assert_eq!(foo, Foo { x: Some(10), y: 10 });
}
#[test]
fn test_preinitialized_fields() {
#[derive(Debug, PartialEq, TypedBuilder)]
struct Foo {
x: i32,
#[builder(via_mutators)]
y: i32,
#[builder(via_mutators = 2)]
z: i32,
#[builder(via_mutators(init = 2))]
w: i32,
}
let foo = Foo::builder().x(1).build();
assert_eq!(foo, Foo { x: 1, y: 0, z: 2, w: 2 });
}
#[test]
fn test_mutators_item() {
#[derive(Debug, PartialEq, TypedBuilder)]
#[builder(mutators(
#[mutator(requires = [x])]
fn inc_x(self) {
self.x += 1;
}
#[mutator(requires = [x])]
fn inc_x_by(self, x: i32) {
self.x += x;
}
fn inc_preset(self) {
self.y += 1;
self.z += 1;
self.w += 1;
}
#[mutator(requires = [x])]
fn inc_y_by_x(self) {
self.y += self.x;
}
))]
struct Foo {
x: i32,
#[builder(via_mutators)]
y: i32,
#[builder(via_mutators = 2)]
z: i32,
#[builder(via_mutators(init = 2))]
w: i32,
}
let foo = Foo::builder().x(1).inc_x().inc_preset().build();
assert_eq!(foo, Foo { x: 2, y: 1, z: 3, w: 3 });
let foo = Foo::builder().x(1).inc_x_by(4).inc_y_by_x().build();
assert_eq!(foo, Foo { x: 5, y: 5, z: 2, w: 2 });
}
#[test]
fn test_mutators_field() {
#[derive(Debug, PartialEq, TypedBuilder)]
#[builder(mutators())]
struct Foo {
#[builder(mutators(
fn inc_x(self) {
self.x += 1;
}
#[mutator(requires = [y])]
fn inc_y_by_x(self) {
self.y += self.x;
}
))]
x: i32,
#[builder(default)]
y: i32,
#[builder(via_mutators = 2, mutators(
fn inc_preset(self) {
self.z += 1;
self.w += 1;
}
))]
z: i32,
#[builder(via_mutators(init = 2))]
w: i32,
}
let foo = Foo::builder().x(1).inc_x().inc_preset().build();
assert_eq!(foo, Foo { x: 2, y: 0, z: 3, w: 3 });
let foo = Foo::builder().x(1).y(1).inc_y_by_x().build();
assert_eq!(foo, Foo { x: 1, y: 2, z: 2, w: 2 });
}
#[test]
fn test_mutators_for_generic_fields() {
use core::ops::AddAssign;
#[derive(Debug, PartialEq, TypedBuilder)]
struct Foo {
#[builder(via_mutators, mutators(
fn x_plus(self, plus: S) {
self.x += plus;
}
))]
x: S,
y: T,
}
assert_eq!(Foo::builder().x_plus(1).y(2).build(), Foo { x: 1, y: 2 });
}
#[test]
fn test_mutators_with_type_param() {
use core::ops::AddAssign;
trait HasS {
type MyS: Default + AddAssign;
}
#[derive(Debug, PartialEq, TypedBuilder)]
struct Foo {
#[builder(via_mutators, mutators(
fn x_plus>(self, s: ::MyS) {
self.x += s;
}
))]
x: S,
}
struct HasSImpl;
impl HasS for HasSImpl {
type MyS = u32;
}
assert_eq!(Foo::builder().x_plus::(1).build(), Foo { x: 1 });
}
#[test]
fn test_default_with_generic_bounds() {
#[derive(Debug, PartialEq, TypedBuilder)]
struct Foo {
#[builder(default, default_where(T: Default))]
x: T,
}
#[derive(Debug, PartialEq)]
struct HasNoDefault {
y: i32,
}
assert_eq!(Foo::builder().build(), Foo { x: 0 });
assert_eq!(
Foo::builder().x(HasNoDefault { y: 7 }).build(),
Foo {
x: HasNoDefault { y: 7 }
}
);
}
#[test]
fn test_custom_default_with_generic_bounds() {
use core::fmt::Debug;
use core::str::FromStr;
#[derive(Debug, PartialEq, TypedBuilder)]
struct Foo {
x: &'static str,
#[builder(default = x.parse().unwrap(), default_where(T: FromStr, ::Err : Debug))]
y: T,
}
assert_eq!(Foo::builder().x("42").build(), Foo { x: "42", y: 42 });
}
#[test]
fn test_builder_type_with_derive_attribute() {
#[derive(TypedBuilder)]
#[builder(builder_type(attributes(#[derive(PartialEq, Debug)])))]
#[allow(dead_code)]
struct Foo {
x: i32,
y: i32,
}
assert_eq!(Foo::builder().x(1), Foo::builder().x(1));
assert_ne!(Foo::builder().x(1), Foo::builder().x(2));
}