缩写 UUID

Abbreviating a UUID

当我们只知道目标的 ID 时,什么是缩写 UUID 以用于用户界面按钮的好方法?

GitHub 似乎通过从头开始使用 7 个字符来缩写提交 ID。例如 b1310ce6bc3cc932ce5cdbe552712b5a3bdcb9e5 在按钮中显示为 b1310ce。虽然这个较短的版本并不完美,但足以在显示它的上下文中看起来很独特。我正在寻找适用于 UUID 的类似解决方案。我想知道 UUID 的某些部分是否比其他部分更随机。

最直接的选择是在破折号处拆分并使用第一部分。 UUID 42e9992a-8324-471d-b7f3-109f6c7df99d 将缩写为 42e9992a。我能想出的所有解决方案似乎都同样武断。也许有一些我没有想到的开箱即用的用户界面设计解决方案。

问题是您是要显示部分 UUID 还是只确保唯一字符串显示为较短的唯一字符串。如果您想关注后者,这似乎是您在开头段落中建议的目标:

(...) While not perfect this shorter version is sufficient to look unique in the context where it is displayed. (...)

您可以使用哈希。

Hashing:

Hashing is the transformation of a string of characters into a usually shorter fixed-length value or key that represents the original string. Hashing is used to index and retrieve items in a database because it is faster to find the item using the shorter hashed key than to find it using the original value.

散列在许多流行语言中非常普遍且易于使用; Python 中的简单方法:

import hashlib
import uuid
encoded_str = uuid.UUID('42e9992a-8324-471d-b7f3-109f6c7df99d').bytes
hash_uuid = hashlib.sha1(encoded_str).hexdigest()
hash_uuid[:10]
'b6e2a1c885'

不出所料,字符串中的微小变化将导致不同的字符串正确显示唯一性。

# Second digit is replaced with 3, rest of the string remains untouched 
encoded_str_two = uuid.UUID('43e9992a-8324-471d-b7f3-109f6c7df99d').bytes
hash_uuid_two = hashlib.sha1(encoded_str_two).hexdigest()
hash_uuid_two[:10]
'406ec3f5ae'

考虑了一段时间后,我意识到短 git 提交哈希被用作命令行命令的一部分。由于 UUID 和图形用户界面不存在此要求,我只是决定使用省略号作为缩写。像这样42e9992...

UUID的熵在UUID V1和V2的前几位最高,在V3、V4和V5均匀分布。因此,前 N 个字符并不比任何其他 N 个字符子集差。

对于 N=8,即第一个破折号之前的组,您可以在单个 GUI 屏幕中合理显示的列表中发生冲突的几率微乎其微。