| 1 |
//! Misc functions to improve readability |
| 2 |
|
| 3 |
use crate::{generic::ArraySlice, prelude::*}; |
| 4 |
use core::ptr::copy; |
| 5 |
#[cfg(feature = "logs")] |
| 6 |
use log::{debug, trace}; |
| 7 |
|
| 8 |
pub(crate) trait IntoLossy<T>: Sized { |
| 9 |
fn into_lossy(self) -> T; |
| 10 |
} |
| 11 |
|
| 12 |
/// Marks branch as impossible, UB if taken in prod, panics in debug |
| 13 |
/// |
| 14 |
/// This function should never be used lightly, it will cause UB if used wrong |
| 15 |
#[inline] |
| 16 |
#[allow(unused_variables)] |
| 17 |
pub(crate) unsafe fn never(s: &str) -> ! { |
| 18 |
#[cfg(debug_assertions)] |
| 19 |
panic!("{}", s); |
| 20 |
|
| 21 |
#[cfg(not(debug_assertions))] |
| 22 |
core::hint::unreachable_unchecked() |
| 23 |
} |
| 24 |
|
| 25 |
/// Encodes `char` into `ArrayString` at specified position, heavily unsafe |
| 26 |
/// |
| 27 |
/// We reimplement the `core` function to avoid panicking (UB instead, be careful) |
| 28 |
/// |
| 29 |
/// Reimplemented from: |
| 30 |
/// |
| 31 |
/// `https://github.com/rust-lang/rust/blob/7843e2792dce0f20d23b3c1cca51652013bef0ea/src/libcore/char/methods.rs#L447` |
| 32 |
/// # Safety |
| 33 |
/// |
| 34 |
/// - It's UB if index is outside of buffer's boundaries (buffer needs at most 4 bytes) |
| 35 |
/// - It's UB if index is inside a character (like a index 3 for "a🤔") |
| 36 |
#[inline] |
| 37 |
pub(crate) unsafe fn encode_char_utf8_unchecked<S: Capacity>( |
| 38 |
s: &mut ArrayString<S>, |
| 39 |
ch: char, |
| 40 |
index: u8, |
| 41 |
) { |
| 42 |
// UTF-8 ranges and tags for encoding characters |
| 43 |
#[allow(clippy::missing_docs_in_private_items)] |
| 44 |
const TAG_CONT: u8 = 0b1000_0000; |
| 45 |
#[allow(clippy::missing_docs_in_private_items)] |
| 46 |
const TAG_TWO_B: u8 = 0b1100_0000; |
| 47 |
#[allow(clippy::missing_docs_in_private_items)] |
| 48 |
const TAG_THREE_B: u8 = 0b1110_0000; |
| 49 |
#[allow(clippy::missing_docs_in_private_items)] |
| 50 |
const TAG_FOUR_B: u8 = 0b1111_0000; |
| 51 |
#[allow(clippy::missing_docs_in_private_items)] |
| 52 |
const MAX_ONE_B: u32 = 0x80; |
| 53 |
#[allow(clippy::missing_docs_in_private_items)] |
| 54 |
const MAX_TWO_B: u32 = 0x800; |
| 55 |
#[allow(clippy::missing_docs_in_private_items)] |
| 56 |
const MAX_THREE_B: u32 = 0x10000; |
| 57 |
|
| 58 |
trace!("Encode char: {} to {}", ch, index); |
| 59 |
|
| 60 |
debug_assert!(ch.len_utf8().saturating_add(index.into()) <= S::to_usize()); |
| 61 |
debug_assert!(ch.len_utf8().saturating_add(s.len().into()) <= S::to_usize()); |
| 62 |
let dst = s.array.as_mut_slice().get_unchecked_mut(index.into()..); |
| 63 |
let code = ch as u32; |
| 64 |
|
| 65 |
if code < MAX_ONE_B { |
| 66 |
debug_assert!(!dst.is_empty()); |
| 67 |
*dst.get_unchecked_mut(0) = code.into_lossy(); |
| 68 |
} else if code < MAX_TWO_B { |
| 69 |
debug_assert!(dst.len() >= 2); |
| 70 |
*dst.get_unchecked_mut(0) = (code >> 6 & 0x1F).into_lossy() | TAG_TWO_B; |
| 71 |
*dst.get_unchecked_mut(1) = (code & 0x3F).into_lossy() | TAG_CONT; |
| 72 |
} else if code < MAX_THREE_B { |
| 73 |
debug_assert!(dst.len() >= 3); |
| 74 |
*dst.get_unchecked_mut(0) = (code >> 12 & 0x0F).into_lossy() | TAG_THREE_B; |
| 75 |
*dst.get_unchecked_mut(1) = (code >> 6 & 0x3F).into_lossy() | TAG_CONT; |
| 76 |
*dst.get_unchecked_mut(2) = (code & 0x3F).into_lossy() | TAG_CONT; |
| 77 |
} else { |
| 78 |
debug_assert!(dst.len() >= 4); |
| 79 |
*dst.get_unchecked_mut(0) = (code >> 18 & 0x07).into_lossy() | TAG_FOUR_B; |
| 80 |
*dst.get_unchecked_mut(1) = (code >> 12 & 0x3F).into_lossy() | TAG_CONT; |
| 81 |
*dst.get_unchecked_mut(2) = (code >> 6 & 0x3F).into_lossy() | TAG_CONT; |
| 82 |
*dst.get_unchecked_mut(3) = (code & 0x3F).into_lossy() | TAG_CONT; |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
/// Copies part of slice to another part (`mem::copy`, basically `memmove`) |
| 87 |
#[inline] |
| 88 |
unsafe fn shift_unchecked(s: &mut [u8], from: usize, to: usize, len: usize) { |
| 89 |
debug!( |
| 90 |
"Shift {:?} {}-{}", |
| 91 |
&s.get(from..).map(|s| s.get(..len)), |
| 92 |
from, |
| 93 |
to |
| 94 |
); |
| 95 |
debug_assert!(to.saturating_add(len) <= s.len() && from.saturating_add(len) <= s.len()); |
| 96 |
let (f, t) = (s.as_ptr().add(from), s.as_mut_ptr().add(to)); |
| 97 |
copy(f, t, len); |
| 98 |
} |
| 99 |
|
| 100 |
/// Shifts string right |
| 101 |
/// |
| 102 |
/// # Safety |
| 103 |
/// |
| 104 |
/// It's UB if `to + (s.len() - from)` is bigger than [`S::to_u8()`] |
| 105 |
/// |
| 106 |
/// [`<S as Unsigned>::to_u8()`]: ../struct.ArrayString.html#CAPACITY |
| 107 |
#[inline] |
| 108 |
pub(crate) unsafe fn shift_right_unchecked<S, F, T>(s: &mut ArrayString<S>, from: F, to: T) |
| 109 |
where |
| 110 |
S: Capacity, |
| 111 |
F: Into<usize> + Copy, |
| 112 |
T: Into<usize> + Copy, |
| 113 |
{ |
| 114 |
let len = (s.len() as usize).saturating_sub(from.into()); |
| 115 |
debug_assert!(from.into() <= to.into() && to.into().saturating_add(len) <= S::to_usize()); |
| 116 |
debug_assert!(s.as_str().is_char_boundary(from.into())); |
| 117 |
shift_unchecked(s.array.as_mut_slice(), from.into(), to.into(), len); |
| 118 |
} |
| 119 |
|
| 120 |
/// Shifts string left |
| 121 |
#[inline] |
| 122 |
pub(crate) unsafe fn shift_left_unchecked<S, F, T>(s: &mut ArrayString<S>, from: F, to: T) |
| 123 |
where |
| 124 |
S: Capacity, |
| 125 |
F: Into<usize> + Copy, |
| 126 |
T: Into<usize> + Copy, |
| 127 |
{ |
| 128 |
debug_assert!(to.into() <= from.into() && from.into() <= s.len().into()); |
| 129 |
debug_assert!(s.as_str().is_char_boundary(from.into())); |
| 130 |
|
| 131 |
let len = (s.len() as usize).saturating_sub(to.into()); |
| 132 |
shift_unchecked(s.array.as_mut_slice(), from.into(), to.into(), len); |
| 133 |
} |
| 134 |
|
| 135 |
/// Returns error if size is outside of specified boundary |
| 136 |
#[inline] |
| 137 |
pub fn is_inside_boundary<S, L>(size: S, limit: L) -> Result<(), OutOfBounds> |
| 138 |
where |
| 139 |
S: Into<usize>, |
| 140 |
L: Into<usize>, |
| 141 |
{ |
| 142 |
let (s, l) = (size.into(), limit.into()); |
| 143 |
trace!("Out of bounds: ensures {} < {}", s, l); |
| 144 |
Some(()).filter(|_| s <= l).ok_or(OutOfBounds) |
| 145 |
} |
| 146 |
|
| 147 |
/// Returns error if index is not at a valid utf-8 char boundary |
| 148 |
#[inline] |
| 149 |
pub fn is_char_boundary<S: Capacity>(s: &ArrayString<S>, idx: u8) -> Result<(), Utf8> { |
| 150 |
trace!("Is char boundary: {} at {}", s.as_str(), idx); |
| 151 |
if s.as_str().is_char_boundary(idx.into()) { |
| 152 |
return Ok(()); |
| 153 |
} |
| 154 |
Err(Utf8) |
| 155 |
} |
| 156 |
|
| 157 |
/// Truncates string to specified size (ignoring last bytes if they form a partial `char`) |
| 158 |
#[inline] |
| 159 |
pub(crate) fn truncate_str(slice: &str, size: u8) -> &str { |
| 160 |
trace!("Truncate str: {} at {}", slice, size); |
| 161 |
if slice.is_char_boundary(size.into()) { |
| 162 |
unsafe { slice.get_unchecked(..size.into()) } |
| 163 |
} else if (size as usize) < slice.len() { |
| 164 |
let mut index = size.saturating_sub(1) as usize; |
| 165 |
while !slice.is_char_boundary(index) { |
| 166 |
index = index.saturating_sub(1); |
| 167 |
} |
| 168 |
unsafe { slice.get_unchecked(..index) } |
| 169 |
} else { |
| 170 |
slice |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
impl IntoLossy<u8> for usize { |
| 175 |
#[allow(clippy::cast_possible_truncation)] |
| 176 |
#[inline] |
| 177 |
fn into_lossy(self) -> u8 { |
| 178 |
self as u8 |
| 179 |
} |
| 180 |
} |
| 181 |
|
| 182 |
impl IntoLossy<u8> for u32 { |
| 183 |
#[allow(clippy::cast_possible_truncation)] |
| 184 |
#[inline] |
| 185 |
fn into_lossy(self) -> u8 { |
| 186 |
self as u8 |
| 187 |
} |
| 188 |
} |
| 189 |
|
| 190 |
#[cfg(test)] |
| 191 |
mod tests { |
| 192 |
use super::*; |
| 193 |
use core::str::from_utf8; |
| 194 |
|
| 195 |
#[test] |
| 196 |
fn truncate() { |
| 197 |
assert_eq!(truncate_str("i", 10), "i"); |
| 198 |
assert_eq!(truncate_str("iiiiii", 3), "iii"); |
| 199 |
assert_eq!(truncate_str("🤔🤔🤔", 5), "🤔"); |
| 200 |
} |
| 201 |
|
| 202 |
#[test] |
| 203 |
fn shift_right() { |
| 204 |
let _ = env_logger::try_init(); |
| 205 |
let mut ls = SmallString::try_from_str("abcdefg").unwrap(); |
| 206 |
unsafe { shift_right_unchecked(&mut ls, 0u8, 4u8) }; |
| 207 |
ls.size += 4; |
| 208 |
assert_eq!(ls.as_str(), "abcdabcdefg"); |
| 209 |
} |
| 210 |
|
| 211 |
#[test] |
| 212 |
fn shift_left() { |
| 213 |
let _ = env_logger::try_init(); |
| 214 |
let mut ls = SmallString::try_from_str("abcdefg").unwrap(); |
| 215 |
unsafe { shift_left_unchecked(&mut ls, 1u8, 0u8) }; |
| 216 |
ls.size -= 1; |
| 217 |
assert_eq!(ls.as_str(), "bcdefg"); |
| 218 |
} |
| 219 |
|
| 220 |
#[test] |
| 221 |
fn shift_nop() { |
| 222 |
let _ = env_logger::try_init(); |
| 223 |
let mut ls = SmallString::try_from_str("abcdefg").unwrap(); |
| 224 |
unsafe { shift_right_unchecked(&mut ls, 0u8, 0u8) }; |
| 225 |
assert_eq!(ls.as_str(), "abcdefg"); |
| 226 |
unsafe { shift_left_unchecked(&mut ls, 0u8, 0u8) }; |
| 227 |
assert_eq!(ls.as_str(), "abcdefg"); |
| 228 |
} |
| 229 |
|
| 230 |
#[test] |
| 231 |
fn encode_char_utf8() { |
| 232 |
let _ = env_logger::try_init(); |
| 233 |
let mut string = SmallString::default(); |
| 234 |
unsafe { |
| 235 |
encode_char_utf8_unchecked(&mut string, 'a', 0); |
| 236 |
assert_eq!(from_utf8(&string.array.as_mut_slice()[..1]).unwrap(), "a"); |
| 237 |
let mut string = SmallString::try_from_str("a").unwrap(); |
| 238 |
|
| 239 |
encode_char_utf8_unchecked(&mut string, '🤔', 1); |
| 240 |
assert_eq!( |
| 241 |
from_utf8(&string.array.as_mut_slice()[..5]).unwrap(), |
| 242 |
"a🤔" |
| 243 |
); |
| 244 |
} |
| 245 |
} |
| 246 |
} |