Mercurial > lasercutter
diff src/clojure/contrib/test_contrib/pprint/examples/hexdump.clj @ 10:ef7dbbd6452c
added clojure source goodness
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sat, 21 Aug 2010 06:25:44 -0400 |
parents | |
children |
line wrap: on
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/clojure/contrib/test_contrib/pprint/examples/hexdump.clj Sat Aug 21 06:25:44 2010 -0400 1.3 @@ -0,0 +1,63 @@ 1.4 +;;; hexdump.clj -- part of the pretty printer for Clojure 1.5 + 1.6 +;; by Tom Faulhaber 1.7 +;; April 3, 2009 1.8 + 1.9 +; Copyright (c) Tom Faulhaber, Dec 2008. All rights reserved. 1.10 +; The use and distribution terms for this software are covered by the 1.11 +; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) 1.12 +; which can be found in the file epl-v10.html at the root of this distribution. 1.13 +; By using this software in any fashion, you are agreeing to be bound by 1.14 +; the terms of this license. 1.15 +; You must not remove this notice, or any other, from this software. 1.16 + 1.17 +;; This example is a classic hexdump program written using cl-format. 1.18 + 1.19 +;; For some local color, it was written in Dulles Airport while waiting for a flight 1.20 +;; home to San Francisco. 1.21 + 1.22 +(ns clojure.contrib.pprint.examples.hexdump 1.23 + (:use clojure.contrib.pprint 1.24 + clojure.contrib.pprint.utilities) 1.25 + (:gen-class (:main true))) 1.26 + 1.27 +(def *buffer-length* 1024) 1.28 + 1.29 +(defn zip-array [base-offset arr] 1.30 + (let [grouped (partition 16 arr)] 1.31 + (first (map-passing-context 1.32 + (fn [line offset] 1.33 + [[offset 1.34 + (map #(if (neg? %) (+ % 256) %) line) 1.35 + (- 16 (count line)) 1.36 + (map #(if (<= 32 % 126) (char %) \.) line)] 1.37 + (+ 16 offset)]) 1.38 + base-offset grouped)))) 1.39 + 1.40 + 1.41 +(defn hexdump 1.42 + ([in-stream] (hexdump in-stream true 0)) 1.43 + ([in-stream out-stream] (hexdump [in-stream out-stream 0])) 1.44 + ([in-stream out-stream offset] 1.45 + (let [buf (make-array Byte/TYPE *buffer-length*)] 1.46 + (loop [offset offset 1.47 + count (.read in-stream buf)] 1.48 + (if (neg? count) 1.49 + nil 1.50 + (let [bytes (take count buf) 1.51 + zipped (zip-array offset bytes)] 1.52 + (cl-format out-stream 1.53 + "~:{~8,'0X: ~2{~8@{~#[ ~:;~2,'0X ~]~} ~}~v@{ ~}~2{~8@{~A~} ~}~%~}" 1.54 + zipped) 1.55 + (recur (+ offset *buffer-length*) (.read in-stream buf)))))))) 1.56 + 1.57 +(defn hexdump-file 1.58 + ([file-name] (hexdump-file file-name true)) 1.59 + ([file-name stream] 1.60 + (with-open [s (java.io.FileInputStream. file-name)] 1.61 + (hexdump s)))) 1.62 + 1.63 +;; I don't quite understand how to invoke main funcs w/o AOT yet 1.64 +(defn -main [& args] 1.65 + (hexdump-file (first args))) 1.66 +