Login
7 branches 0 tags
Benjamin Vincent Schulenburg Better [describe] de1f562 3 years ago 899 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 [raw out symbol-name]
      :export
      [typecheck/only out :lambda]
      [typecheck/only symbol-name :string]

      [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"]
      [return #nil]
      [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]]

[deftest 2223115721 [import [hash] :crypto/adler32] [hash [compiler/c-asset-packer/create-string-asset "asd" "test"]]]
[deftest 48 [buffer/length [compiler/c-asset-packer/create-string-asset "asd" "test"]]]
[deftest 104 [buffer/length [compiler/c-asset-packer/create-string-asset "j32093f3223f" "secret"]]]
[deftest 477043405 [import [hash] :crypto/adler32] [hash [compiler/c-asset-packer/create-string-asset "j32093f3223f" "secret"]]]