//! Conversion from [`U256`] into a `[u8; 32]` big-endian byte array.
use super::U256;

/// Converts a [`U256`] into a 32-byte array in big-endian order where
/// byte `[0]` is the most significant and byte `[31]` is the least
/// significant.
///
/// This is the inverse of [`U256::from_be_bytes`]. Each of the four
/// `u64` limbs is serialized via `u64::to_be_bytes` into the
/// corresponding 8-byte slice.
///
/// # Examples
///
/// ```
/// use cnfy_uint::u256::U256;
///
/// let v = U256::from_be_limbs([0, 0, 0, 1]);
/// let bytes: [u8; 32] = v.into();
/// assert_eq!(bytes[31], 1);
/// assert_eq!(bytes[0], 0);
/// ```
impl From<U256> for [u8; 32] {
    #[inline]
    fn from(value: U256) -> Self {
        let w0 = value.0[3].to_be_bytes();
        let w1 = value.0[2].to_be_bytes();
        let w2 = value.0[1].to_be_bytes();
        let w3 = value.0[0].to_be_bytes();
        [
            w0[0], w0[1], w0[2], w0[3], w0[4], w0[5], w0[6], w0[7], w1[0], w1[1], w1[2], w1[3],
            w1[4], w1[5], w1[6], w1[7], w2[0], w2[1], w2[2], w2[3], w2[4], w2[5], w2[6], w2[7],
            w3[0], w3[1], w3[2], w3[3], w3[4], w3[5], w3[6], w3[7],
        ]
    }
}

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

    /// Round-trip: from_be_bytes then into bytes returns the original.
    #[test]
    fn round_trip() {
        let mut bytes = [0u8; 32];
        bytes[0] = 0xAB;
        bytes[15] = 0xCD;
        bytes[31] = 0xEF;
        let v = U256::from_be_bytes(bytes);
        let back: [u8; 32] = v.into();
        assert_eq!(back, bytes);
    }

    /// Zero produces all-zero bytes.
    #[test]
    fn zero() {
        let bytes: [u8; 32] = U256::ZERO.into();
        assert_eq!(bytes, [0u8; 32]);
    }

    /// MAX produces all-0xFF bytes.
    #[test]
    fn max() {
        let bytes: [u8; 32] = U256::MAX.into();
        assert_eq!(bytes, [0xFF; 32]);
    }

    /// Byte 31 holds the LSB of the lowest limb.
    #[test]
    fn lsb_position() {
        let v = U256::from_be_limbs([0, 0, 0, 0x42]);
        let bytes: [u8; 32] = v.into();
        assert_eq!(bytes[31], 0x42);
        assert_eq!(bytes[30], 0);
    }
}
