//! crypto/md5: hand-rolled MD5.
//!
//! MD5 is broken for cryptographic use; for checksums / interop only.

use crate::types::{byte, int};

pub const Size: int = 16;
pub const BlockSize: int = 64;

pub struct Digest {
    state: [u32; 4],
    buf: Vec<byte>,
    len: u64,
}

#[allow(non_snake_case)]
pub fn New() -> Digest {
    Digest {
        state: [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476],
        buf: Vec::with_capacity(64),
        len: 0,
    }
}

impl Digest {
    pub fn Write(&mut self, p: &[byte]) -> (int, crate::errors::error) {
        self.len = self.len.wrapping_add(p.len() as u64);
        self.buf.extend_from_slice(p);
        while self.buf.len() >= 64 {
            let block: [u8; 64] = self.buf[..64].try_into().unwrap();
            process(&mut self.state, &block);
            self.buf.drain(..64);
        }
        (p.len() as int, crate::errors::nil)
    }

    pub fn Sum(&self, b: &[byte]) -> Vec<byte> {
        let mut state = self.state;
        let mut buf = self.buf.clone();
        let bit_len = self.len.wrapping_mul(8);
        buf.push(0x80);
        while buf.len() % 64 != 56 {
            buf.push(0);
        }
        buf.extend_from_slice(&bit_len.to_le_bytes());
        let mut i = 0;
        while i < buf.len() {
            let block: [u8; 64] = buf[i..i + 64].try_into().unwrap();
            process(&mut state, &block);
            i += 64;
        }
        let mut out = b.to_vec();
        for v in state.iter() {
            out.extend_from_slice(&v.to_le_bytes());
        }
        out
    }

    pub fn Reset(&mut self) {
        self.state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];
        self.buf.clear();
        self.len = 0;
    }
}

#[allow(non_snake_case)]
pub fn Sum(data: &[byte]) -> [byte; 16] {
    let mut h = New();
    h.Write(data);
    let v = h.Sum(&[]);
    let mut out = [0u8; 16];
    out.copy_from_slice(&v);
    out
}

const S: [u32; 64] = [
    7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
    5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
    4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
    6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
];

const K: [u32; 64] = [
    0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a,
    0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
    0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340,
    0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
    0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8,
    0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
    0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa,
    0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
    0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92,
    0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
    0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
];

fn process(state: &mut [u32; 4], block: &[u8; 64]) {
    let mut m = [0u32; 16];
    for i in 0..16 {
        m[i] = u32::from_le_bytes([
            block[i * 4], block[i * 4 + 1], block[i * 4 + 2], block[i * 4 + 3]
        ]);
    }
    let mut a = state[0];
    let mut b = state[1];
    let mut c = state[2];
    let mut d = state[3];
    for i in 0..64 {
        let (f, g) = match i {
            0..=15  => ((b & c) | (!b & d), i),
            16..=31 => ((d & b) | (!d & c), (5 * i + 1) % 16),
            32..=47 => (b ^ c ^ d, (3 * i + 5) % 16),
            _        => (c ^ (b | !d), (7 * i) % 16),
        };
        let temp = d;
        d = c;
        c = b;
        let sum = a.wrapping_add(f).wrapping_add(K[i]).wrapping_add(m[g]);
        b = b.wrapping_add(sum.rotate_left(S[i]));
        a = temp;
    }
    state[0] = state[0].wrapping_add(a);
    state[1] = state[1].wrapping_add(b);
    state[2] = state[2].wrapping_add(c);
    state[3] = state[3].wrapping_add(d);
}

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

    fn hex(b: &[u8]) -> String {
        b.iter().map(|x| format!("{:02x}", x)).collect()
    }

    #[test]
    fn md5_empty() {
        let h = Sum(b"");
        assert_eq!(hex(&h), "d41d8cd98f00b204e9800998ecf8427e");
    }

    #[test]
    fn md5_abc() {
        let h = Sum(b"abc");
        assert_eq!(hex(&h), "900150983cd24fb0d6963f7d28e17f72");
    }

    #[test]
    fn md5_streaming_matches_single() {
        let mut a = New();
        a.Write(b"hello ");
        a.Write(b"world");
        let sb = Sum(b"hello world");
        assert_eq!(a.Sum(&[]), sb.to_vec());
    }
}
