Skip to content

Commit d8fb7f1

Browse files
committed
Merge #143.
2 parents 899f755 + fee5fae commit d8fb7f1

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

Diff for: src/re.rs

+27-2
Original file line numberDiff line numberDiff line change
@@ -976,6 +976,12 @@ impl<'t> Captures<'t> {
976976

977977
/// Get a group by index.
978978
///
979+
/// `'t` is the lifetime of the matched text.
980+
///
981+
/// The text can't outlive the `Captures` object if this method is
982+
/// used, because of how `Index` is defined (normally `a[i]` is part
983+
/// of `a` and can't outlive it); to do that, use `at()` instead.
984+
///
979985
/// # Panics
980986
/// If there is no group at the given index.
981987
impl<'t> Index<usize> for Captures<'t> {
@@ -990,13 +996,20 @@ impl<'t> Index<usize> for Captures<'t> {
990996

991997
/// Get a group by name.
992998
///
999+
/// `'t` is the lifetime of the matched text and `'i` is the lifetime
1000+
/// of the group name (the index).
1001+
///
1002+
/// The text can't outlive the `Captures` object if this method is
1003+
/// used, because of how `Index` is defined (normally `a[i]` is part
1004+
/// of `a` and can't outlive it); to do that, use `name` instead.
1005+
///
9931006
/// # Panics
9941007
/// If there is no group named by the given value.
995-
impl<'t> Index<&'t str> for Captures<'t> {
1008+
impl<'t, 'i> Index<&'i str> for Captures<'t> {
9961009

9971010
type Output = str;
9981011

999-
fn index<'a>(&'a self, name: &str) -> &'a str {
1012+
fn index<'a>(&'a self, name: &'i str) -> &'a str {
10001013
match self.name(name) {
10011014
None => panic!("no group named '{}'", name),
10021015
Some(ref s) => s,
@@ -1295,4 +1308,16 @@ mod test {
12951308
let cap = re.captures("abc").unwrap();
12961309
let _ = cap["bad name"];
12971310
}
1311+
1312+
#[test]
1313+
fn test_cap_index_lifetime() {
1314+
// This is a test of whether the types on `caps["..."]` are general
1315+
// enough. If not, this will fail to typecheck.
1316+
fn inner(s: &str) -> usize {
1317+
let re = Regex::new(r"(?P<number>\d+)").unwrap();
1318+
let caps = re.captures(s).unwrap();
1319+
caps["number"].len()
1320+
}
1321+
assert_eq!(inner("123"), 3);
1322+
}
12981323
}

0 commit comments

Comments
 (0)