~statianzo/janet-hashids

7054cec371fd42209cb92b1083c0b66b858c5423 — Jason Staten 4 years ago 66c6d2b
consistent-shuffle on bytes
2 files changed, 31 insertions(+), 20 deletions(-)

M hashids.janet
M test/consistent-shuffle.janet
M hashids.janet => hashids.janet +19 -13
@@ 39,20 39,26 @@
(defn- intersection [s1 s2]
  (seq [x :in s1 y :in s2 :when (= x y)] x))

(defn consistent-shuffle [alphabet salt]
  (if (= "" salt) alphabet
      (let [alph-bytes (apply array (string/bytes alphabet))
            salt-bytes (string/bytes salt)
            max-index (- (length alph-bytes) 1)]
(defn balance [sep-bytes alph-bytes] 

[

]
) 

(defn consistent-shuffle [alph-bytes salt-bytes]
  (if (empty? salt-bytes) alph-bytes
      (let [alph-array (apply array alph-bytes)
            max-index (- (length alph-array) 1)]
        (var p 0)

        (loop [i :down [max-index 0]]
          (let [v (mod (- max-index i) (length salt-bytes))
                n (get salt-bytes v)
                j (mod (+ n v (set p (+ p n))) i)]
            (swap alph-bytes i j)))
            (swap alph-array i j)))

        (apply string/from-bytes alph-bytes))))
        alph-array)))

(defn setup [opts]
(let [{:salt salt


@@ 62,13 68,13 @@
      alph-bytes (string/bytes alphabet)
      salt-bytes (string/bytes salt)
      seps-bytes (string/bytes seps)
      unbalanced-alph (difference alph-bytes seps-bytes)
      unbalanced-seps (intersection alph-bytes seps-bytes)
      ]
(pp unbalanced-seps)
      alph-unbal (difference alph-bytes seps-bytes)
      seps-unbal (intersection alph-bytes seps-bytes)
      [seps-bal alph-bal] (balance (consistent-shuffle seps-unbal salt-bytes)
                                    alph-unbal)]
{
:seps (apply string/from-bytes unbalanced-seps)
:alph (apply string/from-bytes unbalanced-alph)
:seps (apply string/from-bytes seps-unbal)
:alph (apply string/from-bytes alph-unbal)
  :salt salt
  :min-length min-length
}))

M test/consistent-shuffle.janet => test/consistent-shuffle.janet +12 -7
@@ 1,23 1,28 @@
(import ../hashids :as h)

(assert
  (= "abc" (h/consistent-shuffle "abc" "")))
(defn string-shuffle [alph salt]
  (apply string/from-bytes
         (h/consistent-shuffle (string/bytes alph)
                               (string/bytes salt))))

(def salt "this is my salt")

(assert
  (= "ba" (h/consistent-shuffle "ab" salt)))
  (= "abc" (string-shuffle "abc" "")))

(assert
  (= "ba" (string-shuffle "ab" salt)))

(assert
  (= "bca" (h/consistent-shuffle "abc" salt)))
  (= "bca" (string-shuffle "abc" salt)))

(assert
  (= "cadb" (h/consistent-shuffle "abcd" salt)))
  (= "cadb" (string-shuffle "abcd" salt)))

(assert
  (= "f17a8zvCwo0iuqYDXlJ4RmAS2end5ghTcpjbOWLK9GFyE6xUI3ZBMQtPsNHrkV"
     (h/consistent-shuffle "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
                           "salt")))
     (string-shuffle "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
                     "salt")))