11cb0ef41Sopenharmony_ci// Run for enough iterations that we're likely to catch edge-cases, like
21cb0ef41Sopenharmony_ci// failing to set a reserved bit:
31cb0ef41Sopenharmony_ciconst iterations = 256;
41cb0ef41Sopenharmony_ci// Track all the UUIDs generated during test run, bail if we ever collide:
51cb0ef41Sopenharmony_ciconst uuids = new Set()
61cb0ef41Sopenharmony_cifunction randomUUID() {
71cb0ef41Sopenharmony_ci    const uuid = self.crypto.randomUUID();
81cb0ef41Sopenharmony_ci    if (uuids.has(uuid)) {
91cb0ef41Sopenharmony_ci        throw new Error(`uuid collision ${uuid}`)
101cb0ef41Sopenharmony_ci    }
111cb0ef41Sopenharmony_ci    uuids.add(uuid);
121cb0ef41Sopenharmony_ci    return uuid;
131cb0ef41Sopenharmony_ci}
141cb0ef41Sopenharmony_ci
151cb0ef41Sopenharmony_ci// UUID is in namespace format (16 bytes separated by dashes):
161cb0ef41Sopenharmony_citest(function() {
171cb0ef41Sopenharmony_ci    const UUIDRegex = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/
181cb0ef41Sopenharmony_ci    for (let i = 0; i < iterations; i++) {
191cb0ef41Sopenharmony_ci        assert_true(UUIDRegex.test(randomUUID()));
201cb0ef41Sopenharmony_ci    }
211cb0ef41Sopenharmony_ci}, "namespace format");
221cb0ef41Sopenharmony_ci
231cb0ef41Sopenharmony_ci// Set the 4 most significant bits of array[6], which represent the UUID
241cb0ef41Sopenharmony_ci// version, to 0b0100:
251cb0ef41Sopenharmony_citest(function() {
261cb0ef41Sopenharmony_ci    for (let i = 0; i < iterations; i++) {
271cb0ef41Sopenharmony_ci        let value = parseInt(randomUUID().split('-')[2].slice(0, 2), 16);
281cb0ef41Sopenharmony_ci        value &= 0b11110000;
291cb0ef41Sopenharmony_ci        assert_true(value === 0b01000000);
301cb0ef41Sopenharmony_ci    }
311cb0ef41Sopenharmony_ci}, "version set");
321cb0ef41Sopenharmony_ci
331cb0ef41Sopenharmony_ci// Set the 2 most significant bits of array[8], which represent the UUID
341cb0ef41Sopenharmony_ci// variant, to 0b10:
351cb0ef41Sopenharmony_citest(function() {
361cb0ef41Sopenharmony_ci    for (let i = 0; i < iterations; i++) {
371cb0ef41Sopenharmony_ci        // Grab the byte representing array[8]:
381cb0ef41Sopenharmony_ci        let value = parseInt(randomUUID().split('-')[3].slice(0, 2), 16);
391cb0ef41Sopenharmony_ci        value &= 0b11000000
401cb0ef41Sopenharmony_ci        assert_true(value === 0b10000000);
411cb0ef41Sopenharmony_ci    }
421cb0ef41Sopenharmony_ci}, "variant set");
43