/*
 * Copyright 2015 - 2025 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

#include <ox/std/uuid.hpp>

namespace ox {

bool UUID::s_seeded = false;
Random UUID::s_rand;

void UUID::seedGenerator(const RandomSeed &seed) noexcept {
	s_seeded = true;
	s_rand.seed(seed);
}

// UUID v4
Result<UUID> UUID::generate() noexcept {
	if (!s_seeded) {
		return ox::Error(1, "UUID generator not seeded.");
	}
	UUID out;
	for (auto &v : out.m_value) {
		// shift away 4 lowest bits, as Xoroshiro128+ randomness is weaker there
	 	const auto rand = s_rand.gen() >> 4;
		v = static_cast<uint8_t>(rand % 255);
	}
	out.m_value[6] &= 0x0f;
	out.m_value[6] |= 4 << 4;
	return out;
}

static_assert(UUID{}.isNull());
static_assert(!UUID::fromString("34af4809-043d-4348-b720-2b454e5678c7").value.isNull());

}
