How to process large binary data in Clojure?

a 夏天 提交于 2019-12-03 14:46:28

I would probably personally use aget / aset / areduce here - they may be imperative but they are useful tools when dealing with arrays, and I don't find them particularly ugly. If you want to wrap them in a nice function then of course you can :-)

If you are determined to use sequences, then your problem will be in the construction and traversal of the seq since this will require creation and storage of a new seq object for every byte in the array. This is probably ~24 bytes for each array byte......

So the trick is to get it to work lazily, in which case the earlier objects will be garbage collected before you get to the end of the the array. However to make this work, you'll have to avoid holding any reference to the head of the seq when you traverse the sequence (e.g. with count).

The following might work (untested), but will depend on write-bin-file being implemented in a lazy-friendly manner:

(defn remove-cr-from-file [file]
  (let [dirty-bytes (read-bin-file file)
        clean-bytes (filter #(not (= 13 %)) dirty-bytes)
        changed-bytes (count (filter #(not (= 13 %)) dirty-bytes))
        changed?    (< changed-bytes (alength dirty-bytes))]   
    (if changed?
      (write-bin-file file clean-bytes))))

Note this is essentially the same as your code, but constructs a separate lazy sequence to count the number of changed bytes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!