// MoonBit adaptation and SIMD additions by justjavac, 2026.
// Scalar grammar follows uWebSockets, authored by Alex Hultman, 2018-2026.
// Intellectual property of third-party. Upstream Apache-2.0: LICENSE-APACHE and NOTICE.

///|
/// Recognizes RFC tchar bytes without accepting separator or control characters.
fn is_token(byte : Byte) -> Bool {
  match byte {
    b'A'..<=b'Z' | b'a'..<=b'z' | b'0'..<=b'9' => true
    b'!'
    | b'#'
    | b'$'
    | b'%'
    | b'&'
    | b'\''
    | b'*'
    | b'+'
    | b'-'
    | b'.'
    | b'^'
    | b'_'
    | b'`'
    | b'|'
    | b'~' => true
    _ => false
  }
}

///|
/// Lowercases only ASCII letters in an immutable copy of a header name.
fn lowercase(input : BytesView) -> Bytes {
  Bytes::makei(input.length(), i => {
    let byte = input[i]
    if byte >= b'A' && byte <= b'Z' {
      byte | 32
    } else {
      byte
    }
  })
}

///|
/// Finds a byte in scalar code, returning the view length when absent.
fn find_byte_scalar(input : BytesView, byte : Byte) -> Int32 {
  for index, current in input {
    if current == byte {
      return index
    }
  }
  input.length()
}

///|
/// Finds CR candidates with checked sixteen-byte loads and a scalar remainder.
#cfg(any(target="native", target="wasm"))
fn find_byte_vector(input : BytesView, byte : Byte) -> Int32 {
  let data = input.data()
  let start = input.start_offset()
  let length = input.length()
  let offset = for offset = 0; length - offset >= 16; offset = offset + 16 {
    // The view guard bounds every loaded byte, including unaligned subviews.
    let block = data.unsafe_extract_v128_aligned(start + offset)
    let mask = @simd.i8x16_bitmask(
      @simd.i8x16_eq(block, @simd.i8x16_splat(byte)),
    )
    if mask != 0 {
      return offset + mask.ctz()
    }
  } nobreak {
    offset
  }
  offset + find_byte_scalar(input[offset:], byte)
}

///|
/// Dispatches a byte search only to backends with standard V128 support.
#cfg(any(target="native", target="wasm"))
fn find_byte(input : BytesView, byte : Byte, algorithm : Algorithm) -> Int32 {
  if algorithm == Simd {
    return find_byte_vector(input, byte)
  }
  ignore(algorithm)
  find_byte_scalar(input, byte)
}

///|
/// Uses bounded scalar byte searches on backends without V128 support.
#cfg(not(any(target="native", target="wasm")))
fn find_byte(input : BytesView, byte : Byte, _algorithm : Algorithm) -> Int32 {
  find_byte_scalar(input, byte)
}

///|
/// Finds a target terminator or a byte outside visible ASCII in scalar code.
fn target_end_scalar(input : BytesView) -> Int32 {
  for index, byte in input {
    if byte < 33 || byte > 126 {
      return index
    }
  }
  input.length()
}

///|
/// Finds invalid target bytes using unsigned lane comparisons and a bounded tail.
#cfg(any(target="native", target="wasm"))
fn target_end_vector(input : BytesView) -> Int32 {
  let data = input.data()
  let start = input.start_offset()
  let length = input.length()
  let offset = for offset = 0; length - offset >= 16; offset = offset + 16 {
    let block = data.unsafe_extract_v128_aligned(start + offset)
    let mask = @simd.i8x16_bitmask(
      @simd.v128_or_(
        @simd.i8x16_lt_u(block, @simd.i8x16_splat(33)),
        @simd.i8x16_gt_u(block, @simd.i8x16_splat(126)),
      ),
    )
    if mask != 0 {
      return offset + mask.ctz()
    }
  } nobreak {
    offset
  }
  offset + target_end_scalar(input[offset:])
}

///|
/// Selects an equivalent scalar or vector target scan for the requested backend.
#cfg(any(target="native", target="wasm"))
fn target_end(input : BytesView, algorithm : Algorithm) -> Int32 {
  if algorithm == Simd {
    return target_end_vector(input)
  }
  ignore(algorithm)
  target_end_scalar(input)
}

///|
/// Keeps request-target validation scalar on backends without V128 support.
#cfg(not(any(target="native", target="wasm")))
fn target_end(input : BytesView, _algorithm : Algorithm) -> Int32 {
  target_end_scalar(input)
}

///|
/// Finds a field-value CR or forbidden control, allowing HTAB and obs-text.
fn value_end_scalar(input : BytesView) -> Int32 {
  for index, byte in input {
    if byte < 32 && byte != 9 {
      return index
    }
  }
  input.length()
}

///|
/// Excludes HTAB from a vector control-byte mask and bounds every input load.
#cfg(any(target="native", target="wasm"))
fn value_end_vector(input : BytesView) -> Int32 {
  let data = input.data()
  let start = input.start_offset()
  let length = input.length()
  let offset = for offset = 0; length - offset >= 16; offset = offset + 16 {
    let block = data.unsafe_extract_v128_aligned(start + offset)
    let mask = @simd.i8x16_bitmask(
      @simd.v128_andnot(
        @simd.i8x16_lt_u(block, @simd.i8x16_splat(32)),
        @simd.i8x16_eq(block, @simd.i8x16_splat(9)),
      ),
    )
    if mask != 0 {
      return offset + mask.ctz()
    }
  } nobreak {
    offset
  }
  offset + value_end_scalar(input[offset:])
}

///|
/// Selects an equivalent field-value scan with scalar backend fallbacks.
#cfg(any(target="native", target="wasm"))
fn value_end(input : BytesView, algorithm : Algorithm) -> Int32 {
  if algorithm == Simd {
    return value_end_vector(input)
  }
  ignore(algorithm)
  value_end_scalar(input)
}

///|
/// Keeps field-value validation scalar on backends without V128 support.
#cfg(not(any(target="native", target="wasm")))
fn value_end(input : BytesView, _algorithm : Algorithm) -> Int32 {
  value_end_scalar(input)
}

///|
/// Tracks a split CRLFCRLF delimiter without rescanning buffered input.
fn head_end(
  input : BytesView,
  previous : Int32,
  algorithm : Algorithm,
) -> (Int32, Int32) {
  for offset = 0, matched = previous; offset < input.length(); {
    let offset = if matched == 0 {
      offset + find_byte(input[offset:], 13, algorithm)
    } else {
      offset
    }
    if offset == input.length() {
      return (offset, matched)
    }
    let byte = input[offset]
    let matched = match (matched, byte) {
      (0, 13) | (1, 13) | (3, 13) => 1
      (1, 10) => 2
      (2, 13) => 3
      (3, 10) => 4
      _ => 0
    }
    if matched == 4 {
      return (offset + 1, 4)
    }
    continue offset + 1, matched
  } nobreak {
    (offset, matched)
  }
}