mocker/mockers.rs
1use crate::Mocker;
2
3/// A built-in Mocker, which alternates between uppercase and lowercase.
4pub struct AlternatingMocker {
5 current: bool
6}
7
8impl AlternatingMocker {
9 /// Creates a new AlternatingMocker. This by default starts with a lowercase letter, if you wanna control that, use `AlternatingMocker::new_from_bool()`.
10 pub fn new() -> Self {
11 Self {
12 current: false
13 }
14 }
15 /// Creates a new AlternatingMocker, and allows you to control the case of the starting letter with the parameter.
16 ///
17 /// ```
18 /// let mocked = mock(&text, &mut AlternatingMocker::new_from_bool(true));
19 /// ```
20 pub fn new_from_bool(starting_case: bool) -> Self {
21 Self {
22 current: starting_case
23 }
24 }
25}
26
27impl Mocker for AlternatingMocker {
28 /// Toggles the state of the current case and returns the old one.
29 fn uppercase(&mut self) -> bool {
30 self.current = !self.current;
31 !self.current
32 }
33}
34
35/// A built-in Mocker, which randomly makes characters uppercase or lowercase.
36pub struct RandomMocker;
37
38impl RandomMocker {
39 /// Creates a new RandomMocker.
40 pub fn new() -> Self {
41 Self {}
42 }
43}
44
45impl Mocker for RandomMocker {
46 /// Returns a random boolean (which is also the case of the letter)
47 fn uppercase(&mut self) -> bool {
48 rand::random()
49 }
50}
51
52/// A built-in Mocker, which takes in a closure that returns a boolean. Useful if you don't feel like implementing the Mocker trait yourself.
53///
54/// Example of a ClosureMocker which makes all the letters uppercase:
55///
56/// ```
57/// let text = "hello, World!";
58/// let mut mocker = ClosureMocker::new(|| {
59/// true
60/// });
61/// assert_eq!("HELLO, WORLD!", mock(&text, &mut mocker));
62/// ```
63pub struct ClosureMocker<T: Fn() -> bool> {
64 closure: T
65}
66
67impl<T: Fn() -> bool> ClosureMocker<T> {
68 /// Creates a new ClosureMocker.
69 /// The parameter must be a closure which returns a `bool`.
70 /// The closure will be executed to determine whether the letter should be uppercase or not.
71 pub fn new(closure: T) -> Self {
72 Self {
73 closure: closure
74 }
75 }
76}
77
78impl<T: Fn() -> bool> Mocker for ClosureMocker<T> {
79 /// Executes the closure and returns the value.
80 fn uppercase(&mut self) -> bool {
81 (self.closure)()
82 }
83}