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
use super::fam::{Applicative, Either, Maybe, Vector};
use crate::no_std::{
functions::ext::fn_once_ext::FnOnceExt,
pipelines::{pipe::Pipe, tap::Tap},
};
use alloc::{borrow::Cow, boxed::Box, format, rc::Rc, str, string::String, sync::Arc, vec::Vec};
use core::{
cell::{Cell, RefCell},
ops::{BitXorAssign, Not},
str::Utf8Error,
};
use itertools::Itertools;
/// This trait is to implement some extension functions,
/// which need a generic return type, for any sized type.
pub trait AnyExt1<R>: Sized {
/// The Y Combinator
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// fn factorial(n: u8) -> u8 {
/// n.y(|f, n| match n {
/// 0 => 1,
/// n => n * f(n - 1),
/// })
/// }
/// assert_eq!(factorial(5), 5 * 4 * 3 * 2 * 1);
///
/// fn fibonacci(n: u8) -> u8 {
/// n.y(|f, n| match n {
/// 0 => 0,
/// 1 => 1,
/// n => f(n - 1) + f(n - 2),
/// })
/// }
/// assert_eq!(fibonacci(10), 55);
/// ```
fn y(self, f: impl Copy + Fn(&dyn Fn(Self) -> R, Self) -> R) -> R {
// The Y Combinator
fn y<T, R>(f: impl Copy + Fn(&dyn Fn(T) -> R, T) -> R) -> impl Fn(T) -> R {
move |a| f(&y(f), a)
}
// Chainable
y(f)(self)
}
/// Returns `Some(f())` if it satisfies the given predicate function,
/// or `None` if it doesn't.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// assert_eq!("Hello World".to_string().into_some(), "Hello".if_then(|s| s.starts_with("Hel"), |s| format!("{} World", s)));
/// assert_eq!(None, "Hello".if_then(|s| s.starts_with("Wor"), |_| ()));
/// ```
fn if_then(self, r#if: impl FnOnce(&Self) -> bool, then: impl FnOnce(Self) -> R) -> Option<R> {
if r#if(&self) {
then(self).into_some()
} else {
None
}
}
/// Returns `Some(f())` if it doesn't satisfy the given predicate function,
/// or `None` if it does.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// assert_eq!(None, "Hello".if_not_then(|s| s.starts_with("Hel"), |_| ()));
/// assert_eq!("Hello World".to_string().into_some(), "Hello".if_not_then(|s| s.starts_with("Wor"), |s| format!("{} World", s)));
/// ```
fn if_not_then(
self,
unless: impl FnOnce(&Self) -> bool,
then: impl FnOnce(Self) -> R,
) -> Option<R> {
self.if_then(|x| Not::not.compose(unless)(x), then)
}
}
impl<T, R> AnyExt1<R> for T {}
/// This trait is to implement some extension functions for any sized type.
pub trait AnyExt: Sized {
/// Chainable `drop`
fn drop(self) {}
/// Convert `value` to `Some(value)`
fn into_some(self) -> Option<Self> {
self.pipe(Maybe::pure)
}
/// Convert `value` to `Ok(value)`
fn into_ok<B>(self) -> Result<Self, B> {
self.pipe(Either::pure)
}
/// Convert `value` to `Err(value)`
fn into_err<A>(self) -> Result<A, Self> {
Result::from(Err(self))
}
/// Convert `value` to `Box::new(value)`
fn into_box(self) -> Box<Self> {
self.pipe(Box::new)
}
/// Convert `value` to `Cell::new(value)`
fn into_cell(self) -> Cell<Self> {
self.pipe(Cell::new)
}
/// Convert `value` to `RefCell::new(value)`
fn into_refcell(self) -> RefCell<Self> {
self.pipe(RefCell::new)
}
/// Convert `value` to `Rc::new(value)`
fn into_rc(self) -> Rc<Self> {
self.pipe(Rc::new)
}
/// Convert `value` to `Rc::new(Cell::new(value))`
fn into_rc_cell(self) -> Rc<Cell<Self>> {
Rc::new.compose(Cell::new)(self)
}
/// Convert `value` to `Rc::new(RefCell::new(value))`
fn into_rc_refcell(self) -> Rc<RefCell<Self>> {
Rc::new.compose(RefCell::new)(self)
}
/// Convert `value` to `Arc::new(value)`
fn into_arc(self) -> Arc<Self> {
self.pipe(Arc::new)
}
/// Consumes `self`,
/// returns the name of its type as a string slice and the receiver `self`.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// assert_eq!("".type_name(), "&str");
/// assert_eq!((&"").type_name(), "&&str");
/// ```
fn type_name(self) -> &'static str {
core::any::type_name::<Self>()
}
/// Consumes `self`,
/// returns the size of its type in number and the receiver `self`.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// assert_eq!(().type_size(), 0);
/// assert_eq!((&()).type_size(), 8);
/// assert_eq!([(), ()].type_size(), 0);
/// ```
fn type_size(self) -> usize {
core::mem::size_of::<Self>()
}
/// Consumes `self`,
/// returns the name of its type as a string slice and the receiver `self`.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// assert_eq!("".type_name_with_value().0, "&str");
/// assert_eq!("s".type_name_with_value().1, "s");
/// assert_eq!((&"").type_name_with_value().0, "&&str");
/// ```
fn type_name_with_value(self) -> (&'static str, Self) {
(core::any::type_name::<Self>(), self)
}
/// Consumes `self`,
/// returns the size of its type in number and the receiver `self`.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// assert_eq!(().type_size_with_value().0, 0);
/// assert_eq!(().type_size_with_value().1, ());
/// assert_eq!((&()).type_size_with_value().0, 8);
/// assert_eq!([(), ()].type_size_with_value().0, 0);
/// ```
fn type_size_with_value(self) -> (usize, Self) {
(core::mem::size_of::<Self>(), self)
}
/// Returns `Some(self)` if it satisfies the given predicate function,
/// or `None` if it doesn't.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// assert_eq!(Some("Hello"), "Hello".if_take(|s| s.starts_with("Hel")));
/// assert_eq!(None, "Hello".if_take(|s| s.starts_with("Wor")));
/// ```
fn if_take(self, f: impl FnOnce(&Self) -> bool) -> Option<Self> {
self.if_not_then(|x| Not::not.compose(f)(x), |s| s)
}
/// Returns `Some(self)` if it doesn't satisfy the given predicate function,
/// or `None` if it does.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// assert_eq!(None, "Hello".if_not_take(|s| s.starts_with("Hel")));
/// assert_eq!(Some("Hello"), "Hello".if_not_take(|s| s.starts_with("Wor")));
/// ```
fn if_not_take(self, f: impl FnOnce(&Self) -> bool) -> Option<Self> {
self.if_take(|x| Not::not.compose(f)(x))
}
}
impl<T> AnyExt for T {}
/// This trait is to implement some extension functions for `bool` type.
pub trait BoolExt<R> {
fn if_true(self, value: R) -> Option<R>;
fn if_false(self, value: R) -> Option<R>;
fn then_false(self, f: impl FnOnce() -> R) -> Option<R>;
}
impl<R> BoolExt<R> for bool {
/// Chainable `if`, returns `Some(value)` when the condition is `true`
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// let s = "Hello World";
/// assert_eq!(Some("lo Wo"), s.starts_with("Hel").if_true(&s[3..8]));
/// assert_eq!(None, s.starts_with("Wor").if_true(&s[3..8]));
/// ```
fn if_true(self, value: R) -> Option<R> {
self.if_not_then(|s| s.not(), |_| value)
}
/// Chainable `if`, returns `Some(value)` when the condition is `false`
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// let s = "Hello World";
/// assert_eq!(None, s.starts_with("Hel").if_false(&s[3..8]));
/// assert_eq!(Some("lo Wo"), s.starts_with("Wor").if_false(&s[3..8]));
/// ```
fn if_false(self, value: R) -> Option<R> {
self.if_not_then(|s| *s, |_| value)
}
/// Returns `Some(f())` if the receiver is `false`, or `None` otherwise
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// let s = "Hello World";
///
/// // then:
/// assert_eq!(Some("lo Wo"), s.starts_with("Hel").then(|| &s[3..8]));
/// assert_eq!(None, s.starts_with("Wor").then(|| &s[3..8]));
///
/// // then_false:
/// assert_eq!(None, s.starts_with("Hel").then_false(|| &s[3..8]));
/// assert_eq!(Some("lo Wo"), s.starts_with("Wor").then_false(|| &s[3..8]));
/// ```
fn then_false(self, f: impl FnOnce() -> R) -> Option<R> {
self.if_not_then(|s| *s, |_| f())
}
}
/// This trait is to implement some extension functions for `[T]` type.
pub trait ArrExt {
fn swap_xor(self, i: usize, j: usize) -> Self;
}
impl<T> ArrExt for &mut [T]
where
T: BitXorAssign<T> + Copy,
{
/// Swaps two elements in a slice.
///
/// # Parameters
///
/// * i - The index of the first element
/// * j - The index of the second element
///
/// # Panics
///
/// Panics if `i` or `j` are out of bounds.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// let mut v = [0, 1, 2, 3, 4];
/// v.swap_xor(1, 3);
/// assert!(v == [0, 3, 2, 1, 4]);
/// ```
///
/// # Principles
///
/// * a = 甲, b = 乙
///
/// * a = a ^ b => a = 甲 ^ 乙, b = 乙
/// * b = a ^ b => a = 甲 ^ 乙, b = 甲 ^ (乙 ^ 乙) = 甲 ^ 0 = 甲
/// * a = a ^ b => a = 甲 ^ 乙 ^ 甲 = 甲 ^ 甲 ^ 乙 = 0 ^ 乙 = 乙
fn swap_xor(self, i: usize, j: usize) -> Self {
self.tap_mut(|s| {
if i != j {
s[i] ^= s[j];
s[j] ^= s[i];
s[i] ^= s[j];
}
})
}
}
pub trait StrExt {
fn split_not_empty_and_join(self, split: &str, join: &str) -> String;
fn wildcard_match(self, pattern_text: &str) -> bool;
}
impl StrExt for &str {
fn split_not_empty_and_join(self, split: &str, join: &str) -> String {
self.split(split)
.filter(|s| s.bytes().next().is_some())
.join(join)
}
/// https://gist.github.com/mo-xiaoming/9fb87da16d6ef459e1b94c16055b9978
///
/// # Examples
///
/// ```
/// use std::ops::Not;
/// use ext::{asserts, no_std::functions::ext::*};
///
/// asserts! {
/// "abc".wildcard_match("abc");
/// "a0c".wildcard_match("abc*").not();
/// "mississippi".wildcard_match("mississipp**");
/// "mississippi".wildcard_match("mississippi*");
/// "mississippi.river".wildcard_match("*.*");
/// "mississippi.river".wildcard_match("*ip*");
/// "mississippi.river".wildcard_match("m*i*.*r");
/// "mississippi.river".wildcard_match("m*x*.*r").not();
/// }
/// ```
fn wildcard_match(self, pattern: &str) -> bool {
struct AfterWildcard {
plain_idx: usize,
pattern_idx: usize,
}
// it is None if there are no prev wildcard
// if there were, then `plain_idx` stores *next* index in plain text that wildcard supposes to match
// `pattern_idx` stores *next* index right after the wildcard
// when they first assigned
// latter they become to be the next possible non matches
// anything pre these two considered match
let mut after_wildcard: Option<AfterWildcard> = None;
// current indices moving in two strings
let mut cur_pos_plain_text = 0_usize;
let mut cur_pos_pattern_text = 0_usize;
loop {
// current chars in two strings
let plain_c = self.chars().nth(cur_pos_plain_text);
let pattern_c = pattern.chars().nth(cur_pos_pattern_text);
if plain_c.is_none() {
// plain text ends
match pattern_c {
None => return true, // pattern text ends as well, happy ending
Some('*') =>
// since we make wildcard matches non-eager
// go back to use `after_wildcard` only make it less possible to match
// matches if pattern only have '*' till the end
{
return pattern[cur_pos_pattern_text..].chars().all(|e| e == '*')
}
Some(w) => {
// go back to last wildcard and try next possible char in plain text
let Some(AfterWildcard {
ref mut plain_idx,
pattern_idx,
}) = after_wildcard
else {
// if no prev wildcard exists, then that's it, no match
return false;
};
// move `plain_idx` in `after_wildcard` to the next position of `w` in plain text
// any positions before that is impossible to match the pattern text
let Some(i) = self[*plain_idx..].chars().position(|c| c == w) else {
// if `w` doesn't even exists in plain text, then give up
return false;
};
*plain_idx = i;
cur_pos_plain_text = *plain_idx;
cur_pos_pattern_text = pattern_idx;
continue;
}
}
} else if plain_c != pattern_c {
if pattern_c == Some('*') {
// skip '*'s, one is as good as many
let Some(i) = pattern[cur_pos_pattern_text..]
.chars()
.position(|e| e != '*')
else {
// even better, pattern text ends with a '*', which matches everything
return true;
};
cur_pos_pattern_text += i;
// pattern text doesn't end with this '*', then find next non '*' char
let w = pattern.chars().nth(cur_pos_pattern_text).unwrap();
// char in pattern text does exist in plain text
let Some(i) = self[cur_pos_plain_text..].chars().position(|c| c == w) else {
// otherwise, we cannot match
return false;
};
// update both positions
after_wildcard.replace(AfterWildcard {
plain_idx: i,
pattern_idx: cur_pos_pattern_text,
});
continue;
}
let Some(AfterWildcard { pattern_idx, .. }) = after_wildcard else {
return false;
};
// go back to last wildcard
if pattern_idx != cur_pos_pattern_text {
cur_pos_pattern_text = pattern_idx;
// matches this char, move pattern idx forward
if pattern.chars().nth(cur_pos_pattern_text) == plain_c {
cur_pos_pattern_text += 1;
}
}
// try next plain text char anyway, current one gets swallowed by '*'
// or by a matching char in pattern text
cur_pos_plain_text += 1;
continue;
} else {
cur_pos_plain_text += 1;
cur_pos_pattern_text += 1;
}
}
}
}
/// This trait is to implement some extension functions for `&[u8]` and `Vec<u8>` type.
pub trait Utf8Ext {
fn to_str(&self) -> Result<&str, Utf8Error>;
fn to_str_lossy(&self) -> Cow<str>;
}
impl Utf8Ext for [u8] {
/// Converts a slice of bytes to a string slice.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// assert_eq!("💖", [240, 159, 146, 150].to_str().unwrap());
/// ```
fn to_str(&self) -> Result<&str, Utf8Error> {
str::from_utf8(self)
}
/// Converts a slice of bytes to a string, including invalid characters.
///
/// # Examples
///
/// ```
/// use ext::{assert_eqs, no_std::functions::ext::*};
///
/// assert_eqs! {
/// "💖", [240, 159, 146, 150].to_str_lossy();
/// "Hello �World", b"Hello \xF0\x90\x80World".to_str_lossy();
/// }
///
/// ```
fn to_str_lossy(&self) -> Cow<str> {
String::from_utf8_lossy(self)
}
}
/// This trait is to implement some extension functions for `u128` type.
pub trait U128Ext {
fn fmt_size_from(self, unit: char) -> String;
}
impl U128Ext for u128 {
/// Human readable storage unit.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// assert_eq!(String::from("32.0 G"), 33554432.fmt_size_from('K'));
/// ```
fn fmt_size_from(self, unit: char) -> String {
let units = ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z'];
let mut size = self as f64;
let mut counter = 0;
while size >= 1024.0 {
size /= 1024.0;
counter += 1;
}
for (i, &c) in units.iter().enumerate() {
if c == unit {
counter += i;
break;
}
}
format!(
"{:.1} {}",
size,
units
.get(counter)
.unwrap_or_else(|| panic!("memory unit out of bounds"))
)
}
}
/// This trait is to implement some extension functions for `Option<T>` type.
pub trait OptionExt<T> {
fn or_else_some(self, f: impl FnOnce() -> T) -> Self;
fn apply<R>(self, f: Option<impl FnMut(T) -> R>) -> Option<R>;
}
impl<T> OptionExt<T> for Option<T> {
/// This function is similar to `or_else`,
/// but convert closure result to `Some` automatically.
///
/// # Examples
///
/// ``` rust
/// use ext::no_std::functions::ext::*;
///
/// assert_eq!(Some(0), None::<u8>.or_else_some(|| 0));
/// ```
fn or_else_some(self, f: impl FnOnce() -> T) -> Self {
match self {
Some(_) => self,
None => f().into_some(),
}
}
/// # Examples
///
/// ```
/// use std::ops::Not;
/// use ext::{assert_eqs, no_std::functions::{fun::s, ext::*}};
///
/// assert_eqs! {
/// Some(1), Some(0).apply(Some(|x| x + 1));
/// Some(true), Some(false).apply(Some(|x: bool| x.not()));
/// Some(s("abcd")), Some(s("ab")).apply(Some(|x| x + "cd"));
/// }
/// ```
fn apply<R>(self, f: Option<impl FnMut(T) -> R>) -> Option<R> {
Maybe::apply(self, f)
}
}
/// This trait is to implement some extension functions for `Result<T, E>` type.
pub trait ResultExt<T, E> {
fn zip<U>(self, other: Result<U, E>) -> Result<(T, U), E>;
fn apply<U>(self, f: Result<impl FnMut(T) -> U, E>) -> Result<U, E>;
}
impl<T, E> ResultExt<T, E> for Result<T, E> {
/// Zips `self` with another `Result`.
///
/// If `self` is `Ok(s)` and `other` is `Ok(o)`, this method returns `Ok((s, o))`.
/// Otherwise, `Err` is returned.
///
/// # Examples
///
/// ```
/// use ext::{assert_eqs, no_std::functions::ext::*};
///
/// let x = Ok(1);
/// let y = Ok("hi");
/// let z = Err::<u8, _>(());
///
/// assert_eqs! {
/// x.zip(y), Ok((1, "hi"));
/// x.zip(z), Err(());
/// }
/// ```
fn zip<U>(self, other: Result<U, E>) -> Result<(T, U), E> {
match (self, other) {
(Ok(a), Ok(b)) => (a, b).into_ok(),
(Err(e), _) | (_, Err(e)) => e.into_err(),
}
}
/// # Examples
///
/// ```
/// use std::ops::Not;
/// use ext::{assert_eqs, no_std::functions::{fun::s, ext::*}};
///
/// let mut f = Ok(|x| x + "cd");
/// f = Err(());
///
/// assert_eqs! {
/// Ok::<_, ()>(0), Ok(0).apply(Ok(|x| x / 1));
/// Err(-1), Err(-1).apply(Ok(|x: bool| x.not()));
/// Err(()), Ok(s("ab")).apply(f);
/// }
/// ```
fn apply<U>(self, f: Result<impl FnMut(T) -> U, E>) -> Result<U, E> {
Either::apply(self, f)
}
}
pub trait VecExt<T> {
fn apply<U>(self, f: Vec<impl FnMut(T) -> U>) -> Vec<U>;
}
impl<T> VecExt<T> for Vec<T> {
/// Applies the function to the element.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// let v = vec![2, 4, 6];
/// let f = Vec::from([|x| x + 1, |y| y * 2, |z| z / 3]);
///
/// assert_eq!(v.apply(f), vec![3, 8, 2]);
/// ```
fn apply<U>(self, f: Vec<impl FnMut(T) -> U>) -> Vec<U> {
Vector::apply(self, f)
}
}
/// This trait is a workaround for impl_"Fn"trait_in_assoc_type
pub trait MyFnOnce<Arg>
where
Self: FnOnce(Arg) -> Self::Out,
{
type Out;
}
impl<Arg, Out, T: FnOnce(Arg) -> Out> MyFnOnce<Arg> for T {
type Out = Out;
}
/// This trait is to implement some extension functions with currying two parameters.
pub trait Curry<'a, P1, P2, R> {
type OutputL: MyFnOnce<P2, Out = R> + 'a;
type OutputR: MyFnOnce<P1, Out = R> + 'a;
fn curryl(self) -> impl MyFnOnce<P1, Out = Self::OutputL> + 'a;
fn curryr(self) -> impl MyFnOnce<P2, Out = Self::OutputR> + 'a;
}
impl<'a, P1: 'a, P2: 'a, R, F> Curry<'a, P1, P2, R> for F
where
F: FnOnce(P1, P2) -> R + 'a,
{
type OutputL = impl MyFnOnce<P2, Out = R> + 'a;
type OutputR = impl MyFnOnce<P1, Out = R> + 'a;
/// Two parameters, currying from left to right.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// fn sub(a: u8, b: u8) -> u8 { a - b }
/// let c1 = sub.curryl();
/// assert_eq!(c1(3)(2), 1);
/// ```
fn curryl(self) -> impl MyFnOnce<P1, Out = Self::OutputL> + 'a {
|p1| |p2| self(p1, p2)
}
/// Two parameters, currying from right to left.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::ext::*;
///
/// fn sub(a: u8, b: u8) -> u8 { a - b }
/// let cu = sub.curryr();
/// assert_eq!(cu(2)(3), 1);
/// ```
fn curryr(self) -> impl MyFnOnce<P2, Out = Self::OutputR> + 'a {
|p2| |p1| self(p1, p2)
}
}
pub mod fn_once_ext {
use crate::no_std::pipelines::pipe::Pipe;
/// This trait is to implement some extension functions whose type is `FnOnce`.
pub trait FnOnceExt<T, U, R> {
fn combine(self, g: impl FnOnce(U) -> R) -> impl FnOnce(T) -> R;
fn compose(self, g: impl FnOnce(R) -> T) -> impl FnOnce(R) -> U;
}
impl<T, U, R, F> FnOnceExt<T, U, R> for F
where
F: FnOnce(T) -> U,
{
/// Combining two functions.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::{ext::fn_once_ext::*, fun::s};
///
/// fn inc(arr: &[u8]) -> Vec<u8> { arr.iter().map(|byte| byte + 1).collect() }
/// fn sum(v: Vec<u8>) -> u8 { v.iter().sum() }
/// fn to_string(x: u8) -> String { x.to_string() }
///
/// let func = inc.combine(sum).combine(to_string);
/// assert_eq!(s("45"), func(&[0, 1, 2, 3, 4, 5, 6, 7, 8]));
/// ```
fn combine(self, g: impl FnOnce(U) -> R) -> impl FnOnce(T) -> R {
|x| x.pipe(self).pipe(g) // |x| g(self(x))
}
/// Combining two functions in reverse order.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::{ext::fn_once_ext::*, fun::s};
///
/// fn inc(arr: &[u8]) -> Vec<u8> { arr.iter().map(|byte| byte + 1).collect() }
/// fn sum(v: Vec<u8>) -> u8 { v.iter().sum() }
/// fn to_string(x: u8) -> String { x.to_string() }
///
/// let func = to_string.compose(sum).compose(inc);
/// assert_eq!(s("45"), func(&[0, 1, 2, 3, 4, 5, 6, 7, 8]));
/// ```
fn compose(self, g: impl FnOnce(R) -> T) -> impl FnOnce(R) -> U {
g.combine(self) // |x| self(g(x))
}
}
}
pub mod fn_ext {
use crate::no_std::pipelines::pipe::Pipe;
/// This trait is to implement some extension functions whose type is `Fn`.
pub trait FnExt<T, U, R> {
fn combine(self, g: impl Fn(U) -> R) -> impl Fn(T) -> R;
fn compose(self, g: impl Fn(R) -> T) -> impl Fn(R) -> U;
}
impl<T, U, R, F> FnExt<T, U, R> for F
where
F: Fn(T) -> U,
{
/// Combining two functions.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::{ext::fn_ext::*, fun::s};
///
/// fn inc(arr: &[u8]) -> Vec<u8> { arr.iter().map(|byte| byte + 1).collect() }
/// fn sum(v: Vec<u8>) -> u8 { v.iter().sum() }
/// fn to_string(x: u8) -> String { x.to_string() }
///
/// let func = inc.combine(sum);
/// let func = func.combine(to_string);
/// assert_eq!(s("45"), func(&[0, 1, 2, 3, 4, 5, 6, 7, 8]));
/// ```
fn combine(self, g: impl Fn(U) -> R) -> impl Fn(T) -> R {
move |x| x.pipe(&self).pipe(&g) // |x| g(self(x))
}
/// Combining two functions in reverse order.
///
/// # Examples
///
/// ```
/// use ext::no_std::functions::{ext::fn_ext::*, fun::s};
///
/// fn inc(arr: &[u8]) -> Vec<u8> { arr.iter().map(|byte| byte + 1).collect() }
/// fn sum(v: Vec<u8>) -> u8 { v.iter().sum() }
/// fn to_string(x: u8) -> String { x.to_string() }
///
/// let func = to_string.compose(sum);
/// let func = func.compose(inc);
/// assert_eq!(s("45"), func(&[0, 1, 2, 3, 4, 5, 6, 7, 8]));
/// ```
fn compose(self, g: impl Fn(R) -> T) -> impl Fn(R) -> U {
g.combine(self) // |x| self(g(x))
}
}
}