| 1657 | const TAB_INDENT_WIDTH: usize = 8; |
| 1658 | |
| 1659 | fn from_str(s: &str) -> Self { |
| 1660 | let mut iter = s.chars().peekable(); |
| 1661 | |
| 1662 | let spaces = iter.peeking_take_while(|c| *c == ' ').count(); |
| 1663 | let tabs = iter.peeking_take_while(|c| *c == '\t').count(); |
| 1664 | |
| 1665 | if tabs == 0 { |
| 1666 | // No indent, or spaces only indent |
| 1667 | return Self::Spaces(spaces); |
| 1668 | } |
| 1669 | |
| 1670 | let align_spaces = iter.peeking_take_while(|c| *c == ' ').count(); |
| 1671 | |
| 1672 | if spaces == 0 { |
| 1673 | if align_spaces == 0 { |
| 1674 | return Self::Tabs(tabs); |
| 1675 | } |
| 1676 | |
| 1677 | // At this point it's either a smart tab (tabs followed by spaces) or a wild mix of tabs and spaces. |
| 1678 | if iter.peek().copied() != Some('\t') { |
| 1679 | return Self::TabSpaces { |
| 1680 | tabs, |
| 1681 | spaces: align_spaces, |
| 1682 | }; |
| 1683 | } |
| 1684 | } else if align_spaces == 0 { |
| 1685 | return Self::SpacesTabs { spaces, tabs }; |
| 1686 | } |
| 1687 | |
| 1688 | // Sequence of spaces.. tabs, spaces, tabs... |
| 1689 | let mut width = spaces + tabs * Self::TAB_INDENT_WIDTH + align_spaces; |
| 1690 | // SAFETY: Safe because Ruff doesn't support files larger than 4GB. |
| 1691 | let mut len = TextSize::try_from(spaces + tabs + align_spaces).unwrap(); |
| 1692 | |
| 1693 | for char in iter { |
| 1694 | if char == '\t' { |
| 1695 | // Pad to the next multiple of tab_width |
| 1696 | width += Self::TAB_INDENT_WIDTH - (width.rem_euclid(Self::TAB_INDENT_WIDTH)); |
| 1697 | len += '\t'.text_len(); |
| 1698 | } else if char.is_whitespace() { |
| 1699 | width += char.len_utf8(); |
| 1700 | len += char.text_len(); |
| 1701 | } else { |
| 1702 | break; |
| 1703 | } |
| 1704 | } |
| 1705 | |
| 1706 | // Mixed tabs and spaces |
| 1707 | Self::Mixed { width, len } |
| 1708 | } |
| 1709 | |
| 1710 | /// Returns the indentation's visual width in columns/spaces. |
| 1711 | /// |