| 1 | //! Simple, shared algorithms for slices and iterators. |
| 2 | |
| 3 | use crate::num::Integer; |
| 4 | |
| 5 | /// Copy bytes from source to destination. |
| 6 | /// |
| 7 | /// This is only used in our compact and radix integer formatted, so |
| 8 | /// performance isn't the highest consideration here. |
| 9 | #[inline(always)] |
| 10 | #[cfg(any(feature = "write-floats", feature = "write-integers"))] |
| 11 | pub fn copy_to_dst<T: Copy, Bytes: AsRef<[T]>>(dst: &mut [T], src: Bytes) -> usize { |
| 12 | let src = src.as_ref(); |
| 13 | dst[..src.len()].copy_from_slice(src); |
| 14 | |
| 15 | src.len() |
| 16 | } |
| 17 | |
| 18 | /// Count the number of trailing characters equal to a given value. |
| 19 | #[inline(always)] |
| 20 | #[cfg(any(feature = "write-floats", feature = "write-integers"))] |
| 21 | pub fn rtrim_char_count(slc: &[u8], c: u8) -> usize { |
| 22 | slc.iter().rev().take_while(|&&si| si == c).count() |
| 23 | } |
| 24 | |
| 25 | /// Count the number of leading characters equal to a given value. |
| 26 | #[inline(always)] |
| 27 | #[cfg(any(feature = "write-floats", feature = "write-integers"))] |
| 28 | pub fn ltrim_char_count(slc: &[u8], c: u8) -> usize { |
| 29 | slc.iter().take_while(|&&si| si == c).count() |
| 30 | } |
| 31 | |
| 32 | /// Check to see if parsing the float cannot possible overflow. |
| 33 | /// |
| 34 | /// This allows major optimizations for those types, since we can skip checked |
| 35 | /// arithmetic. Adapted from the rust [corelib][`core`]. |
| 36 | /// |
| 37 | /// [`core`]: <https://doc.rust-lang.org/1.81.0/src/core/num/mod.rs.html#1389> |
| 38 | #[inline(always)] |
| 39 | pub fn cannot_overflow<T: Integer>(length: usize, radix: u32) -> bool { |
| 40 | length <= T::overflow_digits(radix) |
| 41 | } |