Try Create
try_create is a small Rust utility library that provides generic traits for object creation, offering standardized ways to handle infallible, fallible, conditional, and policy-based validated construction.
Overview
This library introduces a set of traits to streamline the creation of new type instances:
IntoInner: A re-exported trait from theinto_innercrate, used as a supertrait to define the input type for construction.TryNew: For fallible construction, where creating an instance might fail (e.g., due to validation rules). It returns aResult.New: For infallible construction. If an invariant is violated, this method is expected to panic.ConditionallyCreate: A utility trait that switches creation logic based on the build profile:- In debug mode, it uses
TryNew::try_new().expect(), panicking iftry_newfails. - In release mode, it uses
New::new().
- In debug mode, it uses
ValidationPolicy: Defines a contract for validation logic. A policy specifies how a value should be validated and what error type is returned upon failure. This allows for reusable validation strategies.TryNewValidated: ExtendsTryNewby associating a specificValidationPolicywith the type. TheTryNewValidated::try_new_validatedmethod first applies the policy and then, if successful, proceeds with the underlyingTryNewconstruction logic.
These traits are designed to be general-purpose and can be used for various types, promoting a consistent API for object instantiation. The library supports no_std environments.
Installation
Add try_create to your Cargo.toml:
[]
= "0.1" # Replace with the latest version
= "0.1" # try_create re-exports IntoInner, but you might depend on it directly too
Usage
1. IntoInner Trait
Both TryNew and New require IntoInner to be implemented. This trait defines the InnerType that your constructor will accept and a way to retrieve this inner value from an instance.
use IntoInner;
2. TryNew Trait (Fallible Creation)
Use TryNew when the creation process can fail and you want to return a Result.
use ;
use fmt;
use Error;
// Define a custom error type
;
// For no_std, NotPositiveError would just need to implement core::fmt::Debug,
// which it does via #[derive(Debug, PartialEq)].
// A struct that wraps an i32, ensuring it's positive.
// Usage
assert_eq!;
assert_eq!;
assert_eq!;
let positive_num = try_new.unwrap;
assert_eq!;
3. New Trait (Infallible/Panicking Creation)
Use New when the creation process should not fail in a recoverable way. If invariants are violated, New::new should panic.
use ; // TryNew often used to implement New
use fmt;
use Error;
// Example struct
;
// Custom error for TryNew implementation (if used to implement New)
;
// Optional TryNew, can be used to implement New
// Usage
assert_eq!;
// The following would panic:
// MyType::new(-5);
4. ConditionallyCreate Trait
This trait provides a create_conditionally method that behaves differently in debug and release builds.
use ;
use fmt;
use Error;
// Using PositiveInteger and NotPositiveError from the TryNew example above
;
// PositiveInteger must also implement New to use ConditionallyCreate
// Usage of ConditionallyCreate
let p1 = create_conditionally;
assert_eq!;
// If PositiveInteger::create_conditionally(-5) was called:
// - In debug mode: it would panic with "ConditionallyCreate: try_new() failed in debug mode".
// - In release mode: it would panic with "PositiveInteger::new failed...".
5. ValidationPolicy Trait
Defines a reusable validation strategy.
use ValidationPolicy;
use fmt;
use Error;
;
// Usage
assert_eq!;
assert!;
assert_eq!; // Uses default validate
assert!; // Uses default validate
6. TryNewValidated Trait
Combines a ValidationPolicy with TryNew for two-phase construction.
use ;
use fmt;
use Error;
// --- Reusing MinValuePolicy and MinValueError from previous example ---
;
; // Simplified for example, assumes fixed min of 0
// --- Define the type to be created and its specific errors ---
// Implement From for error conversion (Policy::Error -> Self::Error)
;
// 1. Implement TryNew for the core construction logic (post-validation)
// 2. Implement TryNewValidated, associating the policy
// Usage
// Policy: value >= 0. Construction: value must be even.
// Valid: 10 >= 0 (policy pass), 10 is even (construction pass)
assert_eq!;
// Invalid: Policy fails (-5 < 0)
let err_policy = try_new_validated.unwrap_err;
match err_policy
// Invalid: Policy passes (5 >= 0), but construction fails (5 is not even)
let err_constr = try_new_validated.unwrap_err;
match err_constr
no_std Support
The library is no_std compatible.
When the std feature is not enabled (default for no_std environments):
TryNew::ErrorandValidationPolicy::Erroronly requirecore::fmt::Debug.- You are responsible for defining error types that conform to this.
Contributing
Contributions, issues, and feature requests are welcome!
License
This project is licensed under the terms of the MIT license and the Apache License (Version 2.0). See LICENSE-MIT and LICENSE-APACHE for details. (You'll need to add these license files to your project).