;;; JS TypedArray bindings
;;; Copyright (C) 2026 David Thompson <dave@spritely.institute>
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;;    http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.

;;; Commentary:
;;;
;;; JavaScript TypedArray bindings.
;;;
;;; Code:

(library (hoot typed-arrays)
  (export make-uint8array
          bytevector->uint8array
          uint8array-length
          uint8array-ref
          uint8array-set!)
  (import (hoot bytevectors)
          (hoot ffi)
          (hoot numbers)
          (hoot syntax))

  ;; length -> Uint8Array
  (define-foreign make-uint8array
    "rt" "make_uint8array" i32 -> (ref extern))
  ;; Uint8Array -> length
  (define-foreign uint8array-length
    "rt" "uint8array_length" (ref extern) -> i32)
  ;; Uint8Array, idx -> byte
  (define-foreign uint8array-ref
    "rt" "uint8array_ref" (ref extern) i32 -> i32)
  ;; Uint8Array, idx, byte -> ()
  (define-foreign uint8array-set!
    "rt" "uint8array_set" (ref extern) i32 i32 -> none)

  (define (bytevector->uint8array bv)
    (let* ((len (bytevector-length bv))
           (array (make-uint8array len)))
      (let lp ((i 0))
        (when (< i len)
          (uint8array-set! array i (bytevector-u8-ref bv i))
          (lp (1+ i))))
      array)))
