Login
7 branches 0 tags
Benjamin Vincent Schulenburg Added :file-handle type symbol 301709c 3 years ago 888 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 [array/allocate 256]]
[dotimes [i 256]
  [array/set! hex-cache i [fmt "0x{i:02X}, "]]]

[defn create-c-asset [filename output-file symbol-name]
      :export
      [typecheck/only filename :string]
      [typecheck/only output-file :string]
      [typecheck/only symbol-name :string]
      [def raw [slurp filename]]
      [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"]
      [out 'block-write [fmt "unsigned char {symbol-name}[] = "]]
      [out 'block-write "{"]
      [dotimes [i [buffer/length raw]]
               [when [zero? [rem i 32]]
                     [out 'block-write "\n"]]
               [out 'block-write [array/ref hex-cache [buffer/ref raw i]]]]
      [out 'block-write "0\n};\n"]
      [out 'close!]]

[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]
      [create-c-asset filename output-file symbol-name]]