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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::{
    description::Description,
    matcher::{Matcher, MatcherBase, MatcherResult},
    matcher_support::{
        edit_distance,
        summarize_diff::{create_diff, create_diff_reversed},
    },
    matchers::eq_matcher::EqMatcher,
};
use std::borrow::Cow;
use std::fmt::Debug;
use std::ops::Deref;

/// Matches a string containing a given substring.
///
/// Both the actual value and the expected substring may be either a `String` or
/// a string reference.
///
/// ```
/// # use googletest::prelude::*;
/// # fn should_pass_1() -> Result<()> {
/// verify_that!("Some value", contains_substring("Some"))?;  // Passes
/// #     Ok(())
/// # }
/// # fn should_fail() -> Result<()> {
/// verify_that!("Another value", contains_substring("Some"))?;   // Fails
/// #     Ok(())
/// # }
/// # fn should_pass_2() -> Result<()> {
/// verify_that!("Some value".to_string(), contains_substring("value"))?;   // Passes
/// verify_that!("Some value", contains_substring("value".to_string()))?;   // Passes
/// #     Ok(())
/// # }
/// # should_pass_1().unwrap();
/// # should_fail().unwrap_err();
/// # should_pass_2().unwrap();
/// ```
///
/// See the [`StrMatcherConfigurator`] extension trait for more options on how
/// the string is matched.
///
/// > Note on memory use: In most cases, this matcher does not allocate memory
/// > when matching strings. However, it must allocate copies of both the actual
/// > and expected values when matching strings while
/// > [`ignoring_ascii_case`][StrMatcherConfigurator::ignoring_ascii_case] is
/// > set.
pub fn contains_substring<T>(expected: T) -> StrMatcher<T> {
    StrMatcher {
        configuration: Configuration { mode: MatchMode::Contains, ..Default::default() },
        expected,
    }
}

/// Matches a string which starts with the given prefix.
///
/// Both the actual value and the expected prefix may be either a `String` or
/// a string reference.
///
/// ```
/// # use googletest::prelude::*;
/// # fn should_pass_1() -> Result<()> {
/// verify_that!("Some value", starts_with("Some"))?;  // Passes
/// #     Ok(())
/// # }
/// # fn should_fail_1() -> Result<()> {
/// verify_that!("Another value", starts_with("Some"))?;   // Fails
/// #     Ok(())
/// # }
/// # fn should_fail_2() -> Result<()> {
/// verify_that!("Some value", starts_with("value"))?;  // Fails
/// #     Ok(())
/// # }
/// # fn should_pass_2() -> Result<()> {
/// verify_that!("Some value".to_string(), starts_with("Some"))?;   // Passes
/// verify_that!("Some value", starts_with("Some".to_string()))?;   // Passes
/// #     Ok(())
/// # }
/// # should_pass_1().unwrap();
/// # should_fail_1().unwrap_err();
/// # should_fail_2().unwrap_err();
/// # should_pass_2().unwrap();
/// ```
///
/// See the [`StrMatcherConfigurator`] extension trait for more options on how
/// the string is matched.
pub fn starts_with<T>(expected: T) -> StrMatcher<T> {
    StrMatcher {
        configuration: Configuration { mode: MatchMode::StartsWith, ..Default::default() },
        expected,
    }
}

/// Matches a string which ends with the given suffix.
///
/// Both the actual value and the expected suffix may be either a `String` or
/// a string reference.
///
/// ```
/// # use googletest::prelude::*;
/// # fn should_pass_1() -> Result<()> {
/// verify_that!("Some value", ends_with("value"))?;  // Passes
/// #     Ok(())
/// # }
/// # fn should_fail_1() -> Result<()> {
/// verify_that!("Some value", ends_with("other value"))?;   // Fails
/// #     Ok(())
/// # }
/// # fn should_fail_2() -> Result<()> {
/// verify_that!("Some value", ends_with("Some"))?;  // Fails
/// #     Ok(())
/// # }
/// # fn should_pass_2() -> Result<()> {
/// verify_that!("Some value".to_string(), ends_with("value"))?;   // Passes
/// verify_that!("Some value", ends_with("value".to_string()))?;   // Passes
/// #     Ok(())
/// # }
/// # should_pass_1().unwrap();
/// # should_fail_1().unwrap_err();
/// # should_fail_2().unwrap_err();
/// # should_pass_2().unwrap();
/// ```
///
/// See the [`StrMatcherConfigurator`] extension trait for more options on how
/// the string is matched.
pub fn ends_with<T>(expected: T) -> StrMatcher<T> {
    StrMatcher {
        configuration: Configuration { mode: MatchMode::EndsWith, ..Default::default() },
        expected,
    }
}

/// Extension trait to configure [`StrMatcher`].
///
/// Matchers which match against string values and, through configuration,
/// specialise to [`StrMatcher`] implement this trait. That includes
/// [`EqMatcher`] and [`StrMatcher`].
pub trait StrMatcherConfigurator<ExpectedT> {
    /// Configures the matcher to ignore any leading whitespace in either the
    /// actual or the expected value.
    ///
    /// Whitespace is defined as in [`str::trim_start`].
    ///
    /// ```
    /// # use googletest::prelude::*;
    /// # fn should_pass() -> Result<()> {
    /// verify_that!("A string", eq("   A string").ignoring_leading_whitespace())?; // Passes
    /// verify_that!("   A string", eq("A string").ignoring_leading_whitespace())?; // Passes
    /// #     Ok(())
    /// # }
    /// # should_pass().unwrap();
    /// ```
    ///
    /// When all other configuration options are left as the defaults, this is
    /// equivalent to invoking [`str::trim_start`] on both the expected and
    /// actual value.
    fn ignoring_leading_whitespace(self) -> StrMatcher<ExpectedT>;

    /// Configures the matcher to ignore any trailing whitespace in either the
    /// actual or the expected value.
    ///
    /// Whitespace is defined as in [`str::trim_end`].
    ///
    /// ```
    /// # use googletest::prelude::*;
    /// # fn should_pass() -> Result<()> {
    /// verify_that!("A string", eq("A string   ").ignoring_trailing_whitespace())?; // Passes
    /// verify_that!("A string   ", eq("A string").ignoring_trailing_whitespace())?; // Passes
    /// #     Ok(())
    /// # }
    /// # should_pass().unwrap();
    /// ```
    ///
    /// When all other configuration options are left as the defaults, this is
    /// equivalent to invoking [`str::trim_end`] on both the expected and
    /// actual value.
    fn ignoring_trailing_whitespace(self) -> StrMatcher<ExpectedT>;

    /// Configures the matcher to ignore both leading and trailing whitespace in
    /// either the actual or the expected value.
    ///
    /// Whitespace is defined as in [`str::trim`].
    ///
    /// ```
    /// # use googletest::prelude::*;
    /// # fn should_pass() -> Result<()> {
    /// verify_that!("A string", eq("   A string   ").ignoring_outer_whitespace())?; // Passes
    /// verify_that!("   A string   ", eq("A string").ignoring_outer_whitespace())?; // Passes
    /// #     Ok(())
    /// # }
    /// # should_pass().unwrap();
    /// ```
    ///
    /// This is equivalent to invoking both
    /// [`ignoring_leading_whitespace`][StrMatcherConfigurator::ignoring_leading_whitespace] and
    /// [`ignoring_trailing_whitespace`][StrMatcherConfigurator::ignoring_trailing_whitespace].
    ///
    /// When all other configuration options are left as the defaults, this is
    /// equivalent to invoking [`str::trim`] on both the expected and actual
    /// value.
    fn ignoring_outer_whitespace(self) -> StrMatcher<ExpectedT>;

    /// Configures the matcher to ignore ASCII case when comparing values.
    ///
    /// This uses the same rules for case as [`str::eq_ignore_ascii_case`].
    ///
    /// ```
    /// # use googletest::prelude::*;
    /// # fn should_pass() -> Result<()> {
    /// verify_that!("Some value", eq("SOME VALUE").ignoring_ascii_case())?;  // Passes
    /// #     Ok(())
    /// # }
    /// # fn should_fail() -> Result<()> {
    /// verify_that!("Another value", eq("Some value").ignoring_ascii_case())?;   // Fails
    /// #     Ok(())
    /// # }
    /// # should_pass().unwrap();
    /// # should_fail().unwrap_err();
    /// ```
    ///
    /// This is **not guaranteed** to match strings with differing upper/lower
    /// case characters outside of the codepoints 0-127 covered by ASCII.
    fn ignoring_ascii_case(self) -> StrMatcher<ExpectedT>;

    /// Configures the matcher to match only strings which otherwise satisfy the
    /// conditions a number times matched by the matcher `times`.
    ///
    /// ```
    /// # use googletest::prelude::*;
    /// # fn should_pass() -> Result<()> {
    /// verify_that!("Some value\nSome value", contains_substring("value").times(eq(2)))?; // Passes
    /// #     Ok(())
    /// # }
    /// # fn should_fail() -> Result<()> {
    /// verify_that!("Some value", contains_substring("value").times(eq(2)))?; // Fails
    /// #     Ok(())
    /// # }
    /// # should_pass().unwrap();
    /// # should_fail().unwrap_err();
    /// ```
    ///
    /// The matched substrings must be disjoint from one another to be counted.
    /// For example:
    ///
    /// ```
    /// # use googletest::prelude::*;
    /// # fn should_fail() -> Result<()> {
    /// // Fails: substrings distinct but not disjoint!
    /// verify_that!("ababab", contains_substring("abab").times(eq(2)))?;
    /// #     Ok(())
    /// # }
    /// # should_fail().unwrap_err();
    /// ```
    ///
    /// This is only meaningful when the matcher was constructed with
    /// [`contains_substring`]. This method will panic when it is used with any
    /// other matcher construction.
    fn times(self, times: impl Matcher<usize> + 'static) -> StrMatcher<ExpectedT>;
}

/// A matcher which matches equality or containment of a string-like value in a
/// configurable way.
///
/// The following matcher methods instantiate this:
///
///  * [`eq`][crate::matchers::eq_matcher::eq],
///  * [`contains_substring`],
///  * [`starts_with`],
///  * [`ends_with`].
#[derive(MatcherBase)]
pub struct StrMatcher<ExpectedT> {
    expected: ExpectedT,
    configuration: Configuration,
}

impl<ExpectedT, ActualT> Matcher<ActualT> for StrMatcher<ExpectedT>
where
    ExpectedT: Deref<Target = str> + Debug,
    ActualT: AsRef<str> + Debug + Copy,
{
    fn matches(&self, actual: ActualT) -> MatcherResult {
        self.configuration.do_strings_match(self.expected.deref(), actual.as_ref()).into()
    }

    fn describe(&self, matcher_result: MatcherResult) -> Description {
        self.configuration.describe(matcher_result, self.expected.deref())
    }

    fn explain_match(&self, actual: ActualT) -> Description {
        self.configuration.explain_match(self.expected.deref(), actual.as_ref())
    }
}

impl<ExpectedT, MatcherT: Into<StrMatcher<ExpectedT>>> StrMatcherConfigurator<ExpectedT>
    for MatcherT
{
    fn ignoring_leading_whitespace(self) -> StrMatcher<ExpectedT> {
        let existing = self.into();
        StrMatcher {
            configuration: existing.configuration.ignoring_leading_whitespace(),
            ..existing
        }
    }

    fn ignoring_trailing_whitespace(self) -> StrMatcher<ExpectedT> {
        let existing = self.into();
        StrMatcher {
            configuration: existing.configuration.ignoring_trailing_whitespace(),
            ..existing
        }
    }

    fn ignoring_outer_whitespace(self) -> StrMatcher<ExpectedT> {
        let existing = self.into();
        StrMatcher { configuration: existing.configuration.ignoring_outer_whitespace(), ..existing }
    }

    fn ignoring_ascii_case(self) -> StrMatcher<ExpectedT> {
        let existing = self.into();
        StrMatcher { configuration: existing.configuration.ignoring_ascii_case(), ..existing }
    }

    fn times(self, times: impl Matcher<usize> + 'static) -> StrMatcher<ExpectedT> {
        let existing = self.into();
        if !matches!(existing.configuration.mode, MatchMode::Contains) {
            panic!("The times() configurator is only meaningful with contains_substring().");
        }
        StrMatcher { configuration: existing.configuration.times(times), ..existing }
    }
}

impl<T: Deref<Target = str>> From<EqMatcher<T>> for StrMatcher<T> {
    fn from(value: EqMatcher<T>) -> Self {
        Self::with_default_config(value.expected)
    }
}

impl<T> StrMatcher<T> {
    /// Returns a [`StrMatcher`] with a default configuration to match against
    /// the given expected value.
    ///
    /// This default configuration is sensitive to whitespace and case.
    fn with_default_config(expected: T) -> Self {
        Self { expected, configuration: Default::default() }
    }
}

// Holds all the information on how the expected and actual strings are to be
// compared. Its associated functions perform the actual matching operations
// on string references. The struct and comparison methods therefore need not be
// parameterised, saving compilation time and binary size on monomorphisation.
//
// The default value represents exact equality of the strings.
struct Configuration {
    mode: MatchMode,
    ignore_leading_whitespace: bool,
    ignore_trailing_whitespace: bool,
    case_policy: CasePolicy,
    times: Option<Box<dyn Matcher<usize>>>,
}

#[derive(Clone)]
enum MatchMode {
    Equals,
    Contains,
    StartsWith,
    EndsWith,
}

impl MatchMode {
    fn to_diff_mode(&self) -> edit_distance::Mode {
        match self {
            MatchMode::StartsWith | MatchMode::EndsWith => edit_distance::Mode::Prefix,
            MatchMode::Contains => edit_distance::Mode::Contains,
            MatchMode::Equals => edit_distance::Mode::Exact,
        }
    }
}

#[derive(Clone)]
enum CasePolicy {
    Respect,
    IgnoreAscii,
}

impl Configuration {
    // The entry point for all string matching. StrMatcher::matches redirects
    // immediately to this function.
    fn do_strings_match(&self, expected: &str, actual: &str) -> bool {
        let (expected, actual) =
            match (self.ignore_leading_whitespace, self.ignore_trailing_whitespace) {
                (true, true) => (expected.trim(), actual.trim()),
                (true, false) => (expected.trim_start(), actual.trim_start()),
                (false, true) => (expected.trim_end(), actual.trim_end()),
                (false, false) => (expected, actual),
            };
        match self.mode {
            MatchMode::Equals => match self.case_policy {
                CasePolicy::Respect => expected == actual,
                CasePolicy::IgnoreAscii => expected.eq_ignore_ascii_case(actual),
            },
            MatchMode::Contains => match self.case_policy {
                CasePolicy::Respect => self.does_containment_match(actual, expected),
                CasePolicy::IgnoreAscii => self.does_containment_match(
                    actual.to_ascii_lowercase().as_str(),
                    expected.to_ascii_lowercase().as_str(),
                ),
            },
            MatchMode::StartsWith => match self.case_policy {
                CasePolicy::Respect => actual.starts_with(expected),
                CasePolicy::IgnoreAscii => {
                    actual.len() >= expected.len()
                        && actual[..expected.len()].eq_ignore_ascii_case(expected)
                }
            },
            MatchMode::EndsWith => match self.case_policy {
                CasePolicy::Respect => actual.ends_with(expected),
                CasePolicy::IgnoreAscii => {
                    actual.len() >= expected.len()
                        && actual[actual.len() - expected.len()..].eq_ignore_ascii_case(expected)
                }
            },
        }
    }

    // Returns whether actual contains expected a number of times matched by the
    // matcher self.times. Does not take other configuration into account.
    fn does_containment_match(&self, actual: &str, expected: &str) -> bool {
        if let Some(times) = self.times.as_ref() {
            // Split returns an iterator over the "boundaries" left and right of the
            // substring to be matched, of which there is one more than the number of
            // substrings.
            matches!(times.matches(actual.split(expected).count() - 1), MatcherResult::Match)
        } else {
            actual.contains(expected)
        }
    }

    // StrMatcher::<str>::describe redirects immediately to this function.
    fn describe(&self, matcher_result: MatcherResult, expected: &str) -> Description {
        let mut addenda: Vec<Cow<'static, str>> = Vec::with_capacity(3);
        match (self.ignore_leading_whitespace, self.ignore_trailing_whitespace) {
            (true, true) => addenda.push("ignoring leading and trailing whitespace".into()),
            (true, false) => addenda.push("ignoring leading whitespace".into()),
            (false, true) => addenda.push("ignoring trailing whitespace".into()),
            (false, false) => {}
        }
        match self.case_policy {
            CasePolicy::Respect => {}
            CasePolicy::IgnoreAscii => addenda.push("ignoring ASCII case".into()),
        }
        if let Some(times) = self.times.as_ref() {
            addenda.push(format!("count {}", times.describe(matcher_result)).into());
        }
        let extra =
            if !addenda.is_empty() { format!(" ({})", addenda.join(", ")) } else { "".into() };
        let match_mode_description = match self.mode {
            MatchMode::Equals => match matcher_result {
                MatcherResult::Match => "is equal to",
                MatcherResult::NoMatch => "isn't equal to",
            },
            MatchMode::Contains => match matcher_result {
                MatcherResult::Match => "contains a substring",
                MatcherResult::NoMatch => "does not contain a substring",
            },
            MatchMode::StartsWith => match matcher_result {
                MatcherResult::Match => "starts with prefix",
                MatcherResult::NoMatch => "does not start with",
            },
            MatchMode::EndsWith => match matcher_result {
                MatcherResult::Match => "ends with suffix",
                MatcherResult::NoMatch => "does not end with",
            },
        };
        format!("{match_mode_description} {expected:?}{extra}").into()
    }

    fn explain_match(&self, expected: &str, actual: &str) -> Description {
        let default_explanation = format!(
            "which {}",
            self.describe(self.do_strings_match(expected, actual).into(), expected)
        )
        .into();
        if !expected.contains('\n') || !actual.contains('\n') {
            return default_explanation;
        }

        if self.ignore_leading_whitespace {
            // TODO - b/283448414 : Support StrMatcher with ignore_leading_whitespace.
            return default_explanation;
        }

        if self.ignore_trailing_whitespace {
            // TODO - b/283448414 : Support StrMatcher with ignore_trailing_whitespace.
            return default_explanation;
        }

        if self.times.is_some() {
            // TODO - b/283448414 : Support StrMatcher with times.
            return default_explanation;
        }
        if matches!(self.case_policy, CasePolicy::IgnoreAscii) {
            // TODO - b/283448414 : Support StrMatcher with ignore ascii case policy.
            return default_explanation;
        }
        if self.do_strings_match(expected, actual) {
            // TODO - b/283448414 : Consider supporting debug difference if the
            // strings match. This can be useful when a small contains is found
            // in a long string.
            return default_explanation;
        }

        let diff = match self.mode {
            MatchMode::Equals | MatchMode::StartsWith | MatchMode::Contains => {
                // TODO(b/287632452): Also consider improving the output in MatchMode::Contains
                // when the substring begins or ends in the middle of a line of the actual
                // value.
                create_diff(actual, expected, self.mode.to_diff_mode())
            }
            MatchMode::EndsWith => create_diff_reversed(actual, expected, self.mode.to_diff_mode()),
        };

        format!("{default_explanation}\n{diff}").into()
    }

    fn ignoring_leading_whitespace(self) -> Self {
        Self { ignore_leading_whitespace: true, ..self }
    }

    fn ignoring_trailing_whitespace(self) -> Self {
        Self { ignore_trailing_whitespace: true, ..self }
    }

    fn ignoring_outer_whitespace(self) -> Self {
        Self { ignore_leading_whitespace: true, ignore_trailing_whitespace: true, ..self }
    }

    fn ignoring_ascii_case(self) -> Self {
        Self { case_policy: CasePolicy::IgnoreAscii, ..self }
    }

    fn times(self, times: impl Matcher<usize> + 'static) -> Self {
        Self { times: Some(Box::new(times)), ..self }
    }
}

impl Default for Configuration {
    fn default() -> Self {
        Self {
            mode: MatchMode::Equals,
            ignore_leading_whitespace: false,
            ignore_trailing_whitespace: false,
            case_policy: CasePolicy::Respect,
            times: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::matcher::MatcherResult;
    use crate::prelude::*;
    use indoc::indoc;

    #[test]
    fn matches_string_reference_with_equal_string_reference() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string");
        verify_that!("A string", matcher)
    }

    #[test]
    fn does_not_match_string_reference_with_non_equal_string_reference() -> Result<()> {
        let matcher = StrMatcher::with_default_config("Another string");
        verify_that!("A string", not(matcher))
    }

    #[test]
    fn matches_owned_string_with_string_reference() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string");
        let value = "A string".to_string();
        verify_that!(value, matcher)
    }

    #[test]
    fn matches_owned_string_reference_with_string_reference() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string");
        let value = "A string".to_string();
        verify_that!(&value, matcher)
    }

    #[test]
    fn ignores_leading_whitespace_in_expected_when_requested() -> Result<()> {
        let matcher = StrMatcher::with_default_config(" \n\tA string");
        verify_that!("A string", matcher.ignoring_leading_whitespace())
    }

    #[test]
    fn ignores_leading_whitespace_in_actual_when_requested() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string");
        verify_that!(" \n\tA string", matcher.ignoring_leading_whitespace())
    }

    #[test]
    fn does_not_match_unequal_remaining_string_when_ignoring_leading_whitespace() -> Result<()> {
        let matcher = StrMatcher::with_default_config(" \n\tAnother string");
        verify_that!("A string", not(matcher.ignoring_leading_whitespace()))
    }

    #[test]
    fn remains_sensitive_to_trailing_whitespace_when_ignoring_leading_whitespace() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string \n\t");
        verify_that!("A string", not(matcher.ignoring_leading_whitespace()))
    }

    #[test]
    fn ignores_trailing_whitespace_in_expected_when_requested() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string \n\t");
        verify_that!("A string", matcher.ignoring_trailing_whitespace())
    }

    #[test]
    fn ignores_trailing_whitespace_in_actual_when_requested() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string");
        verify_that!("A string \n\t", matcher.ignoring_trailing_whitespace())
    }

    #[test]
    fn does_not_match_unequal_remaining_string_when_ignoring_trailing_whitespace() -> Result<()> {
        let matcher = StrMatcher::with_default_config("Another string \n\t");
        verify_that!("A string", not(matcher.ignoring_trailing_whitespace()))
    }

    #[test]
    fn remains_sensitive_to_leading_whitespace_when_ignoring_trailing_whitespace() -> Result<()> {
        let matcher = StrMatcher::with_default_config(" \n\tA string");
        verify_that!("A string", not(matcher.ignoring_trailing_whitespace()))
    }

    #[test]
    fn ignores_leading_and_trailing_whitespace_in_expected_when_requested() -> Result<()> {
        let matcher = StrMatcher::with_default_config(" \n\tA string \n\t");
        verify_that!("A string", matcher.ignoring_outer_whitespace())
    }

    #[test]
    fn ignores_leading_and_trailing_whitespace_in_actual_when_requested() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string");
        verify_that!(" \n\tA string \n\t", matcher.ignoring_outer_whitespace())
    }

    #[test]
    fn respects_ascii_case_by_default() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string");
        verify_that!("A STRING", not(matcher))
    }

    #[test]
    fn ignores_ascii_case_when_requested() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string");
        verify_that!("A STRING", matcher.ignoring_ascii_case())
    }

    #[test]
    fn allows_ignoring_leading_whitespace_from_eq() -> Result<()> {
        verify_that!("A string", eq(" \n\tA string").ignoring_leading_whitespace())
    }

    #[test]
    fn allows_ignoring_trailing_whitespace_from_eq() -> Result<()> {
        verify_that!("A string", eq("A string \n\t").ignoring_trailing_whitespace())
    }

    #[test]
    fn allows_ignoring_outer_whitespace_from_eq() -> Result<()> {
        verify_that!("A string", eq(" \n\tA string \n\t").ignoring_outer_whitespace())
    }

    #[test]
    fn allows_ignoring_ascii_case_from_eq() -> Result<()> {
        verify_that!("A string", eq("A STRING").ignoring_ascii_case())
    }

    #[test]
    fn matches_string_containing_expected_value_in_contains_mode() -> Result<()> {
        verify_that!("Some string", contains_substring("str"))
    }

    #[test]
    fn matches_string_containing_expected_value_in_contains_mode_while_ignoring_ascii_case()
    -> Result<()> {
        verify_that!("Some string", contains_substring("STR").ignoring_ascii_case())
    }

    #[test]
    fn contains_substring_matches_correct_number_of_substrings() -> Result<()> {
        verify_that!("Some string", contains_substring("str").times(eq(1)))
    }

    #[test]
    fn contains_substring_does_not_match_incorrect_number_of_substrings() -> Result<()> {
        verify_that!("Some string\nSome string", not(contains_substring("string").times(eq(1))))
    }

    #[test]
    fn contains_substring_does_not_match_when_substrings_overlap() -> Result<()> {
        verify_that!("ababab", not(contains_substring("abab").times(eq(2))))
    }

    #[test]
    fn starts_with_matches_string_reference_with_prefix() -> Result<()> {
        verify_that!("Some value", starts_with("Some"))
    }

    #[test]
    fn starts_with_matches_string_reference_with_prefix_ignoring_ascii_case() -> Result<()> {
        verify_that!("Some value", starts_with("SOME").ignoring_ascii_case())
    }

    #[test]
    fn starts_with_does_not_match_wrong_prefix_ignoring_ascii_case() -> Result<()> {
        verify_that!("Some value", not(starts_with("OTHER").ignoring_ascii_case()))
    }

    #[test]
    fn ends_with_does_not_match_short_string_ignoring_ascii_case() -> Result<()> {
        verify_that!("Some", not(starts_with("OTHER").ignoring_ascii_case()))
    }

    #[test]
    fn starts_with_does_not_match_string_without_prefix() -> Result<()> {
        verify_that!("Some value", not(starts_with("Another")))
    }

    #[test]
    fn starts_with_does_not_match_string_with_substring_not_at_beginning() -> Result<()> {
        verify_that!("Some value", not(starts_with("value")))
    }

    #[test]
    fn ends_with_matches_string_reference_with_suffix() -> Result<()> {
        verify_that!("Some value", ends_with("value"))
    }

    #[test]
    fn ends_with_matches_string_reference_with_suffix_ignoring_ascii_case() -> Result<()> {
        verify_that!("Some value", ends_with("VALUE").ignoring_ascii_case())
    }

    #[test]
    fn ends_with_does_not_match_wrong_suffix_ignoring_ascii_case() -> Result<()> {
        verify_that!("Some value", not(ends_with("OTHER").ignoring_ascii_case()))
    }

    #[test]
    fn ends_with_does_not_match_too_short_string_ignoring_ascii_case() -> Result<()> {
        verify_that!("Some", not(ends_with("OTHER").ignoring_ascii_case()))
    }

    #[test]
    fn ends_with_does_not_match_string_without_suffix() -> Result<()> {
        verify_that!("Some value", not(ends_with("other value")))
    }

    #[test]
    fn ends_with_does_not_match_string_with_substring_not_at_end() -> Result<()> {
        verify_that!("Some value", not(ends_with("Some")))
    }

    #[test]
    fn describes_itself_for_matching_result() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string");
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::Match),
            displays_as(eq("is equal to \"A string\""))
        )
    }

    #[test]
    fn describes_itself_for_non_matching_result() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string");
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::NoMatch),
            displays_as(eq("isn't equal to \"A string\""))
        )
    }

    #[test]
    fn describes_itself_for_matching_result_ignoring_leading_whitespace() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string").ignoring_leading_whitespace();
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::Match),
            displays_as(eq("is equal to \"A string\" (ignoring leading whitespace)"))
        )
    }

    #[test]
    fn describes_itself_for_non_matching_result_ignoring_leading_whitespace() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string").ignoring_leading_whitespace();
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::NoMatch),
            displays_as(eq("isn't equal to \"A string\" (ignoring leading whitespace)"))
        )
    }

    #[test]
    fn describes_itself_for_matching_result_ignoring_trailing_whitespace() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string").ignoring_trailing_whitespace();
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::Match),
            displays_as(eq("is equal to \"A string\" (ignoring trailing whitespace)"))
        )
    }

    #[test]
    fn describes_itself_for_matching_result_ignoring_leading_and_trailing_whitespace() -> Result<()>
    {
        let matcher = StrMatcher::with_default_config("A string").ignoring_outer_whitespace();
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::Match),
            displays_as(eq("is equal to \"A string\" (ignoring leading and trailing whitespace)"))
        )
    }

    #[test]
    fn describes_itself_for_matching_result_ignoring_ascii_case() -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string").ignoring_ascii_case();
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::Match),
            displays_as(eq("is equal to \"A string\" (ignoring ASCII case)"))
        )
    }

    #[test]
    fn describes_itself_for_matching_result_ignoring_ascii_case_and_leading_whitespace()
    -> Result<()> {
        let matcher = StrMatcher::with_default_config("A string")
            .ignoring_leading_whitespace()
            .ignoring_ascii_case();
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::Match),
            displays_as(eq(
                "is equal to \"A string\" (ignoring leading whitespace, ignoring ASCII case)"
            ))
        )
    }

    #[test]
    fn describes_itself_for_matching_result_in_contains_mode() -> Result<()> {
        let matcher = contains_substring("A string");
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::Match),
            displays_as(eq("contains a substring \"A string\""))
        )
    }

    #[test]
    fn describes_itself_for_non_matching_result_in_contains_mode() -> Result<()> {
        let matcher = contains_substring("A string");
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::NoMatch),
            displays_as(eq("does not contain a substring \"A string\""))
        )
    }

    #[test]
    fn describes_itself_with_count_number() -> Result<()> {
        let matcher = contains_substring("A string").times(gt(2));
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::Match),
            displays_as(eq("contains a substring \"A string\" (count is greater than 2)"))
        )
    }

    #[test]
    fn describes_itself_for_matching_result_in_starts_with_mode() -> Result<()> {
        let matcher = starts_with("A string");
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::Match),
            displays_as(eq("starts with prefix \"A string\""))
        )
    }

    #[test]
    fn describes_itself_for_non_matching_result_in_starts_with_mode() -> Result<()> {
        let matcher = starts_with("A string");
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::NoMatch),
            displays_as(eq("does not start with \"A string\""))
        )
    }

    #[test]
    fn describes_itself_for_matching_result_in_ends_with_mode() -> Result<()> {
        let matcher = ends_with("A string");
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::Match),
            displays_as(eq("ends with suffix \"A string\""))
        )
    }

    #[test]
    fn describes_itself_for_non_matching_result_in_ends_with_mode() -> Result<()> {
        let matcher = ends_with("A string");
        verify_that!(
            Matcher::<&str>::describe(&matcher, MatcherResult::NoMatch),
            displays_as(eq("does not end with \"A string\""))
        )
    }

    #[test]
    fn match_explanation_contains_diff_of_strings_if_more_than_one_line() -> Result<()> {
        let result = verify_that!(
            indoc!(
                "
                    First line
                    Second line
                    Third line
                "
            ),
            starts_with(indoc!(
                "
                    First line
                    Second lines
                    Third line
                "
            ))
        );

        verify_that!(
            result,
            err(displays_as(contains_substring(
                "\
   First line
  -Second line
  +Second lines
   Third line"
            )))
        )
    }

    #[test]
    fn match_explanation_for_starts_with_ignores_trailing_lines_in_actual_string() -> Result<()> {
        let result = verify_that!(
            indoc!(
                "
                    First line
                    Second line
                    Third line
                    Fourth line
                "
            ),
            starts_with(indoc!(
                "
                    First line
                    Second lines
                    Third line
                "
            ))
        );

        verify_that!(
            result,
            err(displays_as(contains_substring(
                "
   First line
  -Second line
  +Second lines
   Third line
   <---- remaining lines omitted ---->"
            )))
        )
    }

    #[test]
    fn match_explanation_for_starts_with_includes_both_versions_of_differing_last_line()
    -> Result<()> {
        let result = verify_that!(
            indoc!(
                "
                    First line
                    Second line
                    Third line
                "
            ),
            starts_with(indoc!(
                "
                    First line
                    Second lines
                "
            ))
        );

        verify_that!(
            result,
            err(displays_as(contains_substring(
                "\
   First line
  -Second line
  +Second lines
   <---- remaining lines omitted ---->"
            )))
        )
    }

    #[test]
    fn match_explanation_for_ends_with_ignores_leading_lines_in_actual_string() -> Result<()> {
        let result = verify_that!(
            indoc!(
                "
                    First line
                    Second line
                    Third line
                    Fourth line
                "
            ),
            ends_with(indoc!(
                "
                    Second line
                    Third lines
                    Fourth line
                "
            ))
        );

        verify_that!(
            result,
            err(displays_as(contains_substring(
                "
  Difference(-actual / +expected):
   <---- remaining lines omitted ---->
   Second line
  -Third line
  +Third lines
   Fourth line"
            )))
        )
    }

    #[test]
    fn match_explanation_for_contains_substring_ignores_outer_lines_in_actual_string() -> Result<()>
    {
        let result = verify_that!(
            indoc!(
                "
                    First line
                    Second line
                    Third line
                    Fourth line
                    Fifth line
                "
            ),
            contains_substring(indoc!(
                "
                    Second line
                    Third lines
                    Fourth line
                "
            ))
        );

        verify_that!(
            result,
            err(displays_as(contains_substring(
                "
  Difference(-actual / +expected):
   <---- remaining lines omitted ---->
   Second line
  -Third line
  +Third lines
   Fourth line
   <---- remaining lines omitted ---->"
            )))
        )
    }

    #[test]
    fn match_explanation_for_contains_substring_shows_diff_when_first_and_last_line_are_incomplete()
    -> Result<()> {
        let result = verify_that!(
            indoc!(
                "
                    First line
                    Second line
                    Third line
                    Fourth line
                    Fifth line
                "
            ),
            contains_substring(indoc!(
                "
                    line
                    Third line
                    Foorth line
                    Fifth"
            ))
        );

        verify_that!(
            result,
            err(displays_as(contains_substring(
                "
  Difference(-actual / +expected):
   <---- remaining lines omitted ---->
  -Second line
  +line
   Third line
  -Fourth line
  +Foorth line
  -Fifth line
  +Fifth
   <---- remaining lines omitted ---->"
            )))
        )
    }

    #[test]
    fn match_explanation_for_eq_does_not_ignore_trailing_lines_in_actual_string() -> Result<()> {
        let result = verify_that!(
            indoc!(
                "
                    First line
                    Second line
                    Third line
                    Fourth line
                "
            ),
            eq(indoc!(
                "
                    First line
                    Second lines
                    Third line
                "
            ))
        );

        verify_that!(
            result,
            err(displays_as(contains_substring(
                "\
   First line
  -Second line
  +Second lines
   Third line
  -Fourth line"
            )))
        )
    }

    #[test]
    fn match_explanation_does_not_show_diff_if_actual_value_is_single_line() -> Result<()> {
        let result = verify_that!(
            "First line",
            starts_with(indoc!(
                "
                    Second line
                    Third line
                "
            ))
        );

        verify_that!(
            result,
            err(displays_as(not(contains_substring("Difference(-actual / +expected):"))))
        )
    }

    #[test]
    fn match_explanation_does_not_show_diff_if_expected_value_is_single_line() -> Result<()> {
        let result = verify_that!(
            indoc!(
                "
                    First line
                    Second line
                    Third line
                "
            ),
            starts_with("Second line")
        );

        verify_that!(
            result,
            err(displays_as(not(contains_substring("Difference(-actual / +expected):"))))
        )
    }
}