nanoid.cr

Codacy Badge Crystal CI GitHub release Docs License

Crystal implementation of original NanoID

Installation

Add this to your application's shard.yml:

dependencies:
  nanoid:
    github: mamantoha/nanoid.cr

Usage

require "nanoid"

Nanoid.generate uses URL-friendly symbols (A-Za-z0-9_-) and returns an ID with 21 characters.

Nanoid.generate
# => 3gFI8yZxcfXsXGhB0036l

If you want to reduce ID length (and increase collisions probability), you can pass the length as an argument.

Nanoid.generate(size: 8, alphabet: "1234567890abcdef")
# => 86984b57

Non-secure API is also available.

Nanoid.generate(secure: false)
# => no0MmiInNcBm9jR2_3sGt

Nanoid.generate(size: 10, alphabet: "1234567890abcdef", secure: false)
# => 2793b2351c

Benchmark

crystal run --release bench/benchmark.cr

Crystal 1.6.0-dev [8cb915f95] (2022-08-01)

LLVM: 10.0.0
Default target: x86_64-unknown-linux-gnu

 Nanoid.simple_generate(21)   2.81  (355.35ms) (± 1.22%)  76.3MB/op        fastest
Nanoid.complex_generate(21)   1.58  (633.44ms) (± 3.91%)  91.7MB/op   1.78× slower
                    UUID v4   2.44  (409.74ms) (± 1.61%)   168MB/op   1.15× slower
 Nanoid.simple_generate(36)   1.88  (530.88ms) (± 1.62%)  107MB/op   1.25× slower
Nanoid.complex_generate(36)   1.27  (785.09ms) (± 6.24%)  122MB/op   1.84× slower
                    UUID v4   2.35  (425.85ms) (± 4.11%)  168MB/op        fastest

Development

Clone this repository and install dependencies:

shards install

Run tests:

crystal spec

Contributing

  1. Fork it (https://github.com/mamantoha/nanoid.cr/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors

License

Copyright: 2018-2022 Anton Maminov ([email protected])

This library is distributed under the MIT license. Please see the LICENSE file.