~statianzo/janet-nanoid

8fe6865e0824ebd25d546d6f6b4468105006aed8 — Jason Staten 4 years ago b4a8a3c
non-secure variant
3 files changed, 38 insertions(+), 1 deletions(-)

M nanoid.janet
A test/gen-non-secure.janet
R test/{nanoid.janet => gen.janet}
M nanoid.janet => nanoid.janet +15 -0
@@ 1,5 1,7 @@
(def- DEFAULT_ALPHABET "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

(def- DEFAULT_RNG (math/rng (os/time)))

(def- masks [15 31 63 127 255])

(defn gen [&keys {:size size


@@ 20,3 22,16 @@
              char (get alphabet mask-byte)]
          (if char (array/push result char)))))
    (string/from-bytes ;result)))


(defn gen-non-secure [&keys {:size size
                             :alphabet alphabet
                             :rng rng}]
  (default size 21)
  (default alphabet DEFAULT_ALPHABET)
  (default rng DEFAULT_RNG)


  (string/from-bytes
    ;(seq [i :range [0 size]]
       (get alphabet (math/rng-int rng (length alphabet))))))

A test/gen-non-secure.janet => test/gen-non-secure.janet +23 -0
@@ 0,0 1,23 @@
(import ../nanoid :as n)

(loop [x :range [0 100]]
  (assert
    (= 21 (length (n/gen-non-secure)))
    "generates id of length 21"))

(loop [x :range [0 100]]
  (assert
    (= 10 (length (n/gen-non-secure :size 10)))
    "generates id of length 10"))

(let [results (table)]
  (loop [x :range [0 10_000]]
    (let [id (n/gen-non-secure)]
      (assert (nil? (results id))
              (string/format "%q not unique" id))
      (put results id true))))

(assert
  (= "eXB2i0JMOYeczrdWVJiYC"
     (n/gen-non-secure :rng (math/rng 123)))
  "allows custom rng")

R test/nanoid.janet => test/gen.janet +0 -1
@@ 9,7 9,6 @@
  (assert
    (= 10 (length (n/gen :size 10)))
    "generates id of length 10"))
(pp (n/gen))

(let [results (table)]
  (loop [x :range [0 10_000]]