television_utils::strings

Function make_matched_string_printable

Source
pub fn make_matched_string_printable(
    matched_string: &str,
    match_ranges: Option<&[(u32, u32)]>,
) -> (String, Vec<(u32, u32)>)
Expand description

Make a matched string printable while preserving match ranges in the process.

This function preprocesses the matched string and returns a printable version of it along with the match ranges adjusted to the new string.

§Examples

use television_utils::strings::make_matched_string_printable;

let matched_string = "Hello, World!";
let match_ranges = vec![(0, 1), (7, 8)];
let match_ranges = Some(match_ranges.as_slice());
let (printable, match_indices) = make_matched_string_printable(matched_string, match_ranges);
assert_eq!(printable, "Hello, World!");
assert_eq!(match_indices, vec![(0, 1), (7, 8)]);

let matched_string = "Hello,\tWorld!";
let match_ranges = vec![(0, 1), (7, 8)];
let match_ranges = Some(match_ranges.as_slice());
let (printable, match_indices) = make_matched_string_printable(matched_string, match_ranges);
assert_eq!(printable, "Hello,    World!");
assert_eq!(match_indices, vec![(0, 1), (10, 11)]);

let matched_string = "Hello,\nWorld!";
let match_ranges = vec![(0, 1), (7, 8)];
let match_ranges = Some(match_ranges.as_slice());
let (printable, match_indices) = make_matched_string_printable(matched_string, match_ranges);
assert_eq!(printable, "Hello,World!");
assert_eq!(match_indices, vec![(0, 1), (6, 7)]);

let matched_string = "Hello, World!";
let (printable, match_indices) = make_matched_string_printable(matched_string, None);
assert_eq!(printable, "Hello, World!");
assert_eq!(match_indices, vec![]);

let matched_string = "build.rs";
let match_ranges = vec![(0, 1), (7, 8)];
let match_ranges = Some(match_ranges.as_slice());
let (printable, match_indices) = make_matched_string_printable(matched_string, match_ranges);
assert_eq!(printable, "build.rs");
assert_eq!(match_indices, vec![(0, 1), (7, 8)]);

let matched_string = "a\tb";
let match_ranges = vec![(0, 1), (2, 3)];
let match_ranges = Some(match_ranges.as_slice());
let (printable, match_indices) = make_matched_string_printable(matched_string, match_ranges);
assert_eq!(printable, "a    b");
assert_eq!(match_indices, vec![(0, 1), (5, 6)]);

let matched_string = "a\tbcd".repeat(65);
let match_ranges = vec![(0, 1), (310, 311)];
let match_ranges = Some(match_ranges.as_slice());
let (printable, match_indices) = make_matched_string_printable(&matched_string, match_ranges);
assert_eq!(printable.len(), 480);
assert_eq!(match_indices, vec![(0, 1)]);

§Panics

This will panic if the length of the printable string or the match indices don’t fit into a u32.