try_create 0.1.2

A small library providing generic traits for fallible and infallible object creation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
#![deny(rustdoc::broken_intra_doc_links)]

//! This crate provides a set of traits for standardizing object creation
//! patterns in Rust, covering infallible, fallible, conditional, and
//! policy-based validated construction.
//!
//! # Core Traits
//!
//! - [`IntoInner`]: A trait for types that can be converted into an "inner"
//!   value. This is often a prerequisite for construction traits.
//! - [`TryNew`]: For fallible construction that returns a [`Result`]. Use this
//!   when creating an instance might fail due to validation or other reasons.
//! - [`New`]: For infallible construction. If creation cannot logically fail
//!   (or if failure should deterministically panic), use this trait.
//!
//! # Advanced Construction Patterns
//!
//! - [`ConditionallyCreate`]: Provides a `create_conditionally` method that
//!   behaves differently in debug and release builds. In debug, it uses
//!   `TryNew::try_new().expect()`, panicking on failure. In release, it uses
//!   `New::new()`. This is useful for enforcing stricter checks during
//!   development.
//! - [`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`]: Extends [`TryNew`] by associating a specific
//!   [`ValidationPolicy`] with the type. The [`TryNewValidated::try_new_validated`] method
//!   first applies the policy and then, if successful, proceeds with the
//!   underlying [`TryNew`] construction logic. This enables a two-phase
//!   construction process: external validation followed by internal creation.
//!
//! # Features
//!
//! - `std`: (Enabled by default) When enabled, the `Error` associated type
//!   for [`TryNew`] and [`ValidationPolicy`] is bound by `std::error::Error`.
//! - If `std` is not enabled, their `Error` types are bound by `core::fmt::Debug`.
//!
//! # Examples
//!
//! See the documentation for individual traits for specific examples.

// Re-export IntoInner for convenience, as it's a supertrait of TryNew.
pub use into_inner::IntoInner;

use duplicate::duplicate_item;
use num::Complex;
use std::convert::Infallible;

/// A trait for creating new instances of a type with fallible validation.
///
/// This trait provides a standardized way to create new instances of a type from an
/// "inner" value, where the construction process might fail (e.g., due to validation rules).
/// Implementors must also implement [`IntoInner`], which defines the `InnerType` used
/// for construction.
///
/// # Associated Types
///
/// - `InnerType`: (From the [`IntoInner`] supertrait) The type of the input value used to
///   attempt creation of a new instance of `Self`.
/// - `Error`: The error type that is returned if `try_new` fails. This error type
///   must implement `std::error::Error` if the `std` feature is enabled.
///   If the `std` feature is not enabled, it must implement `core::fmt::Debug`.
///
/// # Examples
///
/// ```rust
/// use try_create::{TryNew, IntoInner};
/// # #[cfg(feature = "std")]
/// # use std::error::Error;
/// # #[cfg(feature = "std")]
/// # use core::fmt;
///
/// // Define a custom error type
/// #[derive(Debug, PartialEq)]
/// struct NotPositiveError;
///
/// // Implement Display and Error for the custom error (required if using std::error::Error)
/// # #[cfg(feature = "std")]
/// impl fmt::Display for NotPositiveError {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         write!(f, "Value must be positive")
///     }
/// }
/// # #[cfg(feature = "std")]
/// impl Error for NotPositiveError {}
/// # #[cfg(not(feature = "std"))]
/// # trait Error: core::fmt::Debug {} // Minimal Error trait for no_std
/// # #[cfg(not(feature = "std"))]
/// # impl Error for NotPositiveError {}
///
///
/// // A struct that wraps an i32, ensuring it's positive.
/// #[derive(Debug, PartialEq)]
/// struct PositiveInteger {
///     value: i32,
/// }
///
/// // Implement IntoInner to define what `InnerType` is.
/// impl IntoInner for PositiveInteger {
///     type InnerType = i32;
///
///     fn into_inner(self) -> Self::InnerType {
///         self.value
///     }
/// }
///
/// // Implement TryNew for PositiveInteger.
/// impl TryNew for PositiveInteger {
///     type Error = NotPositiveError;
///     // `InnerType` is `i32`, inherited from `IntoInner`.
///
///     fn try_new(value: Self::InnerType) -> Result<Self, Self::Error> {
///         if value > 0 {
///             Ok(PositiveInteger { value })
///         } else {
///             Err(NotPositiveError)
///         }
///     }
/// }
///
/// // Usage
/// assert_eq!(PositiveInteger::try_new(10), Ok(PositiveInteger { value: 10 }));
/// assert_eq!(PositiveInteger::try_new(0), Err(NotPositiveError));
/// assert_eq!(PositiveInteger::try_new(-5), Err(NotPositiveError));
///
/// let positive_num = PositiveInteger::try_new(42).unwrap();
/// assert_eq!(positive_num.into_inner(), 42);
/// ```
pub trait TryNew: Sized + IntoInner {
    /// The error type that can be returned by the `try_new` method.
    #[cfg(feature = "std")]
    type Error: std::error::Error;
    #[cfg(not(feature = "std"))]
    type Error: core::fmt::Debug; // Added for no_std consistency

    /// Attempts to create a new instance of `Self` from `value`.
    ///
    /// # Parameters
    ///
    /// - `value`: The `InnerType` value from which to create the instance.
    ///
    /// # Returns
    ///
    /// - `Ok(Self)` if the instance is created successfully.
    /// - `Err(Self::Error)` if creation fails (e.g., due to invalid input).
    fn try_new(value: Self::InnerType) -> Result<Self, Self::Error>;
}

/// A trait for creating new instances of a type infallibly.
///
/// This trait provides a method for creating new instances of a type from `Self::InnerType`
/// (defined by the `IntoInner` supertrait).
///
/// Implementors should ensure that the [`New`] method cannot fail in a way that would
/// typically return a `Result`. If invalid input could lead to an unrecoverable state
/// or violate invariants, [`New`] should panic. For fallible construction that returns
/// a `Result`, use the [[`TryNew`]] trait.
///
/// # Examples
///
/// ```rust
/// use try_create::{New, IntoInner, TryNew}; // Assuming TryNew is used for context or comparison
/// # #[cfg(feature = "std")]
/// # use std::error::Error;
/// # #[cfg(feature = "std")]
/// # use std::fmt;
///
/// // Example struct
/// #[derive(Debug, PartialEq)]
/// struct MyType(i32);
///
/// // Define a custom error for MyType for the TryNew example
/// #[derive(Debug, PartialEq)]
/// struct MyTypeError(String);
///
/// // Implement Display and Error for MyTypeError
/// # #[cfg(feature = "std")]
/// impl fmt::Display for MyTypeError {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         write!(f, "MyTypeError: {}", self.0)
///     }
/// }
///
/// # #[cfg(feature = "std")]
/// impl Error for MyTypeError {}
/// // For no_std, MyTypeError already derives Debug, which is sufficient.
///
/// impl IntoInner for MyType {
///     type InnerType = i32;
///     fn into_inner(self) -> Self::InnerType { self.0 }
/// }
///
/// // Example TryNew (optional here, but good for context)
/// impl TryNew for MyType {
///     type Error = MyTypeError; // Use the custom error type
///     fn try_new(value: i32) -> Result<Self, Self::Error> {
///         if value < 0 { Err(MyTypeError("Value cannot be negative".to_string())) }
///         else { Ok(MyType(value)) }
///     }
/// }
///
/// impl New for MyType {
///     fn new(value: i32) -> Self {
///         if value < 0 {
///             panic!("MyType::new: Value cannot be negative");
///         }
///         MyType(value)
///     }
/// }
///
/// assert_eq!(MyType::new(10), MyType(10));
/// // The following would panic:
/// // MyType::new(-5);
/// ```
pub trait New: Sized + IntoInner {
    /// Creates a new instance of `Self` from `value`.
    ///
    /// This method is expected to be infallible in terms of returning a `Result`.
    /// If the provided `value` cannot produce a valid instance of `Self`
    /// according to the type's invariants, this method should panic.
    ///
    /// # Parameters
    ///
    /// - `value`: The `Self::InnerType` value from which to create the instance.
    fn new(value: Self::InnerType) -> Self;
}

// It's necessary to import Debug for the bound on TryNew's error type.
// This is implicitly handled if `std::error::Error` is used (as it requires Debug)
// or if `core::fmt::Debug` is directly used for no_std.
// For clarity, if you were in a module that didn't automatically have `std::fmt::Debug`
// or `core::fmt::Debug` in scope, you might need:
// use core::fmt::Debug; // or std::fmt::Debug if std is assumed

/// A trait for conditionally creating objects.
///
/// In debug mode, it uses `Self::try_new().expect()` to create an instance,
/// panicking if `try_new` returns an error.
/// In release mode, it uses `Self::new()` to create an instance.
///
/// This trait requires the type to also implement [`TryNew`] and [`New`].
/// The error associated with [`TryNew`] (`<Self as TryNew>::Error`) must implement [`Debug`].
///
/// # Example
/// ```rust
/// use try_create::{ConditionallyCreate, TryNew, New, IntoInner};
/// # // Copied from TryNew example for self-containment, adjust if shared
/// # #[cfg(feature = "std")]
/// # use std::error::Error;
/// # #[cfg(feature = "std")]
/// # use std::fmt;
///
/// #[derive(Debug, PartialEq)]
/// struct NotPositiveError;
///
/// # #[cfg(feature = "std")]
/// impl fmt::Display for NotPositiveError {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         write!(f, "Value must be positive")
///     }
/// }
/// # #[cfg(feature = "std")]
/// impl Error for NotPositiveError {}
/// # #[cfg(not(feature = "std"))]
/// # trait Error: core::fmt::Debug {} // Minimal Error trait for no_std
/// # #[cfg(not(feature = "std"))]
/// # impl Error for NotPositiveError {}
///
///
/// #[derive(Debug, PartialEq)]
/// struct PositiveInteger { value: i32 }
///
/// impl IntoInner for PositiveInteger {
///     type InnerType = i32;
///     fn into_inner(self) -> Self::InnerType { self.value }
/// }
///
/// impl TryNew for PositiveInteger {
///     type Error = NotPositiveError;
///     fn try_new(value: Self::InnerType) -> Result<Self, Self::Error> {
///         if value > 0 { Ok(PositiveInteger { value }) }
///         else { Err(NotPositiveError) }
///     }
/// }
///
/// // To use ConditionallyCreate, PositiveInteger must also implement New.
/// impl New for PositiveInteger {
///     fn new(value: Self::InnerType) -> Self {
///         match Self::try_new(value) {
///             Ok(instance) => instance,
///             Err(e) => panic!("PositiveInteger::new failed for a non-positive value. Error: {:?}", e),
///         }
///     }
/// }
///
/// // Now you can call:
/// # fn example_usage() { // Encapsulate in a function for the doctest
/// let val_ok = 10;
/// let _p1 = PositiveInteger::create_conditionally(val_ok);
/// assert_eq!(_p1, PositiveInteger { value: 10 });
///
/// // In debug, this would panic (difficult to test directly in doctest without specific harness):
/// // let val_err = -5;
/// // let _p2 = PositiveInteger::create_conditionally(val_err);
/// # }
/// # example_usage();
/// ```
pub trait ConditionallyCreate: Sized + TryNew + New
where
    <Self as TryNew>::Error: core::fmt::Debug,
{
    /// Conditionally creates an instance of `Self`.
    ///
    /// # Parameters
    ///
    /// - `value`: The `Self::InnerType` value (defined by `IntoInner`)
    ///   from which to create the instance.
    ///
    /// # Panics
    ///
    /// In debug mode, this method will panic if `Self::try_new(value)`
    /// returns `Err`. The panic message will include the error's description.
    /// In release mode, the panic behavior depends on the implementation
    /// of `Self::new(value)`.
    fn create_conditionally(value: Self::InnerType) -> Self {
        #[cfg(debug_assertions)]
        {
            // In debug mode, use try_new and panic on error.
            Self::try_new(value).expect("ConditionallyCreate: try_new() failed in debug mode")
        }
        #[cfg(not(debug_assertions))]
        {
            // In release mode, use new (which is assumed to be infallible
            // or to handle failure internally, e.g., by panicking).
            Self::new(value)
        }
    }
}

// Blanket implementation of `ConditionallyCreate` for all types `T`
// that implement [`TryNew`] and [`New`], and whose `TryNew::Error` type
// implements `Debug`.
impl<T> ConditionallyCreate for T
where
    T: TryNew + New,
    <T as TryNew>::Error: core::fmt::Debug, // This bound is inherited from the trait definition
{
    // The `create_conditionally` method already has a default implementation in the trait,
    // so it doesn't need to be redefined here.
}

/// Defines a contract for validation policies.
///
/// A validation policy specifies how a value of a certain type (`Value`)
/// should be validated and what error type (`Error`) is returned upon failure.
///
/// # Associated Types
///
/// - `Value`: The type of the value to be validated.
/// - `Error`: The type of the error returned if validation fails. This error type
///   must implement [`std::error::Error`] if the `std` feature is enabled.
///   If the `std` feature is not enabled, it must implement [`core::fmt::Debug`].
pub trait ValidationPolicy {
    /// The type of the value to be validated.
    type Value;

    /// The type of the error returned if validation fails.
    #[cfg(feature = "std")]
    type Error: std::error::Error;
    #[cfg(not(feature = "std"))]
    type Error: core::fmt::Debug; // For no_std consistency

    /// Validates a value by consuming it.
    ///
    /// If validation is successful, the original value is returned.
    /// Otherwise, an error is returned.
    /// This default implementation calls [`Self::validate_ref()]`.
    fn validate(v: Self::Value) -> Result<Self::Value, Self::Error> {
        Self::validate_ref(&v)?;
        Ok(v)
    }

    /// Validates a value by reference.
    ///
    /// Returns `Ok(())` if validation is successful, otherwise an error is returned.
    /// This method must be implemented by concrete policies.
    fn validate_ref(v: &Self::Value) -> Result<(), Self::Error>;
}

/// A trait for creating new instances of a type with fallible validation,
/// where the validation logic is defined by an associated `ValidationPolicy`.
///
/// This trait extends [`TryNew`] by associating a specific [`ValidationPolicy`]
/// with the type. The [`Self::try_new_validated()`] method first uses this policy to validate
/// the input value. If validation succeeds, it then typically calls the underlying
/// `try_new` method (or a similar construction logic) to create the instance.
///
/// # Supertraits
///
/// - [`TryNew`]: Implementors of `TryNewValidated` must also implement `TryNew`.
///   This means they must define an `InnerType` (via the [`IntoInner`] supertrait of `TryNew`),
///   an `Error` type, and a `try_new` method.
pub trait TryNewValidated: TryNew {
    /// An implementor of [`ValidationPolicy`].
    /// - The `Value` associated type of this `Policy` must be the same as the
    ///   `InnerType` of `Self` (i.e., `Self::Policy::Value == <Self as IntoInner>::InnerType`).
    /// - The `Error` associated type of this `Policy` must be convertible into
    ///   `Self::Error` (the error type defined by the `TryNew` trait for `Self`).
    ///   This is ensured by the `From` bound on `Self::Error`.
    type Policy: ValidationPolicy<Value = <Self as IntoInner>::InnerType>;

    /// Attempts to create a new instance of `Self` from `value`.
    /// This method should first validate `value` using `Self::Policy::validate_ref(&value)`
    /// (or `Self::Policy::validate(value)` if consuming the value is intended by the policy).
    /// If validation is successful, it proceeds to construct the `Self` instance,
    /// typically by calling `Self::try_new(value)`.
    /// If validation fails, the error from the policy is converted into `Self::Error` and returned.
    /// If construction after successful validation fails, the error from `Self::try_new` is returned.
    fn try_new_validated(
        value: <Self as IntoInner>::InnerType,
    ) -> Result<Self, Self::Error>
    where
        Self: Sized;
}

#[duplicate_item(
    T;
    [f32];
    [f64];
    [i8];
    [i16];
    [i32];
    [i64];
    [i128];
    [u8];
    [u16];
    [u32];
    [u64];
    [u128];
    [isize];
    [usize];
    [bool];
    [char];
    [Complex<f32>];
    [Complex<f64>];
)]
impl New for T {
    /// Creates a new instance of the fundamental type from the given value.
    ///
    /// This implementation is infallible and simply returns the input value.
    fn new(value: Self::InnerType) -> Self {
        value
    }
}

#[duplicate_item(
    T;
    [f32];
    [f64];
    [i8];
    [i16];
    [i32];
    [i64];
    [i128];
    [u8];
    [u16];
    [u32];
    [u64];
    [u128];
    [isize];
    [usize];
    [bool];
    [char];
    [Complex<f32>];
    [Complex<f64>];
)]
impl TryNew for T {
    type Error = Infallible; // No error type needed for fundamental types

    /// Creates a new instance of the fundamental type from the given value.
    ///
    /// This implementation is infallible and simply returns the input value.
    fn try_new(value: Self::InnerType) -> Result<Self, Infallible> {
        Ok(value)
    }
}

#[cfg(test)]
mod tests {
    use super::*; // Import traits from the parent module (your library)

    // --- Test setup for PositiveInteger ---
    #[derive(Debug, PartialEq)]
    struct TestNotPositiveError;

    // Implement Display and Error for TestNotPositiveError for std builds
    #[cfg(feature = "std")]
    impl std::fmt::Display for TestNotPositiveError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "Value must be positive (Test Error)")
        }
    }

    #[cfg(feature = "std")]
    impl std::error::Error for TestNotPositiveError {}

    // For no_std, deriving Debug is sufficient as per TryNew's Error bound.

    #[derive(Debug, PartialEq)]
    struct TestPositiveInteger {
        value: i32,
    }

    impl IntoInner for TestPositiveInteger {
        type InnerType = i32;
        fn into_inner(self) -> Self::InnerType {
            self.value
        }
    }

    impl TryNew for TestPositiveInteger {
        type Error = TestNotPositiveError;
        fn try_new(value: Self::InnerType) -> Result<Self, Self::Error> {
            if value > 0 {
                Ok(TestPositiveInteger { value })
            } else {
                Err(TestNotPositiveError)
            }
        }
    }

    impl New for TestPositiveInteger {
        fn new(value: Self::InnerType) -> Self {
            // Consistent with the example: panic if try_new would fail
            match Self::try_new(value) {
                Ok(instance) => instance,
                Err(_) => panic!("TestPositiveInteger::new: Value must be positive."),
            }
        }
    }

    mod try_new {
        use super::*; // Import traits from the parent module (your library)

        // --- Tests for PositiveInteger ---
        #[test]
        fn test_positive_integer_try_new_ok() {
            assert_eq!(
                TestPositiveInteger::try_new(10),
                Ok(TestPositiveInteger { value: 10 })
            );
        }

        #[test]
        fn test_positive_integer_try_new_err_zero() {
            assert_eq!(TestPositiveInteger::try_new(0), Err(TestNotPositiveError));
        }

        #[test]
        fn test_positive_integer_try_new_err_negative() {
            assert_eq!(TestPositiveInteger::try_new(-5), Err(TestNotPositiveError));
        }

        // --- Tests for MyType ---
        #[test]
        fn test_my_type_try_new_ok() {
            assert_eq!(TestMyType::try_new(5), Ok(TestMyType(5)));
        }

        #[test]
        fn test_my_type_try_new_err() {
            assert_eq!(
                TestMyType::try_new(-1),
                Err(TestMyTypeError("Value cannot be negative".to_string()))
            );
        }
    } // mod try_new

    mod new {
        use super::*; // Import traits from the parent module (your library)

        #[test]
        fn test_positive_integer_new_ok() {
            assert_eq!(
                TestPositiveInteger::new(10),
                TestPositiveInteger { value: 10 }
            );
        }

        #[test]
        #[should_panic(expected = "TestPositiveInteger::new: Value must be positive.")]
        fn test_positive_integer_new_panic_zero() {
            TestPositiveInteger::new(0);
        }

        #[test]
        #[should_panic(expected = "TestPositiveInteger::new: Value must be positive.")]
        fn test_positive_integer_new_panic_negative() {
            TestPositiveInteger::new(-10);
        }

        #[test]
        fn test_my_type_new_ok() {
            assert_eq!(TestMyType::new(100), TestMyType(100));
        }

        #[test]
        #[should_panic(expected = "TestMyType::new: Value cannot be negative")]
        fn test_my_type_new_panic() {
            TestMyType::new(-1);
        }
    } // mod new

    mod into_inner {
        use super::*;

        #[test]
        fn test_positive_integer_into_inner() {
            let pi = TestPositiveInteger::new(42);
            assert_eq!(pi.into_inner(), 42);
        }

        #[test]
        fn test_my_type_into_inner() {
            let mt = TestMyType::new(7);
            assert_eq!(mt.into_inner(), 7);
        }
    }

    // --- Test setup for MyType (from New example) ---
    #[derive(Debug, PartialEq)]
    struct TestMyTypeError(String);

    #[cfg(feature = "std")]
    impl std::fmt::Display for TestMyTypeError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "TestMyTypeError: {}", self.0)
        }
    }

    #[cfg(feature = "std")]
    impl std::error::Error for TestMyTypeError {}

    #[derive(Debug, PartialEq)]
    struct TestMyType(i32);

    impl IntoInner for TestMyType {
        type InnerType = i32;
        fn into_inner(self) -> Self::InnerType {
            self.0
        }
    }

    impl TryNew for TestMyType {
        type Error = TestMyTypeError;
        fn try_new(value: i32) -> Result<Self, Self::Error> {
            if value < 0 {
                Err(TestMyTypeError("Value cannot be negative".to_string()))
            } else {
                Ok(TestMyType(value))
            }
        }
    }

    impl New for TestMyType {
        fn new(value: i32) -> Self {
            if value < 0 {
                panic!("TestMyType::new: Value cannot be negative");
            }
            TestMyType(value)
        }
    }

    mod conditionally_create {
        use super::*;

        #[test]
        #[cfg(debug_assertions)] // This test specifically targets the debug behavior
        fn test_positive_integer_conditionally_create_debug_ok() {
            assert_eq!(
                TestPositiveInteger::create_conditionally(10),
                TestPositiveInteger { value: 10 }
            );
        }

        #[test]
        #[cfg(debug_assertions)] // This test specifically targets the debug behavior
        #[should_panic(expected = "ConditionallyCreate: try_new() failed in debug mode")]
        fn test_positive_integer_conditionally_create_debug_panic() {
            TestPositiveInteger::create_conditionally(-5);
        }

        #[test]
        #[cfg(not(debug_assertions))] // This test specifically targets the release behavior
        fn test_positive_integer_conditionally_create_release_ok() {
            assert_eq!(
                TestPositiveInteger::create_conditionally(10),
                TestPositiveInteger { value: 10 }
            );
        }

        #[test]
        #[cfg(not(debug_assertions))] // This test specifically targets the release behavior
        #[should_panic(expected = "TestPositiveInteger::new: Value must be positive.")]
        fn test_positive_integer_conditionally_create_release_panic() {
            // In release, create_conditionally calls new(), which for TestPositiveInteger panics.
            TestPositiveInteger::create_conditionally(-5);
        }

        #[test]
        #[cfg(debug_assertions)]
        fn test_my_type_conditionally_create_debug_ok() {
            assert_eq!(TestMyType::create_conditionally(20), TestMyType(20));
        }

        #[test]
        #[cfg(debug_assertions)]
        #[should_panic(expected = "ConditionallyCreate: try_new() failed in debug mode")]
        fn test_my_type_conditionally_create_debug_panic() {
            TestMyType::create_conditionally(-3);
        }

        #[test]
        #[cfg(not(debug_assertions))]
        fn test_my_type_conditionally_create_release_ok() {
            assert_eq!(TestMyType::create_conditionally(20), TestMyType(20));
        }

        #[test]
        #[cfg(not(debug_assertions))]
        #[should_panic(expected = "TestMyType::new: Value cannot be negative")]
        fn test_my_type_conditionally_create_release_panic() {
            TestMyType::create_conditionally(-3);
        }
    }

    mod try_new_validated {
        use super::*;

        // --- Test setup for ValidationPolicy and TryNewValidated ---

        // 1. Define a concrete ValidationPolicy
        #[derive(Debug, PartialEq)]
        struct TestPolicyError(String);

        #[cfg(feature = "std")]
        impl std::fmt::Display for TestPolicyError {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "TestPolicyError: {}", self.0)
            }
        }

        #[cfg(feature = "std")]
        impl std::error::Error for TestPolicyError {}

        struct MinValuePolicy {
            min_value: i32,
        }

        impl ValidationPolicy for MinValuePolicy {
            type Value = i32;
            type Error = TestPolicyError;

            fn validate_ref(v: &Self::Value) -> Result<(), Self::Error> {
                // For this test, let's imagine a global or static policy.
                // A real policy might take its configuration (e.g., min_value) at construction.
                // For simplicity, we'll hardcode a value or use a fixed one.
                // Let's make it simple: value must be >= 0 for this policy.
                if *v >= 0 {
                    Ok(())
                } else {
                    Err(TestPolicyError("Value must be non-negative.".to_string()))
                }
            }
            // `validate` method uses the default implementation.
        }

        // 2. Define a concrete type that implements TryNewValidated

        #[derive(Debug, PartialEq)]
        enum TestValidatedTypeError {
            Policy(TestPolicyError),
            Construction(String),
        }

        #[cfg(feature = "std")]
        impl std::fmt::Display for TestValidatedTypeError {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match self {
                    TestValidatedTypeError::Policy(e) => write!(f, "Policy error: {}", e),
                    TestValidatedTypeError::Construction(s) => {
                        write!(f, "Construction error: {}", s)
                    }
                }
            }
        }

        #[cfg(feature = "std")]
        impl std::error::Error for TestValidatedTypeError {
            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
                match self {
                    TestValidatedTypeError::Policy(e) => Some(e),
                    TestValidatedTypeError::Construction(_) => None,
                }
            }
        }
        // No-std: Debug is derived.

        impl From<TestPolicyError> for TestValidatedTypeError {
            fn from(e: TestPolicyError) -> Self {
                TestValidatedTypeError::Policy(e)
            }
        }

        #[derive(Debug, PartialEq)]
        struct MyValidatedType {
            value: i32,
        }

        impl IntoInner for MyValidatedType {
            type InnerType = i32;
            fn into_inner(self) -> Self::InnerType {
                self.value
            }
        }

        impl TryNew for MyValidatedType {
            type Error = TestValidatedTypeError;

            fn try_new(value: Self::InnerType) -> Result<Self, Self::Error> {
                // Inner construction logic: value must be > 10
                if value > 10 {
                    Ok(MyValidatedType { value })
                } else {
                    Err(TestValidatedTypeError::Construction(
                        "Value must be greater than 10 for construction.".to_string(),
                    ))
                }
            }
        }

        impl TryNewValidated for MyValidatedType {
            type Policy = MinValuePolicy; // Using the policy defined above

            fn try_new_validated(value: <Self as IntoInner>::InnerType) -> Result<Self, Self::Error>
            where
                Self: Sized,
                Self::Error: From<<Self::Policy as ValidationPolicy>::Error>,
            {
                // 1. Validate using the policy. The `?` handles error conversion.
                Self::Policy::validate_ref(&value)?;

                // 2. If policy validation passes, proceed with `try_new`.
                Self::try_new(value)
            }
        }

        // --- Tests for ValidationPolicy (using MinValuePolicy) ---
        #[test]
        fn validation_policy_validate_ref_ok() {
            assert_eq!(MinValuePolicy::validate_ref(&5), Ok(()));
            assert_eq!(MinValuePolicy::validate_ref(&0), Ok(()));
        }

        #[test]
        fn validation_policy_validate_ref_err() {
            assert_eq!(
                MinValuePolicy::validate_ref(&-5),
                Err(TestPolicyError("Value must be non-negative.".to_string()))
            );
        }

        #[test]
        fn validation_policy_validate_consuming_ok() {
            // Tests the default `validate` method
            assert_eq!(MinValuePolicy::validate(5), Ok(5));
            assert_eq!(MinValuePolicy::validate(0), Ok(0));
        }

        #[test]
        fn validation_policy_validate_consuming_err() {
            // Tests the default `validate` method
            assert_eq!(
                MinValuePolicy::validate(-5),
                Err(TestPolicyError("Value must be non-negative.".to_string()))
            );
        }

        // --- Tests for TryNewValidated (using MyValidatedType) ---
        #[test]
        fn try_new_validated_success() {
            // Policy (>=0) passes for 15. try_new (>10) passes for 15.
            assert_eq!(
                MyValidatedType::try_new_validated(15),
                Ok(MyValidatedType { value: 15 })
            );
        }

        #[test]
        fn try_new_validated_policy_fail() {
            // Policy (>=0) fails for -5.
            let result = MyValidatedType::try_new_validated(-5);
            assert!(matches!(result, Err(TestValidatedTypeError::Policy(..))));
        }

        #[test]
        fn try_new_validated_construction_fail_after_policy_pass() {
            // Policy (>=0) passes for 5. try_new (>10) fails for 5.
            let result = MyValidatedType::try_new_validated(5);
            assert!(matches!(
                result,
                Err(TestValidatedTypeError::Construction(..))
            ));
        }

        #[test]
        fn try_new_validated_policy_pass_construction_pass_edge() {
            // Policy (>=0) passes for 11. try_new (>10) passes for 11.
            assert_eq!(
                MyValidatedType::try_new_validated(11),
                Ok(MyValidatedType { value: 11 })
            );
        }

        #[test]
        fn try_new_validated_policy_pass_construction_fail_edge() {
            // Policy (>=0) passes for 10. try_new (>10) fails for 10.
            let result = MyValidatedType::try_new_validated(10);
            assert!(matches!(
                result,
                Err(TestValidatedTypeError::Construction(..))
            ));
        }
    }
}