u/limited_unique_id: Add process unique id generator

This commit is contained in:
Jakob Bornecrantz 2023-09-18 12:28:19 +01:00
parent 22770320f2
commit f27cb14669
3 changed files with 68 additions and 0 deletions

View file

@ -59,6 +59,8 @@ add_library(
u_json.c
u_json.h
u_json.hpp
u_limited_unique_id.cpp
u_limited_unique_id.h
u_logging.c
u_logging.h
u_metrics.c

View file

@ -0,0 +1,26 @@
// Copyright 2023, Collabora, Ltd.
// SPDX-License-Identifier: BSL-1.0
/*!
* @file
* @brief A very simple generator to create process unique ids.
* @author Jakob Bornecrantz <jakob@collabora.com>
* @ingroup aux_util
*/
#include "u_limited_unique_id.h"
#include <atomic>
/*
* This code is in C++ and not C because MSVC doesn't implement C atomics yet,
* but to make things even more fun the C++11 standard defines atomic_uint64_t
* as optional, but atomic_uint_fast64_t is listed as required, so here we are.
*/
static std::atomic_uint_fast64_t generator;
extern "C" xrt_limited_unique_id_t
u_limited_unique_id_get(void)
{
return xrt_limited_unique_id_t{static_cast<uint64_t>(++generator)};
}

View file

@ -0,0 +1,40 @@
// Copyright 2023, Collabora, Ltd.
// SPDX-License-Identifier: BSL-1.0
/*!
* @file
* @brief A very simple generator to create process unique ids.
* @author Jakob Bornecrantz <jakob@collabora.com>
* @ingroup aux_util
*/
#pragma once
#include "xrt/xrt_defines.h"
#ifdef __cplusplus
extern "C" {
#endif
/*!
* This function returns a unsigned 64 bit value that is guaranteed to be unique
* within the current running process, and not zero. There is of course the
* limit of running out of those ID once all values has been returned, but the
* value is 64 bit so that should not be a practical limit. The value is useful
* when needing to implement caching of a complex object, this lets us not use
* memory addresses as keys which may be reused by underlying alloc
* implementation and could lead to false hits.
*
* The current implementation is naive and is a simple monotonic counter.
*
* @ingroup aux_util
*/
xrt_limited_unique_id_t
u_limited_unique_id_get(void);
#ifdef __cplusplus
}
#endif