Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UUID Version 6 を生成する

Posted at

UUID は Version が 1 から 5 までしかないので、タイトルはエラーとなります。しかしながら、なぜ存在しないはずの Version 6 を語らないといけないか、と述べますと「ソートできるUUID」を人類は求めているからです。例えば Ulid などが議論に挙がるというのは、それを裏付けることでありましょう。この記事ではその「あったらいいな」というもの、つまりはソートできる UUID を作っていくことにします。

サンプルコード

UUID_V1 = `uuidgen -t`.chomp

def uuid_v1_to_v6 v1
  uh = v1.split(/-/).join
  tlo1 = uh[...5]
  tlo2 = uh[5...8]
  tmid = uh[8...12]
  thig = uh[13...16]
  rest = uh[16..]

  thig + tmid + tlo1 + '6' + tlo2 + rest
end

p uuid_v1_to_v6(UUID_V1)

require 'test/unit'
class TC_Foo < Test::Unit::TestCase
  def test_v1_to_v6
    assert_equal uuid_v1_to_v6('adb17428-60e4-11ea-bc55-0242ac130003'), '1ea60e4adb176428bc550242ac130003'
    assert_equal uuid_v1_to_v6('0966a06e-60df-11ea-b5d2-7be3aea104a2'), '1ea60df0966a606eb5d27be3aea104a2'
  end

  def test_sortable
    assert uuid_v1_to_v6(UUID_V1) < uuid_v1_to_v6(`uuidgen -t`.chomp)
  end
end

↑では仰々しく書いたけど、UUID "Version 6" The version RFC 4122 forgot. という記事にあったコードを Ruby で書き直しただけです。つまりは、ただのパクリです。m(_ _)m

おわりに

正直に申せば、uuidgen というコマンドをうっているあたり「OSコマンドインジェクションとか考えてなさそう...」とか、「将来 Version 6 ができたた時にちゃんと動くのか?」という批判は甘んじます。まぁ「ソート可能な UUID みたいなもの」という条件はそろえているので、良しということにしといてください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?