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 {
51 std::default::Default::default()
52}
53
54/// Uniform syntax : `MyStruct::___()` instead of `MyStruct::default()`
55pub trait DefaultIsTripleUnderscore : Default
56{
57 /// The `Self::default()` method.
58 ///
59 /// Returns the "default value" for a type.
60 ///
61 /// ```ignore
62 /// type T = i32; // any type with default
63 /// assert_eq!(T::default(), T::___());
64 /// ```
65 fn ___() -> Self { Self::default() }
66}
67
68impl<T:Default> DefaultIsTripleUnderscore for T
69{
70 fn ___() -> Self {
71 Self::default()
72 }
73}
74
75pub trait DefaultExtension : Default + PartialEq
76{
77 fn is_default(&self) -> bool { self == &___() }
78 fn is_not_default(&self) -> bool { !self.is_default() }
79}
80impl<T> DefaultExtension for T where T: Default + PartialEq {}