Skip to content
Bill La Forge edited this page Oct 29, 2015 · 9 revisions

Adleer32 is usually good enough as a file checksum, but when it is not there are alternatives. A 256-bit checksum is often prefered as it is faster to calculate than the usual polynomial checksums and offers a high assurance that no corruption has occurred. AATree has 3 functions which support 256-bit checksums:

  • (aatree.nodes.cs256 ByteBuffer) calculates the 32-byte checksum from the contents of a ByteBuffer and returns it in the form of a BitSet.
  • (aatree.nodes.put-cs256 ByteBuffer BitSet) Puts the 32-bytes of the checksum in the ByteBuffer.
  • (aatree.nodes.get-cs256 ByteBuffer) Gets 32 bytes from a ByteBuffer and returns it in the form of a BitSet.
(ns aatree.cs256-example
  (:require [aatree.core :refer :all]
            [aatree.nodes :refer :all])
  (:import (java.nio ByteBuffer)
           (java.io File)))

(set! *warn-on-reflection* true)

(def opts (lazy-opts))
(def empty-set (new-sorted-set opts))

(let [ls1 (conj empty-set :dog :cat :rabbit)
      bb-len (+ (byte-length ls1) 32)
      ^ByteBuffer bb (ByteBuffer/allocate bb-len)
      _ (put-aa bb ls1)
      ^ByteBuffer csbb (.flip (.duplicate bb))
      cs (compute-cs256 csbb)]
  (put-cs256 bb cs)
  (.flip bb)
  (file-save bb (File. "cs245-example.lazy")))

(let [^ByteBuffer bb (file-load (File. "cs245-example.lazy"))
      csp (- (.limit bb) 32)
      ^ByteBuffer csbb (.limit (.duplicate bb) csp)
      cs (compute-cs256 csbb)
      ocs (get-cs256 (.position (.duplicate bb) csp))
      lv2 (if (= cs ocs)
            (load-sorted-set bb opts)
            (throw (java.lang.Exception. "Checksum does not match")))]
  (println lv2)); -> #{:cat :dog :rabbit}
Clone this wiki locally