Login
7 branches 0 tags
Ben (X13/Arch) Removed args from NFunc 4877ff9 9 days ago 1259 Commits
nujel / tools / c-asset-packer.nuj
;;; Nujel - Copyright (C) 2020-2021 - Benjamin Vincent Schulenburg
;;; This project uses the MIT license, a copy should be included under /LICENSE
;;;
;;; Can be used to create C source files for various binary/text files to be
;;; included in exceutables

(def hex-cache (:alloc Array 256))
(dotimes (i 256)
  (set! hex-cache i (fmt " {i},")))

(defn create-c-asset (raw out symbol-name)
      :export
      (typecheck/only symbol-name :string)

      (:block-write out (fmt "unsigned long long int {symbol-name}_len = {};\n" (:length raw)))
      (:block-write out (fmt "unsigned char {symbol-name}[] = "))
      (:block-write out "{")
      (dotimes (i (:length raw))
               (when (zero? (bit-and i #xF))
                 (:block-write out "\n"))
               (:block-write out (ref hex-cache (ref raw i))))
      (:block-write out "};")
      (:close! out))

(defn create-string-asset (in symbol-name)
      :export
      (def out (:new StringOutputPort))
      (create-c-asset in out symbol-name)
      (:return-string out))

(defn main (args)
      :export
      (def filename (car args))
      (def output-file (cadr args))
      (def symbol-name (caddr args))
      (typecheck/only filename :string)
      (typecheck/only output-file :string)
      (typecheck/only symbol-name :string)
      (pfmtln "Packing {filename} into {output-file} as {symbol-name}")
      (def out (:new OutputPort (file/open-output* output-file :replace)))
      (:block-write out "/* This file is auto-generated, manual changes will be overwritten! */\n")
      (create-c-asset (slurp filename) out symbol-name))