Login
7 branches 0 tags
Ben (X13/Arch) Simplified NFunc handling c0a27b4 2 years ago 1180 Commits
nujel / stdlib_modules / compiler / 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 "0x{i:02X}, ")))

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

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

(defn create-string-asset (in symbol-name)
      :export
      (with-string-port out (create-c-asset in out symbol-name)))

(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)
      (def out (make-output-port (file/open-output* output-file :replace)))
      (out 'block-write "/* This file is auto-generated, manual changes will be overwritten! */\n")
      (create-c-asset (slurp filename) out symbol-name))