1- /// TODO make trait of string
2- /// Split string by prefix, including the prefix in the result.
3- pub ( crate ) fn split_prefix_inclusive < ' a > ( string : & ' a str , prefix : & str ) -> Vec < & ' a str > {
4- let matches = string. match_indices ( prefix) . map ( |( idx, _) | idx) ;
5- let mut start = 0 ;
6- let mut substrings = Vec :: new ( ) ;
7- for idx in matches {
8- if idx != start {
9- substrings. push ( & string[ start..idx] ) ;
10- start = idx;
1+ pub ( crate ) trait SplitPrefixInclusive {
2+ fn split_prefix_inclusive < ' a > ( & ' a self , prefix : & str ) -> Vec < & ' a str > ;
3+ }
4+
5+ impl SplitPrefixInclusive for str {
6+ /// Split string by prefix, including the prefix in the result.
7+ fn split_prefix_inclusive < ' a > ( & ' a self , prefix : & str ) -> Vec < & ' a str > {
8+ let matches = self . match_indices ( prefix) . map ( |( idx, _) | idx) ;
9+ let mut start = 0 ;
10+ let mut substrings = Vec :: new ( ) ;
11+ for idx in matches {
12+ if idx != start {
13+ substrings. push ( & self [ start..idx] ) ;
14+ start = idx;
15+ }
1116 }
12- }
13- substrings. push ( & string[ start..] ) ;
17+ substrings. push ( & self [ start..] ) ;
1418
15- substrings
19+ substrings
20+ }
1621}
1722
1823/// Finds the file name from a diff. The diff is expected to be of the form
@@ -33,16 +38,16 @@ mod tests {
3338 fn test_split_prefix_inclusive ( ) {
3439 let string = include_str ! ( "../tests/data/example_1.diff" ) ;
3540 let pattern = "diff --git " ;
36- assert_eq ! ( split_prefix_inclusive( string , pattern) . len( ) , 5 ) ;
41+ assert_eq ! ( string . split_prefix_inclusive( pattern) . len( ) , 5 ) ;
3742 }
3843
3944 #[ test]
4045 fn test_basic_split_prefix_inclusive ( ) {
4146 let string = "x111x222x333" ;
4247 let pattern = "x" ;
43- assert_eq ! ( split_prefix_inclusive( string , pattern) . len( ) , 3 ) ;
48+ assert_eq ! ( string . split_prefix_inclusive( pattern) . len( ) , 3 ) ;
4449 assert_eq ! (
45- split_prefix_inclusive( string , pattern) ,
50+ string . split_prefix_inclusive( pattern) ,
4651 & [ "x111" , "x222" , "x333" ]
4752 ) ;
4853 }
@@ -51,9 +56,9 @@ mod tests {
5156 fn test_basic_split_prefix_inclusive_2 ( ) {
5257 let string = "x111\n x222\n x333" ;
5358 let pattern = "\n x" ;
54- assert_eq ! ( split_prefix_inclusive( string , pattern) . len( ) , 3 ) ;
59+ assert_eq ! ( string . split_prefix_inclusive( pattern) . len( ) , 3 ) ;
5560 assert_eq ! (
56- split_prefix_inclusive( string , pattern) ,
61+ string . split_prefix_inclusive( pattern) ,
5762 & [ "x111" , "\n x222" , "\n x333" ]
5863 ) ;
5964 }
0 commit comments