hexga_core/default.rs
1//! A *shorter* way to write default. Provide :
2//!
3//! - `___()` as a shorthand for `Default::default()`
4//! - `i32::___()` instead of `i32::default()`
5//!
6//! Based on the [internals Rust discussion](https://internals.rust-lang.org/t/could-we-have-std-default/8756)
7//!
8//! Also check the [Defaults crate](https://github.com/dpc/rust-default) which use `default()` instead of `Default::default()`
9
10/// `___()` is a shorthand for `Default::default()`
11///
12/// # Examples
13///
14/// ```
15/// use hexga_core::prelude::*;
16///
17/// let b : i32 = Default::default(); // Default Rust
18/// let a : i32 = ___(); // Now
19
20/// assert_eq!(a, b);
21/// ```
22///
23/// Can also be used with function :
24///
25/// ```ignore
26/// let a = f(Default::default()); // Default Rust
27/// let b = f(___()); // Now
28/// assert_eq!(a, b);
29/// ```
30///
31/// Can also be used to initialize complex Rust struct when implementing the `Default` trait :
32///
33/// ```ignore
34/// impl Default for ComplexStruct {
35/// fn default() -> Self {
36/// Self { a : ___(), b : ___(), c : ___(), vec : vec![0] }
37/// // instead of
38/// // Self { a : Default::default(), b : Default::default(), c : Default::default(), vec : vec![0] }
39/// }
40/// }
41/// ````
42///
43/// And also to partially initialize a struct
44///
45/// ```ignore
46/// let a = BigStruct { x : 42, y : 64, ..Default::default() };
47/// let b = BigStruct { x : 42, y : 64, ..___() };
48/// assert_eq!(a, b);
49/// ```
50pub fn ___<T: Default>() -> T { core::default::Default::default() }
51
52/// Uniform syntax : `MyStruct::___()` instead of `MyStruct::default()`
53pub trait DefaultIsTripleUnderscore: Default
54{
55 /// The `Self::default()` method.
56 ///
57 /// Returns the "default value" for a type.
58 ///
59 /// ```ignore
60 /// type T = i32; // any type with default
61 /// assert_eq!(T::default(), T::___());
62 /// ```
63 fn ___() -> Self { Self::default() }
64}
65
66impl<T: Default> DefaultIsTripleUnderscore for T
67{
68 fn ___() -> Self { Self::default() }
69}
70
71pub trait DefaultExtension: Default + PartialEq
72{
73 fn is_default(&self) -> bool { self == &___() }
74 fn is_not_default(&self) -> bool { !self.is_default() }
75}
76impl<T> DefaultExtension for T where T: Default + PartialEq {}