Cysharp / Ulid

Fast .NET C# Implementation of ULID for .NET and Unity.
MIT License
1.33k stars 57 forks source link

Add cast to and from GUID #7

Closed lynzrand closed 4 years ago

lynzrand commented 4 years ago

This pull request adds casts to and from GUID, as well as tests for them. The cast preserves ordering but not byte arrangement.

The added items are:

This cast is not the same as NUlid.ToGuid()!

Notes

According to Documentation on Guid type, comparison between Guids is done as the following:

To preserve ordering, we must encode the first 8 bytes as little-endian integers, thus changing the byte arrangement.

neuecc commented 4 years ago

Guid and Ulid is completely different structure. If Guid -> Ulid, Ulid's timestamp is completely random. I don't think it makes sense. But if conversion is needed, Unsafe.As <Guid, Ulid> (ref value) Will convert it.

lynzrand commented 4 years ago

My purpose of this pull request was that, as many database support storing Guid (uuid) data type as an int128 value, we can convert this Ulid value into Guid and use as database primary key, while also preserving order so we can still sort the database key according to time. The same thing applies to networking, etc. as Guid is more widely used and supported than Ulid.

Using a Guid as a Ulid is not my purpose.

neuecc commented 4 years ago

Thanks, I've understood. Surely it is useful. ToByteArray's allocation is not good so require to rewrite code, but this feature, I should add.

lynzrand commented 4 years ago

ToByteArray's allocation is not good so require to rewrite code

I was hesitant on that piece of code too. Should I assume the memory layout described in the current library code's code is true for every system and build upon that?

lynzrand commented 4 years ago

Made a version using stackalloc spans to avoid allocation, assuming all implementations use the same Guid memory layout as the current code.