|
| 1 | + |
| 2 | +// Copyright 2022-2024 Herb Sutter |
| 3 | +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 4 | +// |
| 5 | +// Part of the Cppfront Project, under the Apache License v2.0 with LLVM Exceptions. |
| 6 | +// See https://github.com/hsutter/cppfront/blob/main/LICENSE for license information. |
| 7 | + |
| 8 | +#ifndef CPP2_EXPERIMENTAL_EXTRINSIC_STORAGE_STD_LOCKED_H |
| 9 | +#define CPP2_EXPERIMENTAL_EXTRINSIC_STORAGE_STD_LOCKED_H |
| 10 | + |
| 11 | +#include <map> |
| 12 | +#include <mutex> |
| 13 | +#include <string> |
| 14 | +#include <unordered_map> |
| 15 | + |
| 16 | + |
| 17 | +//----------------------------------------------------------------------------------- |
| 18 | +// Some helpers |
| 19 | +// |
| 20 | +auto print(std::integral auto val) -> std::string { |
| 21 | + auto ret = std::to_string(val % 10); |
| 22 | + auto pos = 0; |
| 23 | + while ((val /= 10) > 0) { |
| 24 | + if ((++pos % 3) == 0) { ret = ',' + ret; } |
| 25 | + ret = std::to_string(val % 10) + ret; |
| 26 | + } |
| 27 | + return ret; |
| 28 | +} |
| 29 | + |
| 30 | + |
| 31 | +//----------------------------------------------------------------------------------- |
| 32 | +// A "brute-force" locked implementation to measure against |
| 33 | +// |
| 34 | +// NOTE: For performance comparison only, not recommended |
| 35 | +// |
| 36 | +template <typename Data> |
| 37 | +class extrinsic_storage { |
| 38 | + std::mutex mut; |
| 39 | + //std::map<void*,Data> data; |
| 40 | + std::unordered_map<void*,Data> data; |
| 41 | +public: |
| 42 | + //-------------------------------------------------------------------------- |
| 43 | + // find_or_insert( pobj ) - returns the data entry for pobj |
| 44 | + // |
| 45 | + // If pobj does not yet have an entry, creates it |
| 46 | + // |
| 47 | + auto find_or_insert(void* pobj) -> Data* { |
| 48 | + auto _ = std::lock_guard{mut}; |
| 49 | + return &data[pobj]; |
| 50 | + } |
| 51 | + |
| 52 | + //-------------------------------------------------------------------------- |
| 53 | + // find( pobj ) - returns the data entry for pobj or null if not present |
| 54 | + // |
| 55 | + auto find(void* pobj) noexcept -> Data* { |
| 56 | + auto _ = std::lock_guard{mut}; |
| 57 | + if (auto iter = data.find(pobj); |
| 58 | + iter != data.end() |
| 59 | + ) |
| 60 | + { |
| 61 | + return &iter->second; |
| 62 | + } |
| 63 | + // Else |
| 64 | + return nullptr; |
| 65 | + } |
| 66 | + |
| 67 | + //-------------------------------------------------------------------------- |
| 68 | + // erase( pobj ) - removes the entry for pobj |
| 69 | + // |
| 70 | + auto erase(void* pobj) noexcept -> void { |
| 71 | + auto _ = std::lock_guard{mut}; |
| 72 | + data.erase(pobj); |
| 73 | + } |
| 74 | +}; |
| 75 | + |
| 76 | +#endif |
0 commit comments