Skip to main content

parse_range

Function parse_range 

Source
pub fn parse_range(
    spec: &str,
    total: usize,
) -> Result<Option<(usize, usize)>, String>
Expand description

Parse a --range spec into a 0-based inclusive [start, end], clamped to a file of total lines. Returns None when the range selects nothing.

Accepts A:B (1-based, inclusive), A: (to end), :B (from start), and a bare A (one line). Lines are 1-based; 0 is an error.

ยงExamples

use coding_tools::view::parse_range;

assert_eq!(parse_range("2:4", 10).unwrap(), Some((1, 3))); // 0-based, inclusive
assert_eq!(parse_range("3", 10).unwrap(), Some((2, 2)));   // a single line
assert_eq!(parse_range("8:", 10).unwrap(), Some((7, 9)));  // open end
assert_eq!(parse_range(":3", 10).unwrap(), Some((0, 2)));  // open start
assert_eq!(parse_range("9:99", 10).unwrap(), Some((8, 9))); // end clamps to EOF
assert_eq!(parse_range("20:30", 10).unwrap(), None);        // wholly past EOF
assert!(parse_range("0:3", 10).is_err());                   // lines are 1-based