|
| 1 | +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT |
| 2 | +// file at the top-level directory of this distribution and at |
| 3 | +// http://rust-lang.org/COPYRIGHT. |
| 4 | +// |
| 5 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 7 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 8 | +// option. This file may not be copied, modified, or distributed |
| 9 | +// except according to those terms. |
| 10 | + |
| 11 | +trait Matcher { |
| 12 | + fn next_match(&mut self) -> Option<(uint, uint)>; |
| 13 | +} |
| 14 | + |
| 15 | +struct CharPredMatcher<'a, 'b> { |
| 16 | + str: &'a str, |
| 17 | + pred: |char|:'b -> bool |
| 18 | +} |
| 19 | + |
| 20 | +impl<'a, 'b> Matcher for CharPredMatcher<'a, 'b> { |
| 21 | + fn next_match(&mut self) -> Option<(uint, uint)> { |
| 22 | + None |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +trait IntoMatcher<'a, T> { |
| 27 | + fn into_matcher(self, &'a str) -> T; |
| 28 | +} |
| 29 | + |
| 30 | +impl<'a, 'b> IntoMatcher<'a, CharPredMatcher<'a, 'b>> for |char|:'b -> bool { |
| 31 | + fn into_matcher(self, s: &'a str) -> CharPredMatcher<'a, 'b> { |
| 32 | + CharPredMatcher { |
| 33 | + str: s, |
| 34 | + pred: self |
| 35 | + } |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +struct MatchIndices<M> { |
| 40 | + matcher: M |
| 41 | +} |
| 42 | + |
| 43 | +impl<M: Matcher> Iterator<(uint, uint)> for MatchIndices<M> { |
| 44 | + fn next(&mut self) -> Option<(uint, uint)> { |
| 45 | + self.matcher.next_match() |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +fn match_indices<'a, M, T: IntoMatcher<'a, M>>(s: &'a str, from: T) -> MatchIndices<M> { |
| 50 | + let string_matcher = from.into_matcher(s); |
| 51 | + MatchIndices { matcher: string_matcher } |
| 52 | +} |
| 53 | + |
| 54 | +fn main() { |
| 55 | + let s = "abcbdef"; |
| 56 | + match_indices(s, |c: char| c == 'b') |
| 57 | + .collect::<Vec<(uint, uint)>>(); |
| 58 | +} |
0 commit comments