#[cfg(any(not(target_endian = "big"), test))]
#[must_use]
fn parse_digits4_le(digits: [u8; 4]) -> u16 {
let chunk1 = u32::from_le_bytes(digits);
const LOWER_MASK_1: u32 = 0x0f_00_0f_00;
const UPPER_MASK_1: u32 = 0x00_0f_00_0f;
let chunk1_lower = (chunk1 & LOWER_MASK_1) >> 8;
let chunk1_upper = (chunk1 & UPPER_MASK_1) * 10;
let chunk2: u32 = chunk1_lower + chunk1_upper;
((chunk2 >> 16) + (chunk2 * 100)) as u16
}
#[cfg(any(target_endian = "big", test))]
#[must_use]
fn parse_digits4_be(digits: [u8; 4]) -> u16 {
let chunk1 = u32::from_be_bytes(digits);
const LOWER_MASK_1: u32 = 0x00_0f_00_0f;
const UPPER_MASK_1: u32 = 0x0f_00_0f_00;
let chunk1_lower = chunk1 & LOWER_MASK_1;
let chunk1_upper = ((chunk1 & UPPER_MASK_1) >> 8) * 10;
let chunk2: u32 = chunk1_lower + chunk1_upper;
((chunk2 >> 16) * 100 + chunk2) as u16
}
#[inline]
#[must_use]
pub(crate) fn parse_digits4(digits: [u8; 4]) -> u16 {
#[cfg(not(target_endian = "big"))]
{
parse_digits4_le(digits)
}
#[cfg(target_endian = "big")]
{
parse_digits4_be(digits)
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::convert::TryFrom;
fn as_digit4(s: &str) -> [u8; 4] {
TryFrom::try_from(s.as_bytes()).unwrap()
}
#[test]
fn digits4_le() {
assert_eq!(parse_digits4_le(as_digit4("0000")), 0000);
assert_eq!(parse_digits4_le(as_digit4("1234")), 1234);
assert_eq!(parse_digits4_le(as_digit4("8765")), 8765);
assert_eq!(parse_digits4_le(as_digit4("9999")), 9999);
}
#[test]
fn digits4_be() {
assert_eq!(parse_digits4_be(as_digit4("0000")), 0000);
assert_eq!(parse_digits4_be(as_digit4("1234")), 1234);
assert_eq!(parse_digits4_be(as_digit4("8765")), 8765);
assert_eq!(parse_digits4_be(as_digit4("9999")), 9999);
}
#[test]
fn digits4() {
assert_eq!(parse_digits4(as_digit4("0000")), 0000);
assert_eq!(parse_digits4(as_digit4("1234")), 1234);
assert_eq!(parse_digits4(as_digit4("8765")), 8765);
assert_eq!(parse_digits4(as_digit4("9999")), 9999);
}
}