janet-lang / janet

A dynamic language and bytecode vm
https://janet-lang.org
MIT License
3.54k stars 228 forks source link

Add function to generate UUID v4 #1504

Closed katomuso closed 2 months ago

katomuso commented 2 months ago

I'd like to propose adding a function to generate UUID v4 in the standard library because they are frequently used in all kinds of systems and there is already os/cryptorand in the standard library, so implementation should be trivial.

This function could be placed in the os module, with possible names such as os/uuid, os/uuid4, os/uuidgen, os/random-uuid, or os/randuuid. Personally, I prefer the first three names, but the final decision is yours.

In Janet, a simple implementation using os/cryptorand looks like this:

(defn uuid4 []
  (def uuid @"")
  (def bytes (os/cryptorand 16))
  (update bytes 6 |(bor 2r01000000 (brshift $ 4)))
  (update bytes 8 |(bor 2r10000000 (brshift $ 2)))
  (each i (range 16)
    (when (or (= i 4) (= i 6) (= i 8) (= i 10))
      (buffer/push uuid "-"))
    (buffer/push uuid (string/format "%02x" (bytes i))))
  uuid)
sogaiu commented 2 months ago

I'm inclined to suggest addition to spork initially and if it's really seen to be useful, consider inclusion in janet itself later.

Please see this issue and this issue for some recent discussions regarding additions to janet.

katomuso commented 2 months ago

I'm inclined to suggest addition to spork initially and if it's really seen to be useful, consider inclusion in janet itself later.

Please see this issue and this issue for some recent discussions regarding additions to janet.

As far as I understand, the mentioned issues are related to design choices. Generating UUIDs is a pretty basic feature which is included by default in many scripting languages because, as I mentioned, they are frequently used in all kinds of systems.

It is not that hard to implement yourself, as I demonstrated, but can become cumbersome if you need to do this often, and probably this is not worth adding a dependency for.

So, considering how useful and easy to implement it is, I think it is worth adding to the standard library.

bakpakin commented 2 months ago

Definitely not adding this to the standard library. I don't know of many languages that add uuids to the standard libraries - there are plenty of ways to have random IDs that are not valid UUIDs and provide more information.

Also, arguably, the correct way to represents UUIDs in a program is not as a string but (os/cryptorand 16) with some bits masked off. Formatting to a string is something that is only done for display purposes as it wastes space.