aboutsummaryrefslogtreecommitdiff
path: root/core/encoding/uuid/generation.odin
blob: b210f6a52b91b35cdb91223b12b54992a694b083 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package uuid

import "base:runtime"
import "core:crypto/hash"
import "core:math/rand"
import "core:time"

/*
Generate a version 1 UUID.

Inputs:
- clock_seq: The clock sequence, a number which must be initialized to a random number once in the lifetime of a system.
- node: An optional 48-bit spatially unique identifier, specified to be the IEEE 802 address of the system.
  If one is not provided or available, 48 bits of random state will take its place.
- timestamp: A timestamp from the `core:time` package, or `nil` to use the current time.

Returns:
- result: The generated UUID.
*/
generate_v1 :: proc(clock_seq: u16, node: Maybe([6]u8) = nil, timestamp: Maybe(time.Time) = nil) -> (result: Identifier) {
	assert(clock_seq <= 0x3FFF, BIG_CLOCK_ERROR)
	unix_time_in_hns_intervals := time.to_unix_nanoseconds(timestamp.? or_else time.now()) / 100

	uuid_timestamp := cast(u64le)(HNS_INTERVALS_BETWEEN_GREG_AND_UNIX + unix_time_in_hns_intervals)
	uuid_timestamp_octets := transmute([8]u8)uuid_timestamp

	result[0] = uuid_timestamp_octets[0]
	result[1] = uuid_timestamp_octets[1]
	result[2] = uuid_timestamp_octets[2]
	result[3] = uuid_timestamp_octets[3]
	result[4] = uuid_timestamp_octets[4]
	result[5] = uuid_timestamp_octets[5]

	result[6] = uuid_timestamp_octets[6] >> 4
	result[7] = uuid_timestamp_octets[6] << 4 | uuid_timestamp_octets[7]

	if realized_node, ok := node.?; ok {
		mutable_node := realized_node
		runtime.mem_copy_non_overlapping(&result[10], &mutable_node[0], 6)
	} else {
		assert(.Cryptographic in runtime.random_generator_query_info(context.random_generator), NO_CSPRNG_ERROR)
		bytes_generated := rand.read(result[10:])
		assert(bytes_generated == 6, "RNG failed to generate 6 bytes for UUID v1.")
	}

	result[VERSION_BYTE_INDEX] |= 0x10
	result[VARIANT_BYTE_INDEX] |= 0x80

	result[8] |= cast(u8)(clock_seq & 0x3F00 >> 8)
	result[9]  = cast(u8)clock_seq

	return
}

/*
Generate a version 4 UUID.

This UUID will be pseudorandom, save for 6 pre-determined version and variant bits.

Returns:
- result: The generated UUID.
*/
generate_v4 :: proc() -> (result: Identifier) {
	assert(.Cryptographic in runtime.random_generator_query_info(context.random_generator), NO_CSPRNG_ERROR)
	bytes_generated := rand.read(result[:])
	assert(bytes_generated == 16, "RNG failed to generate 16 bytes for UUID v4.")

	result[VERSION_BYTE_INDEX] &= 0x0F
	result[VERSION_BYTE_INDEX] |= 0x40

	result[VARIANT_BYTE_INDEX] &= 0x3F
	result[VARIANT_BYTE_INDEX] |= 0x80

	return
}

/*
Generate a version 6 UUID.

Inputs:
- clock_seq: The clock sequence from version 1, now made optional.
  If unspecified, it will be replaced with random bits.
- node: An optional 48-bit spatially unique identifier, specified to be the IEEE 802 address of the system.
  If one is not provided or available, 48 bits of random state will take its place.
- timestamp: A timestamp from the `core:time` package, or `nil` to use the current time.

Returns:
- result: The generated UUID.
*/
generate_v6 :: proc(clock_seq: Maybe(u16) = nil, node: Maybe([6]u8) = nil, timestamp: Maybe(time.Time) = nil) -> (result: Identifier) {
	unix_time_in_hns_intervals := time.to_unix_nanoseconds(timestamp.? or_else time.now()) / 100

	uuid_timestamp := cast(u128be)(HNS_INTERVALS_BETWEEN_GREG_AND_UNIX + unix_time_in_hns_intervals)

	result = transmute(Identifier)(
		uuid_timestamp & 0x0FFFFFFF_FFFFF000 << 68 |
		uuid_timestamp & 0x00000000_00000FFF << 64
	)

	if realized_clock_seq, ok := clock_seq.?; ok {
		assert(realized_clock_seq <= 0x3FFF, BIG_CLOCK_ERROR)
		result[8] |= cast(u8)(realized_clock_seq & 0x3F00 >> 8)
		result[9]  = cast(u8)realized_clock_seq
	} else {
		assert(.Cryptographic in runtime.random_generator_query_info(context.random_generator), NO_CSPRNG_ERROR)
		temporary: [2]u8
		bytes_generated := rand.read(temporary[:])
		assert(bytes_generated == 2, "RNG failed to generate 2 bytes for UUID v1.")
		result[8] |= temporary[0] & 0x3F
		result[9]  = temporary[1]
	}

	if realized_node, ok := node.?; ok {
		mutable_node := realized_node
		runtime.mem_copy_non_overlapping(&result[10], &mutable_node[0], 6)
	} else {
		assert(.Cryptographic in runtime.random_generator_query_info(context.random_generator), NO_CSPRNG_ERROR)
		bytes_generated := rand.read(result[10:])
		assert(bytes_generated == 6, "RNG failed to generate 6 bytes for UUID v1.")
	}

	result[VERSION_BYTE_INDEX] |= 0x60
	result[VARIANT_BYTE_INDEX] |= 0x80

	return
}

/*
Generate a version 7 UUID.

This UUID will be pseudorandom, save for 6 pre-determined version and variant
bits and a 48-bit timestamp.

It is designed with time-based sorting in mind, such as for database usage, as
the highest bits are allocated from the timestamp of when it is created.

Inputs:
- timestamp: A timestamp from the `core:time` package, or `nil` to use the current time.

Returns:
- result: The generated UUID.
*/
generate_v7_basic :: proc(timestamp: Maybe(time.Time) = nil) -> (result: Identifier) {
	assert(.Cryptographic in runtime.random_generator_query_info(context.random_generator), NO_CSPRNG_ERROR)
	unix_time_in_milliseconds := time.to_unix_nanoseconds(timestamp.? or_else time.now()) / 1e6

	result = transmute(Identifier)(cast(u128be)unix_time_in_milliseconds << VERSION_7_TIME_SHIFT)

	bytes_generated := rand.read(result[6:])
	assert(bytes_generated == 10, "RNG failed to generate 10 bytes for UUID v7.")

	result[VERSION_BYTE_INDEX] &= 0x0F
	result[VERSION_BYTE_INDEX] |= 0x70

	result[VARIANT_BYTE_INDEX] &= 0x3F
	result[VARIANT_BYTE_INDEX] |= 0x80

	return
}

/*
Generate a version 7 UUID that has an incremented counter.

This UUID will be pseudorandom, save for 6 pre-determined version and variant
bits, a 48-bit timestamp, and 12 bits of counter state.

It is designed with time-based sorting in mind, such as for database usage, as
the highest bits are allocated from the timestamp of when it is created.

This procedure is preferable if you are generating hundreds or thousands of
UUIDs as a batch within the span of a millisecond. Do note that the counter
only has 12 bits of state, thus `counter` cannot exceed the number 4,095.

Example:

	import "core:uuid"

	// Create a batch of UUIDs all at once.
	batch: [dynamic]uuid.Identifier

	for i: u16 = 0; i < 1000; i += 1 {
		my_uuid := uuid.generate_v7_counter(i)
		append(&batch, my_uuid)
	}

Inputs:
- counter: A 12-bit value which should be incremented each time a UUID is generated in a batch.
- timestamp: A timestamp from the `core:time` package, or `nil` to use the current time.

Returns:
- result: The generated UUID.
*/
generate_v7_with_counter :: proc(counter: u16, timestamp: Maybe(time.Time) = nil) -> (result: Identifier) {
	assert(.Cryptographic in runtime.random_generator_query_info(context.random_generator), NO_CSPRNG_ERROR)
	assert(counter <= 0x0fff, VERSION_7_BIG_COUNTER_ERROR)
	unix_time_in_milliseconds := time.to_unix_nanoseconds(timestamp.? or_else time.now()) / 1e6

	result = transmute(Identifier)(
		cast(u128be)unix_time_in_milliseconds << VERSION_7_TIME_SHIFT |
		cast(u128be)counter << VERSION_7_COUNTER_SHIFT
	)

	bytes_generated := rand.read(result[8:])
	assert(bytes_generated == 8, "RNG failed to generate 8 bytes for UUID v7.")

	result[VERSION_BYTE_INDEX] &= 0x0F
	result[VERSION_BYTE_INDEX] |= 0x70

	result[VARIANT_BYTE_INDEX] &= 0x3F
	result[VARIANT_BYTE_INDEX] |= 0x80

	return
}

generate_v7 :: proc {
	generate_v7_basic,
	generate_v7_with_counter,
}

/*
Generate a version 8 UUID using a specific hashing algorithm.

This UUID is generated by hashing a name with a namespace.

Note that all version 8 UUIDs are for experimental or vendor-specific use
cases, per the specification. This use case in particular is for offering a
non-legacy alternative to UUID versions 3 and 5.

Inputs:
- namespace: An `Identifier` that is used to represent the underlying namespace.
  This can be any one of the `Namespace_*` values provided in this package.
- name: The byte slice which will be hashed with the namespace.
- algorithm: A hashing algorithm from `core:crypto/hash`.

Returns:
- result: The generated UUID.

Example:
	import "core:crypto/hash"
	import "core:encoding/uuid"
	import "core:fmt"

	generate_v8_hash_bytes_example :: proc() {
		my_uuid := uuid.generate_v8_hash(uuid.Namespace_DNS, "www.odin-lang.org", .SHA256)
		my_uuid_string := uuid.to_string(my_uuid, context.temp_allocator)
		fmt.println(my_uuid_string)
	}

Output:

	3730f688-4bff-8dce-9cbf-74a3960c5703

*/
generate_v8_hash_bytes :: proc(
	namespace: Identifier,
	name: []byte,
	algorithm: hash.Algorithm,
) -> (
	result: Identifier,
) {
	// 128 bytes should be enough for the foreseeable future.
	digest: [128]byte

	assert(hash.DIGEST_SIZES[algorithm] >= 16, "Per RFC 9562, the hashing algorithm used must generate a digest of 128 bits or larger.")
	assert(hash.DIGEST_SIZES[algorithm] < len(digest), "Digest size is too small for this algorithm. The buffer must be increased.")

	hash_context: hash.Context
	hash.init(&hash_context, algorithm)

	mutable_namespace := namespace
	hash.update(&hash_context, mutable_namespace[:])
	hash.update(&hash_context, name[:])
	hash.final(&hash_context, digest[:])

	runtime.mem_copy_non_overlapping(&result, &digest, 16)

	result[VERSION_BYTE_INDEX] &= 0x0F
	result[VERSION_BYTE_INDEX] |= 0x80

	result[VARIANT_BYTE_INDEX] &= 0x3F
	result[VARIANT_BYTE_INDEX] |= 0x80

	return
}

/*
Generate a version 8 UUID using a specific hashing algorithm.

This UUID is generated by hashing a name with a namespace.

Note that all version 8 UUIDs are for experimental or vendor-specific use
cases, per the specification. This use case in particular is for offering a
non-legacy alternative to UUID versions 3 and 5.

Inputs:
- namespace: An `Identifier` that is used to represent the underlying namespace.
  This can be any one of the `Namespace_*` values provided in this package.
- name: The string which will be hashed with the namespace.
- algorithm: A hashing algorithm from `core:crypto/hash`.

Returns:
- result: The generated UUID.

Example:
	import "core:crypto/hash"
	import "core:encoding/uuid"
	import "core:fmt"

	generate_v8_hash_string_example :: proc() {
		my_uuid := uuid.generate_v8_hash(uuid.Namespace_DNS, "www.odin-lang.org", .SHA256)
		my_uuid_string := uuid.to_string(my_uuid, context.temp_allocator)
		fmt.println(my_uuid_string)
	}

Output:

	3730f688-4bff-8dce-9cbf-74a3960c5703

*/
generate_v8_hash_string :: proc(
	namespace: Identifier,
	name: string,
	algorithm: hash.Algorithm,
) -> (
	result: Identifier,
) {
	return generate_v8_hash_bytes(namespace, transmute([]byte)name, algorithm)
}

generate_v8_hash :: proc {
	generate_v8_hash_bytes,
	generate_v8_hash_string,
}