Skip to content

Commit 2cc2672

Browse files
authored
Rollup merge of #72932 - poliorcetics:pattern-contains-behaviour, r=hanna-kruppe
Clarify the behaviour of Pattern when used with methods like str::contains Fixes #45507. I used the previous work by @Emerentius (thanks !), added a paragraph and checked the links (they work for me but I'm not against someone else checking them too).
2 parents 1fb612b + 4548eb8 commit 2cc2672

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/libcore/str/pattern.rs

+37
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,43 @@ use crate::slice::memchr;
6060
/// The trait itself acts as a builder for an associated
6161
/// `Searcher` type, which does the actual work of finding
6262
/// occurrences of the pattern in a string.
63+
///
64+
/// Depending on the type of the pattern, the behaviour of methods like
65+
/// [`str::find`] and [`str::contains`] can change. The table below describes
66+
/// some of those behaviours.
67+
///
68+
/// | Pattern type | Match condition |
69+
/// |--------------------------|-------------------------------------------|
70+
/// | `&str` | is substring |
71+
/// | `char` | is contained in string |
72+
/// | `&[char] | any char in slice is contained in string |
73+
/// | `F: FnMut(char) -> bool` | `F` returns `true` for a char in string |
74+
/// | `&&str` | is substring |
75+
/// | `&String` | is substring |
76+
///
77+
/// # Examples
78+
/// ```
79+
/// // &str
80+
/// assert_eq!("abaaa".find("ba"), Some(1));
81+
/// assert_eq!("abaaa".find("bac"), None);
82+
///
83+
/// // char
84+
/// assert_eq!("abaaa".find('a'), Some(0));
85+
/// assert_eq!("abaaa".find('b'), Some(1));
86+
/// assert_eq!("abaaa".find('c'), None);
87+
///
88+
/// // &[char]
89+
/// assert_eq!("ab".find(&['b', 'a'][..]), Some(0));
90+
/// assert_eq!("abaaa".find(&['a', 'z'][..]), Some(0));
91+
/// assert_eq!("abaaa".find(&['c', 'd'][..]), None);
92+
///
93+
/// // FnMut(char) -> bool
94+
/// assert_eq!("abcdef_z".find(|ch| ch > 'd' && ch < 'y'), Some(4));
95+
/// assert_eq!("abcddd_z".find(|ch| ch > 'd' && ch < 'y'), None);
96+
/// ```
97+
///
98+
/// [`str::find`]: ../../../std/primitive.str.html#method.find
99+
/// [`str::contains`]: ../../../std/primitive.str.html#method.contains
63100
pub trait Pattern<'a>: Sized {
64101
/// Associated searcher for this pattern
65102
type Searcher: Searcher<'a>;

0 commit comments

Comments
 (0)