| 1 | // Taken from https://github.com/rust-lang/rust/pull/86497 |
| 2 | // TODO: Remove when this is in the version of the Rust standard library that delta is building |
| 3 | // against. |
| 4 | |
| 5 | #[inline] |
| 6 | const fn is_utf8_char_boundary(b: u8) -> bool { |
| 7 | // This is bit magic equivalent to: b < 128 || b >= 192 |
| 8 | (b as i8) >= -0x40 |
| 9 | } |
| 10 | |
| 11 | #[inline] |
| 12 | pub fn floor_char_boundary(s: &str, index: usize) -> usize { |
| 13 | if index >= s.len() { |
| 14 | s.len() |
| 15 | } else { |
| 16 | let lower_bound = index.saturating_sub(3); |
| 17 | let new_index = s.as_bytes()[lower_bound..=index] |
| 18 | .iter() |
| 19 | .rposition(|b| is_utf8_char_boundary(*b)); |
| 20 | |
| 21 | // SAFETY: we know that the character boundary will be within four bytes |
| 22 | unsafe { lower_bound + new_index.unwrap_unchecked() } |
| 23 | } |
| 24 | } |