File
Blob: src/workerd/util/uuid.h
| 1 | // Copyright (c) 2017-2022 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | |
| 5 | #pragma once |
| 6 | |
| 7 | #include <kj/hash.h> |
| 8 | #include <kj/string.h> |
| 9 | |
| 10 | #include <cstdint> |
| 11 | |
| 12 | namespace kj { |
| 13 | class EntropySource; |
| 14 | } |
| 15 | |
| 16 | namespace workerd { |
| 17 | |
| 18 | // Generates a random version 4 UUID using the given entropy source or a default |
| 19 | // secure random number generator. Unless you pass in a predictable entropy |
| 20 | // source, it is safe to assume that the output of this function is unique. |
| 21 | kj::String randomUUID(kj::Maybe<kj::EntropySource&> optionalEntropySource); |
| 22 | |
| 23 | // A 128-bit universally unique identifier (UUID). |
| 24 | // |
| 25 | // A UUID can be created from and converted between between two formats: |
| 26 | // 1. Upper/lower format: an "upper" field representing the most significant bits and "lower" field |
| 27 | // representings the least significant bits. |
| 28 | // 2. Stringified 8-4-4-4-12 hex format. |
| 29 | // |
| 30 | // A "null UUID" (a UUID with a value of 0) is considered invalid and is not possible to create. |
| 31 | class UUID { |
| 32 | public: |
| 33 | // Create a UUID from upper and lower parts. If the UUID would be null, return kj::none. |
| 34 | // |
| 35 | // For example, creating a UUID from upper and lower values of 81985529216486895 and |
| 36 | // 81985529216486895 respectively yields a UUID which stringifies to |
| 37 | // "01234567-89ab-cdef-0123-456789abcdef". |
| 38 | static kj::Maybe<UUID> fromUpperLower(uint64_t upper, uint64_t lower); |
| 39 | |
| 40 | // Create a UUID from 8-4-4-4-12 hex format. If the provided string is not valid, or the UUID |
| 41 | // would be null, return kj::none. |
| 42 | static kj::Maybe<UUID> fromString(kj::StringPtr str); |
| 43 | |
| 44 | uint64_t getUpper() const { |
| 45 | return upper; |
| 46 | } |
| 47 | |
| 48 | uint64_t getLower() const { |
| 49 | return lower; |
| 50 | } |
| 51 | |
| 52 | // Stringify the UUID to 8-4-4-4-12 hex format. |
| 53 | // |
| 54 | // Note that this is NOT just a debugging API. Its behavior is relied upon to implement |
| 55 | // user-facing APIs. |
| 56 | kj::String toString() const; |
| 57 | |
| 58 | bool operator==(const UUID& other) const { |
| 59 | return upper == other.upper && lower == other.lower; |
| 60 | } |
| 61 | |
| 62 | size_t hashCode() const { |
| 63 | return kj::hashCode(upper, lower); |
| 64 | } |
| 65 | |
| 66 | private: |
| 67 | uint64_t upper; |
| 68 | uint64_t lower; |
| 69 | |
| 70 | UUID(uint64_t upper, uint64_t lower): upper(upper), lower(lower) {} |
| 71 | }; |
| 72 | |
| 73 | } // namespace workerd |