This is a straightforward fork of the lazy-init
, with fallible initialisation added that I couldn't provide with a wrapper.
Please use cargo-edit to always add the latest version of this library:
cmd
cargo add try-lazy-init
```rust use trylazyinit::{Lazy, LazyTransform};
let lazy = Lazy::new(); asserteq!( // Not yet initialized, so this closure runs: lazy.getorcreate(|| 1), &1 ); asserteq!( // Already initialized so this closure doesn't run: lazy.trygetorcreate(|| { unreachable!(); Err(()) }), Ok(&1) ); asserteq!(lazy.get(), Some(&1)); asserteq!(lazy.intoinner(), Some(1));
let lazytransform = LazyTransform::new(1);
asserteq!(
// Not yet initialized, so this closure runs:
lazytransform.getorcreate(|x| x + 1),
&2
);
asserteq!(
// Only available where T: Clone
.
// Already initialized so this closure doesn't run:
lazytransform.trygetorcreate(|| { unreachable!(); Err(()) }),
Ok(&2)
);
asserteq!(
// Available also without where T: Clone
.
// Already initialized so this closure doesn't run:
lazytransform.getorcreateorpoison(|| { unreachable!(); Err(()) }),
Ok(&2)
);
asserteq!(lazytransform.get(), Some(&2));
asserteq!(lazytransform.into_inner(), Ok(2));
let lazytransform2 = LazyTransform::<_, ()>::new(1);
asserteq!(
// This poisons by error, which won't panic this method or .try_into_inner
:
lazytransform2.getorcreateorpoison(|| Err(())),
Err(Some(()))
);
asserteq!(
// The original value is now gone:
lazytransform2.tryinto_inner(),
Err(None)
);
```
As of 2021-09-05 (i.e. the date of the fork), lazy-init
's Cargo.toml states license = "Apache-2.0/MIT"
while only the MIT License's text is present in LICENSE. I've left this situation unchanged.
As such, consider the package MIT-licensed for use and Apache-2.0/MIT dual-licensed when contributing.
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.
try-lazy-init
strictly follows Semantic Versioning 2.0.0 with the following exceptions:
This includes the Rust version requirement specified above.
Earlier Rust versions may be compatible, but this can change with minor or patch releases.
Which versions are affected by features and patches can be determined from the respective headings in CHANGELOG.md.