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
//! Universal extension trait.Implemented for every type.

use std_::marker::PhantomData;

use phantom_variances::*;
use TypeIdentity;

// use std::mem;

/// Extension trait for every type.
///
/// The most importand methods in this are:
///
/// - [piped](#method.piped):
///      Allows emulating the pipeline operator.
///
/// - [mutated](#method.mutated):
///      Allows mutating `self` with a closure passing it along the method chain
///
/// - [observe](./trait.SelfOps.html#method.observe):
///     Observes the value of `self` with a closure passing
///     it along the method chain unmodified.
///
/// - [into_](#method.into_),
///   [as_ref_](#method.as_ref_),
///   [as_mut_](#method.as_mut_):
///      Alternative syntax for the standard conversion methods.
///
pub trait SelfOps {
    /// Represents Self by using a VariantPhantom<Self>,
    /// using the syntax `Type::T` to pass it in methods with `_:VariantPhantom<T>` parameters.
    ///
    /// # Example
    ///
    /// ```
    /// use core_extensions::{SelfOps,IteratorExt};
    ///
    /// assert_eq!((0..4).collect_(Vec::T       ),vec![0,1,2,3]);
    /// assert_eq!((0..4).collect_(Vec::<_>::T  ),vec![0,1,2,3]);
    /// assert_eq!((0..4).collect_(Vec::<i32>::T),vec![0,1,2,3]);
    /// ```
    ///
    ///
    const T: VariantPhantom<Self> = PhantomData;

    /// Represents Self by using a VariantDropPhantom<Self>,for specialized cases.
    ///
    /// For advanced use cases when one needs a drop check on a PhantomData.
    const T_D: VariantDropPhantom<Self> = PhantomData;

    #[inline(always)]
    /// Asserts that `other` is the same type as `self`.
    fn assert_ty(self, _other: VariantPhantom<Self>) -> Self
    where
        Self: Sized,
    {
        self
    }

    #[inline(always)]
    /// Asserts that `other` is the same type as `self`.
    fn assert_ty_ref(&self, _other: VariantPhantom<Self>) -> &Self
    where
        Self: Sized,
    {
        self
    }

    #[inline(always)]
    /// Asserts that `other` is the same type as `self`.
    fn assert_ty_mut(&mut self, _other: VariantPhantom<Self>) -> &mut Self
    where
        Self: Sized,
    {
        self
    }

    #[inline(always)]
    /// Equivalent to [SelfOps::T](#associatedconstant.T),as a method.
    ///
    /// Reasons for calling this method instead:
    ///
    /// - The type is longer that the code required to instantiate it.
    ///
    /// - To assert that 2 variables have the same type,using `var0.ty_()==var1.ty_()`.
    ///
    fn ty_(&self) -> VariantPhantom<Self> {
        PhantomData
    }

    #[inline(always)]
    /// Equivalent to [Self::ty_],for specialized cases.
    ///
    /// For specialized cases when one needs a drop check on a PhantomData.
    fn ty_d(&self) -> VariantDropPhantom<Self> {
        PhantomData
    }

    #[inline(always)]
    /// Equivalent to [Self::ty_] with an invariant type.
    fn ty_inv(&self) -> InvariantPhantom<Self> {
        PhantomData
    }

    #[inline(always)]
    /// Equivalent to [Self::ty_] with an invariant lifetime.
    fn ty_inv_ref(&self) -> InvariantRefPhantom<Self> {
        PhantomData
    }

    /// Identity comparison to another value of the same type.
    ///
    /// Comparing the address of `self` with the address of `other`.
    ///
    /// # Example
    ///
    /// ```
    /// use core_extensions::SelfOps;
    ///
    /// let a=5.to_string();
    /// let b=5.to_string();
    ///
    /// assert!(!a.eq_id(&b));
    /// assert!(!b.eq_id(&a));
    /// assert!( a.eq_id(&a));
    /// assert!( b.eq_id(&b));
    /// assert_eq!(a,b);
    ///
    /// ```
    fn eq_id(&self, other: &Self) -> bool {
        (self as *const Self) == (other as *const Self)
    }

    /// Emulates the pipeline operator,allowing method syntax in more places.
    ///
    /// Allows calling functions as part of a method chain.
    ///
    ///
    /// # Example
    ///
    /// ```
    /// use core_extensions::SelfOps;
    /// use std::sync::{Mutex,Arc};
    ///
    /// let hello="hello"
    ///     .to_string()
    ///     .mutated(|s| s.push_str("_world") )
    ///     .piped(Mutex::new)
    ///     .piped(Arc::new);
    ///
    /// assert_eq!(hello.lock().unwrap().as_str(),"hello_world");
    /// ```
    ///
    /// # Example,calling functions
    /// ```
    /// use core_extensions::SelfOps;
    ///
    /// # fn opposed<S:AsRef<str>>(s:S)->String{
    /// #     let s=s.as_ref();
    /// #     format!("{}{}",s,s.chars().rev().collect::<String>())
    /// # }
    /// #
    /// "what"
    ///     .piped(|x|opposed(x)+"-")
    ///     .observe(|s| assert_eq!(s,"whattahw-") )
    ///     .piped(opposed)
    ///     .observe(|s| assert_eq!(s,"whattahw--whattahw") );
    /// ```
    ///
    #[inline(always)]
    fn piped<F, U>(self, f: F) -> U
    where
        F: FnOnce(Self) -> U,
        Self: Sized,
    {
        f(self)
    }

    /// The same as `piped` except that the function takes `&Self`
    /// Useful for functions that take `&Self` instead of `Self`.
    ///
    /// # Example
    ///
    /// ```
    /// use core_extensions::SelfOps;
    ///
    /// let problem="air".to_string();
    /// let edited=problem.piped_ref(|s| format!("{} problems.",s) );
    ///
    /// println!("{:?}",problem); // problem wasn't consumed by `.piped_ref`
    /// assert_eq!(edited,"air problems.");
    ///
    /// ```
    ///
    #[inline(always)]
    fn piped_ref<'a, F, U>(&'a self, f: F) -> U
    where
        F: FnOnce(&'a Self) -> U,
    {
        f(self)
    }

    /// The same as `piped` except that the function takes `&mut Self`.
    /// Useful for functions that take `&mut Self` instead of `Self`.
    ///
    #[inline(always)]
    fn piped_mut<'a, F, U>(&'a mut self, f: F) -> U
    where
        F: FnOnce(&'a mut Self) -> U,
    {
        f(self)
    }

    /// Mutates self using a closure taking self by mutable reference,
    /// passing it along the method chain.
    ///
    /// This is useful for initializing a variable and then freezing it.
    ///
    /// # Example of initialization
    ///
    /// ```
    /// use core_extensions::SelfOps;
    /// let list=Vec::new().mutated(|v|{
    ///     v.push("This");
    ///     v.push("is");
    ///     v.push("[redacted]");
    /// });
    /// assert_eq!(list.join(" "),"This is [redacted]");
    ///
    /// ```
    ///
    /// # Example of mutating in a method chain
    /// ```
    /// use core_extensions::SelfOps;
    ///
    /// "what".to_string()
    ///     .mutated(|v| v.push_str(" the") )
    ///     .observe(|v| assert_eq!(v,"what the") );
    ///
    /// ```
    ///  
    #[inline(always)]
    fn mutated<F>(mut self, f: F) -> Self
    where
        F: FnOnce(&mut Self),
        Self: Sized,
    {
        f(&mut self);
        self
    }
    /// Observes the value of self passing it along unmodified.
    /// Useful in a long method chain.
    ///
    /// # Example
    ///
    /// ```
    /// use core_extensions::SelfOps;
    /// let v="1234"
    ///     .parse()
    ///     .observe(|d|assert_eq!(&Ok(1234),d))
    ///     .unwrap();
    /// assert_eq!(v,1234);
    /// ```
    ///
    #[inline(always)]
    fn observe<F>(self, f: F) -> Self
    where
        F: FnOnce(&Self),
        Self: Sized,
    {
        f(&self);
        self
    }

    /// Performs a conversion using Into.
    ///
    /// This method is defined to allow using the `.into_(String::T)` syntax.
    ///
    /// type::T is an associated constant defined for every type
    /// [here](#associatedconstant.T).
    ///
    /// # Example
    /// ```
    /// use core_extensions::SelfOps;
    /// use std::borrow::Cow;
    ///
    /// let word="hello";
    /// assert_eq!(word,word.into_(Cow::T));
    /// assert_eq!(word,word.into_(Cow::<str>::T));
    /// assert_eq!(word,word.into_(String::T));
    ///
    /// let vec_=||vec![0,1,2,3];
    /// assert_eq!(vec_().into_(Cow::T)           ,vec_());
    /// assert_eq!(vec_().into_(Cow::<[usize]>::T),vec_());
    /// assert_eq!(vec_().into_(Vec::T)           ,vec_());
    /// assert_eq!(vec_().into_(Vec::<usize>::T)  ,vec_());
    ///
    /// ```
    #[inline(always)]
    fn into_<T>(self, _: VariantPhantom<T>) -> T
    where
        Self: Into<T>,
    {
        self.into()
    }

    /// Performs a reference to reference conversion using AsRef,
    /// using the turbofish `.as_ref_::<_>()` syntax.
    ///
    /// # Example
    /// ```
    /// use core_extensions::SelfOps;
    /// let s="the path";
    /// assert_eq!( s,s.as_ref_::<str>());
    /// ```
    #[inline(always)]
    fn as_ref_<T: ?Sized>(&self) -> &T
    where
        Self: AsRef<T>,
    {
        self.as_ref()
    }
    /// Performs a mutable reference to mutable reference conversion using AsMut,
    /// using the turbofish `.as_mut_::<_>()` syntax.
    ///
    /// # Example
    /// ```
    /// use core_extensions::SelfOps;
    /// let mut s_0=vec![1,2,3,4];
    /// let mut s_1=s_0.clone();
    /// assert_eq!(s_1,s_0.as_mut_::<[_]>());
    /// ```
    #[inline(always)]
    fn as_mut_<T: ?Sized>(&mut self) -> &mut T
    where
        Self: AsMut<T>,
    {
        self.as_mut()
    }
    /// Drops `self` using method notation.
    /// Alternative to `std::mem::drop`.
    ///
    /// # Example,ignore #\[must_use\] values.
    /// ```
    /// #![deny(unused_must_use)]
    /// use std::fmt::Write;
    /// use core_extensions::SelfOps;
    ///
    /// let mut buff=String::new();
    ///
    /// buff.write_str("hello_").drop_();
    /// buff.write_str("world").drop_();
    /// assert_eq!(buff,"hello_world");
    ///
    /// ```
    #[inline(always)]
    fn drop_(self)
    where
        Self: Sized,
    {
    }

    #[doc(hidden)]
    #[allow(dead_code)]
    /// Prevents creating a trait object of this trait
    fn _dummy_generic_method_preventing_trait_object<F>(self: &Self)
    where
        F: TypeIdentity<Type = Self>,
    {

    }
}
impl<T: ?Sized> SelfOps for T {}