Nanoid implementation in Zig
When I need a random ID, I commonly generate a UUID because the UUID specification is precise, and the specified algorithms supporting UUID are sound.
I realized that Nanoid was very popular among JavaScript aficionados. So, as a curiosity to understand the underlying algorithms, I decided to implement Nanoid in Zig, which I'm currently learning.
The code includes the nanoid implementation in file nanoid.zig
, and a command line main.zig
demonstrating how to use the library.
$ nanoid --help
Usage:
nanoid Generate a nanoid with the default size (21) and default alphabet
nanoid -s | --size <size> Generate a nanoid with a custom size and default alphabet
nanoid -a | --alphabet <alphabet> Generate a nanoid with a custom alphabet (requires the size)
nanoid -h | --help Display this help
nanoid -v | --version Print the version
Examples:
nanoid
nanoid -s 42
nanoid -s 42 -a 0123456789
$ nanoid
bnX1GLQViedU3axkMeFH1
$ nanoid --size 42
AO6gpj98L1J6bNKx-CCAbUjU060yoX8YtE6ntZNmZK
$ nanoid --size 42 --alphabet 0123456789
523818966093355749724259496656326495868533
The build uses a justfile
https://github.com/casey/just tested on Mac OS and Linux.
To build in debug mode:
$ just build
...
To build in release mode:
$ just release
...
$ just test
...
I did not find any concrete specs similar to the UUID specs and referred to some of the existing implementations.
- https://github.com/ai/nanoid (MIT License)
- https://github.com/matoous/go-nanoid (MIT License)
- https://github.com/puyuan/py-nanoid (MIT License)