@@ -5,9 +5,9 @@ use anyhow::bail;
55const RANGE_SEPARATOR : & ' static str = ":" ;
66pub const DEFAULT_RANGE : & ' static str = "start:end" ;
77
8- pub struct Range ( pub String , pub String ) ;
8+ pub struct Range < T > ( pub T , pub T ) ;
99
10- impl Range {
10+ impl Range < String > {
1111 // Prepare range string by following rules:
1212 //
1313 // If raw_range is equal to "n:", which means x:end
@@ -30,20 +30,22 @@ impl Range {
3030 let range = Range :: prepare_range ( range_str) ;
3131 let range_points = range. split ( RANGE_SEPARATOR ) . collect :: < Vec < _ > > ( ) ;
3232
33- if range_points. len ( ) != 2 {
33+ // When range is in format "start:end", the length of range_points is 2
34+ // When range is in format "line_number", the length of range_points is 1
35+ if range_points. len ( ) != 2 && range_points. len ( ) != 1 {
3436 bail ! ( "Invalid range format" ) ;
3537 }
3638
37- Ok ( Range (
38- range_points[ 0 ] . to_string ( ) ,
39- range_points [ 1 ] . to_string ( ) ,
40- ) )
39+ let start = range_points [ 0 ] . to_string ( ) ;
40+ let end = range_points. get ( 1 ) . unwrap_or ( & start . as_str ( ) ) . to_string ( ) ;
41+
42+ Ok ( Range ( start , end ) )
4143 }
4244
4345 // Parse "start" to 0, "end" to lines.len(), and other values to usize
44- fn parse_range ( & self , code_snippet_lines : & Lines ) -> anyhow:: Result < ( usize , usize ) > {
46+ pub fn parse_range ( & self , code_snippet : & str ) -> anyhow:: Result < Range < usize > > {
4547 let Range ( start, end) = self ;
46- let lines = code_snippet_lines . clone ( ) . collect :: < Vec < & str > > ( ) ;
48+ let lines = code_snippet . lines ( ) . clone ( ) . collect :: < Vec < & str > > ( ) ;
4749 let start = parse_range_point ( & start, & lines) ?;
4850 let end = parse_range_point ( & end, & lines) ?;
4951 let points = if start > end {
@@ -52,15 +54,17 @@ impl Range {
5254 ( start, end)
5355 } ;
5456
55- Ok ( points)
57+ Ok ( Range ( points. 0 , points . 1 ) )
5658 }
59+ }
5760
58- pub fn cut_code_snippet ( & self , code_snippet : String ) -> anyhow:: Result < String > {
61+ impl Range < usize > {
62+ pub fn cut_code_snippet ( & self , code_snippet : & str ) -> anyhow:: Result < String > {
63+ let Range ( start, end) = self ;
5964 let code_snippet_lines = code_snippet. lines ( ) ;
60- let ( start, end) = self . parse_range ( & code_snippet_lines) ?;
6165 let code_snippet = code_snippet_lines
62- . skip ( start)
63- . take ( end - start)
66+ . skip ( start - 1 )
67+ . take ( ( end + 1 ) - start)
6468 . collect :: < Vec < & str > > ( )
6569 . join ( "\n " ) ;
6670
0 commit comments