///|
let blake2s_iv : FixedArray[UInt32] = [
  0x6a09e667U, 0xbb67ae85U, 0x3c6ef372U, 0xa54ff53aU, 0x510e527fU, 0x9b05688cU, 0x1f83d9abU,
  0x5be0cd19U,
]

///|
let blake2s_sigma : FixedArray[Int32] = [
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 10, 4, 8, 9, 15, 13,
  6, 1, 12, 0, 2, 11, 7, 5, 3, 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9,
  4, 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, 9, 0, 5, 7, 2, 4, 10,
  15, 14, 1, 11, 12, 6, 8, 3, 13, 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14,
  1, 9, 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, 13, 11, 7, 14, 12,
  1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1,
  4, 10, 5, 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
]

///|
fn rotr32(x : UInt32, n : Int32) -> UInt32 {
  (x >> n) | (x << (32 - n))
}

///|
fn blake2s_g(
  v : FixedArray[UInt32],
  a : Int32,
  b : Int32,
  c : Int32,
  d : Int32,
  x : UInt32,
  y : UInt32,
) -> Unit {
  v[a] = v[a] + v[b] + x
  v[d] = rotr32(v[d] ^ v[a], 16)
  v[c] = v[c] + v[d]
  v[b] = rotr32(v[b] ^ v[c], 12)
  v[a] = v[a] + v[b] + y
  v[d] = rotr32(v[d] ^ v[a], 8)
  v[c] = v[c] + v[d]
  v[b] = rotr32(v[b] ^ v[c], 7)
}

///|
/// Incremental BLAKE2s hash / MAC state (RFC 7693).
pub struct Blake2s {
  priv h : FixedArray[UInt32]
  priv mut t_lo : UInt32
  priv mut t_hi : UInt32
  priv buf : FixedArray[Byte]
  priv mut buf_len : Int32
  priv out_len : Int32
}

///|
fn Blake2s::compress(self : Blake2s, is_last : Bool) -> Unit {
  let m = FixedArray::make(16, 0U)
  for i in 0..<16 {
    let off = i * 4
    m[i] = self.buf[off].to_uint() |
      (self.buf[off + 1].to_uint() << 8) |
      (self.buf[off + 2].to_uint() << 16) |
      (self.buf[off + 3].to_uint() << 24)
  }
  let v = FixedArray::make(16, 0U)
  for i in 0..<8 {
    v[i] = self.h[i]
    v[i + 8] = blake2s_iv[i]
  }
  v[12] = v[12] ^ self.t_lo
  v[13] = v[13] ^ self.t_hi
  if is_last {
    v[14] = v[14] ^ 0xffffffffU
  }
  for r in 0..<10 {
    let base = r * 16
    blake2s_g(
      v,
      0,
      4,
      8,
      12,
      m[blake2s_sigma[base + 0]],
      m[blake2s_sigma[base + 1]],
    )
    blake2s_g(
      v,
      1,
      5,
      9,
      13,
      m[blake2s_sigma[base + 2]],
      m[blake2s_sigma[base + 3]],
    )
    blake2s_g(
      v,
      2,
      6,
      10,
      14,
      m[blake2s_sigma[base + 4]],
      m[blake2s_sigma[base + 5]],
    )
    blake2s_g(
      v,
      3,
      7,
      11,
      15,
      m[blake2s_sigma[base + 6]],
      m[blake2s_sigma[base + 7]],
    )
    blake2s_g(
      v,
      0,
      5,
      10,
      15,
      m[blake2s_sigma[base + 8]],
      m[blake2s_sigma[base + 9]],
    )
    blake2s_g(
      v,
      1,
      6,
      11,
      12,
      m[blake2s_sigma[base + 10]],
      m[blake2s_sigma[base + 11]],
    )
    blake2s_g(
      v,
      2,
      7,
      8,
      13,
      m[blake2s_sigma[base + 12]],
      m[blake2s_sigma[base + 13]],
    )
    blake2s_g(
      v,
      3,
      4,
      9,
      14,
      m[blake2s_sigma[base + 14]],
      m[blake2s_sigma[base + 15]],
    )
  }
  for i in 0..<8 {
    self.h[i] = self.h[i] ^ v[i] ^ v[i + 8]
  }
}

///|
fn Blake2s::add_counter(self : Blake2s, inc : UInt32) -> Unit {
  let next = self.t_lo + inc
  if next < self.t_lo {
    self.t_hi = self.t_hi + 1U
  }
  self.t_lo = next
}

///|
/// Initialize a BLAKE2s context with output length `out_len` (1..=32) and optional `key` (0..=32 bytes).
pub fn Blake2s::new(
  out_len~ : Int32 = 32,
  key~ : BytesView = b"",
) -> Blake2s raise CryptoError {
  if out_len < 1 || out_len > 32 {
    raise CryptoError::InvalidOutputLength(actual=out_len)
  }
  let klen = key.length()
  if klen > 32 {
    raise CryptoError::InvalidKeyLength(expected=32, actual=klen)
  }
  let h = FixedArray::make(8, 0U)
  for i in 0..<8 {
    h[i] = blake2s_iv[i]
  }
  h[0] = h[0] ^
    0x01010000U ^
    (klen.reinterpret_as_uint() << 8) ^
    out_len.reinterpret_as_uint()
  let buf = FixedArray::make(64, b'\x00')
  let mut buf_len = 0
  if klen > 0 {
    for i in 0.. Unit {
  let mut pos = 0
  let len = data.length()
  while pos < len {
    if self.buf_len == 64 {
      self.add_counter(64U)
      self.compress(false)
      self.buf_len = 0
    }
    let space = 64 - self.buf_len
    let rem = len - pos
    let take = if rem < space { rem } else { space }
    for i in 0.. Bytes {
  self.add_counter(self.buf_len.reinterpret_as_uint())
  for i in self.buf_len..<64 {
    self.buf[i] = b'\x00'
  }
  self.compress(true)
  let full = FixedArray::make(32, b'\x00')
  for i in 0..<8 {
    write_u32_le(full, i * 4, self.h[i])
  }
  if self.out_len == 32 {
    Bytes::from_array(full)
  } else {
    let out = FixedArray::make(self.out_len, b'\x00')
    for i in 0.. Bytes raise CryptoError {
  let st = Blake2s::new(out_len~, key~)
  st.update(data)
  st.finalize()
}

///|
/// Unkeyed 32-byte BLAKE2s hash (`Hash(input)` in WireGuard §5.4).
pub fn blake2s_256(data : BytesView) -> Bytes {
  let st = try! Blake2s::new(out_len=32)
  st.update(data)
  st.finalize()
}

///|
/// Unkeyed 32-byte BLAKE2s hash over the concatenation `a || b`.
pub fn blake2s_256_pair(a : BytesView, b : BytesView) -> Bytes {
  let st = try! Blake2s::new(out_len=32)
  st.update(a)
  st.update(b)
  st.finalize()
}

///|
/// WireGuard `Mac(key, input)` (§5.4.4 / §5.4.7): 16-byte keyed BLAKE2s.
pub fn wg_mac(key : BytesView, input : BytesView) -> Bytes raise CryptoError {
  if key.length() < 1 || key.length() > 32 {
    raise CryptoError::InvalidKeyLength(expected=32, actual=key.length())
  }
  blake2s(input, out_len=16, key~)
}

///|
/// RFC 2104 HMAC-BLAKE2s-256 (64-byte block size, 32-byte output).
pub fn hmac_blake2s(key : BytesView, data : BytesView) -> Bytes {
  let k_block = FixedArray::make(64, b'\x00')
  if key.length() > 64 {
    let hashed = blake2s_256(key)
    for i in 0..<32 {
      k_block[i] = hashed[i]
    }
  } else {
    for i in 0.. Bytes {
  let k_block = FixedArray::make(64, b'\x00')
  if key.length() > 64 {
    let hashed = blake2s_256(key)
    for i in 0..<32 {
      k_block[i] = hashed[i]
    }
  } else {
    for i in 0.. Bytes {
  let prk = hmac_blake2s(key, input)
  hmac_blake2s(prk, [0x01])
}

///|
/// WireGuard `Kdf2(key, input)` (§5.4): two 32-byte HKDF-BLAKE2s outputs.
pub fn kdf2(key : BytesView, input : BytesView) -> (Bytes, Bytes) {
  let prk = hmac_blake2s(key, input)
  let t1 = hmac_blake2s(prk, [0x01])
  let t2 = hmac_blake2s_pair(prk, t1, [0x02])
  (t1, t2)
}

///|
/// WireGuard `Kdf3(key, input)` (§5.4): three 32-byte HKDF-BLAKE2s outputs.
pub fn kdf3(key : BytesView, input : BytesView) -> (Bytes, Bytes, Bytes) {
  let prk = hmac_blake2s(key, input)
  let t1 = hmac_blake2s(prk, [0x01])
  let t2 = hmac_blake2s_pair(prk, t1, [0x02])
  let t3 = hmac_blake2s_pair(prk, t2, [0x03])
  (t1, t2, t3)
}