Replace all tabs in a string with spaces, using the given tab size.
(input: &str, tab_size: usize)
| 558 | |
| 559 | /// Replace all tabs in a string with spaces, using the given tab size. |
| 560 | pub fn expandtabs(input: &str, tab_size: usize) -> String { |
| 561 | let tab_stop = tab_size; |
| 562 | let mut expanded_str = String::with_capacity(input.len()); |
| 563 | let mut tab_size = tab_stop; |
| 564 | let mut col_count = 0usize; |
| 565 | for ch in input.chars() { |
| 566 | match ch { |
| 567 | '\t' => { |
| 568 | let num_spaces = tab_size - col_count; |
| 569 | col_count += num_spaces; |
| 570 | let expand = " ".repeat(num_spaces); |
| 571 | expanded_str.push_str(&expand); |
| 572 | } |
| 573 | '\r' | '\n' => { |
| 574 | expanded_str.push(ch); |
| 575 | col_count = 0; |
| 576 | tab_size = 0; |
| 577 | } |
| 578 | _ => { |
| 579 | expanded_str.push(ch); |
| 580 | col_count += 1; |
| 581 | } |
| 582 | } |
| 583 | if col_count >= tab_size { |
| 584 | tab_size += tab_stop; |
| 585 | } |
| 586 | } |
| 587 | expanded_str |
| 588 | } |
| 589 | |
| 590 | /// Creates an [`AsciiStr`][ascii::AsciiStr] from a string literal, throwing a compile error if the |
| 591 | /// literal isn't actually ascii. |