Skip to content

Commit 890e0c6

Browse files
committed
Loosen lifetime bounds on accessing named captures via Index.
The current definition equates the lifetime of the strings being matched/captured and the string used as the capture name. The latter is usually `'static` (string literals), which leads to confusing [borrow-check errors][err] on reasonable-looking code. This change declares the two lifetimes as separate; this should be a strict increase in the set of `impl` instances, so it's a minor version bump. [err][]: https://gist.github.com/jld/476a13a00ad05bd99a63
1 parent 318aac0 commit 890e0c6

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "regex"
3-
version = "0.1.43"
3+
version = "0.1.44"
44
authors = ["The Rust Project Developers"]
55
license = "MIT/Apache-2.0"
66
readme = "README.md"

src/re.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -970,11 +970,11 @@ impl<'t> Index<usize> for Captures<'t> {
970970
///
971971
/// # Panics
972972
/// If there is no group named by the given value.
973-
impl<'t> Index<&'t str> for Captures<'t> {
973+
impl<'t, 'i> Index<&'i str> for Captures<'t> {
974974

975975
type Output = str;
976976

977-
fn index<'a>(&'a self, name: &str) -> &'a str {
977+
fn index<'a>(&'a self, name: &'i str) -> &'a str {
978978
match self.name(name) {
979979
None => panic!("no group named '{}'", name),
980980
Some(ref s) => s,
@@ -1262,4 +1262,16 @@ mod test {
12621262
let cap = re.captures("abc").unwrap();
12631263
let _ = cap["bad name"];
12641264
}
1265+
1266+
#[test]
1267+
fn test_cap_index_lifetime() {
1268+
// This is a test of whether the types on `caps["..."]` are general
1269+
// enough. If not, this will fail to typecheck.
1270+
fn inner(s: &str) -> usize {
1271+
let re = Regex::new(r"(?P<number>\d+)").unwrap();
1272+
let caps = re.captures(s).unwrap();
1273+
caps["number"].len()
1274+
}
1275+
assert_eq!(inner("123"), 3);
1276+
}
12651277
}

0 commit comments

Comments
 (0)