//! Construction of a [`U256`] from a 32-byte big-endian array.
use super::U256;

impl U256 {
    /// Creates a new [`U256`] from a 32-byte array in big-endian order.
    ///
    /// Bytes `[0..8]` become limb `w0` (most significant), bytes `[8..16]`
    /// become `w1`, bytes `[16..24]` become `w2`, and bytes `[24..32]`
    /// become `w3` (least significant).
    ///
    /// # Examples
    ///
    /// ```
    /// use cnfy_uint::u256::U256;
    ///
    /// let bytes = [
    ///     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    ///     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
    /// ];
    /// assert_eq!(U256::from_be_bytes(bytes), U256::from_be_limbs([0, 0, 0, 1]));
    /// ```
    #[inline]
    pub const fn from_be_bytes(bytes: [u8; 32]) -> Self {
        let w0 = u64::from_be_bytes([
            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
        ]);
        let w1 = u64::from_be_bytes([
            bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15],
        ]);
        let w2 = u64::from_be_bytes([
            bytes[16], bytes[17], bytes[18], bytes[19], bytes[20], bytes[21], bytes[22], bytes[23],
        ]);
        let w3 = u64::from_be_bytes([
            bytes[24], bytes[25], bytes[26], bytes[27], bytes[28], bytes[29], bytes[30], bytes[31],
        ]);
        Self([w3, w2, w1, w0])
    }
}

#[cfg(test)]
mod ai_tests {
    use super::*;

    /// All zeros produces the zero value.
    #[test]
    fn zero() {
        assert_eq!(
            U256::from_be_bytes([0; 32]),
            U256::from_be_limbs([0, 0, 0, 0]),
        );
    }

    /// All ones produces the maximum value.
    #[test]
    fn max() {
        assert_eq!(
            U256::from_be_bytes([0xFF; 32]),
            U256::from_be_limbs([u64::MAX, u64::MAX, u64::MAX, u64::MAX]),
        );
    }

    /// Byte 31 (least significant) maps to the low bit of limb w3.
    #[test]
    fn single_lsb() {
        let mut bytes = [0u8; 32];
        bytes[31] = 1;
        assert_eq!(
            U256::from_be_bytes(bytes),
            U256::from_be_limbs([0, 0, 0, 1]),
        );
    }

    /// Byte 0 (most significant) maps to the high bit of limb w0.
    #[test]
    fn single_msb() {
        let mut bytes = [0u8; 32];
        bytes[0] = 0x80;
        assert_eq!(
            U256::from_be_bytes(bytes),
            U256::from_be_limbs([0x8000000000000000, 0, 0, 0]),
        );
    }

    /// Boundary between w1 and w2 at bytes 15/16.
    #[test]
    fn limb_boundary() {
        let mut bytes = [0u8; 32];
        bytes[15] = 1;
        bytes[16] = 1;
        assert_eq!(
            U256::from_be_bytes(bytes),
            U256::from_be_limbs([0, 1, 0x0100000000000000, 0]),
        );
    }
}
