qxLib
string_pool.h
Go to the documentation of this file.
1 /**
2 
3  @file string_pool.h
4  @author Khrapov
5  @date 17.01.2026
6  @copyright (c) Nick Khrapov, 2026. All right reserved.
7 
8 **/
9 #pragma once
10 
12 
13 #include <array>
14 #include <atomic>
15 #include <cstdint>
16 #include <limits>
17 #include <string>
18 #include <utility>
19 
20 namespace qx
21 {
22 
23 /**
24 
25  @class string_pool
26  @brief Fixed-size atomic string pool
27  @tparam nSize - pool size
28  @tparam bStringStartCapacity - start string capacity for each string
29  @author Khrapov
30  @date 18.01.2026
31 
32 **/
33 template<size_t nSize = 32, size_t bStringStartCapacity = 128>
35 {
36  static constexpr size_t bTotalBits = 64; // bits in u64
37  static constexpr size_t nBlocks = (nSize + bTotalBits - 1) / bTotalBits;
38 
39 public:
40  static constexpr int nFreeString = -1;
41 
42  struct item
43  {
44  string sValue;
45  int nIndex = nFreeString;
46  };
47 
48 public:
49  string_pool();
50 
51  /**
52  @brief Acquire a string from the pool.
53  @retval - If a free slot exists, returns it (moved) and its index,
54  otherwise returns a fresh string with nIndex = nFreeString.
55  **/
56  item acquire();
57 
58  /**
59  @brief Return a string back to the pool.
60  @param item - an item object to release.
61  If nIndex == nFreeString, it is ignored. A string that isn't from this pool is acceptable.
62  **/
63  void release(item item);
64 
65 private:
66  /**
67  @brief Count trailing zeros for a non-zero 64-bit value
68  @param nBit - 64-bit value
69  @retval - number of trailing zeros
70  **/
71  static int ctz64(u64 nBit) noexcept;
72 
73  /**
74  @brief Prepare a string for pooling
75  @param string - a string
76  **/
77  static void normalize(string& string);
78 
79 private:
80  std::array<string, nSize> m_Storage;
81 
82  // 1 = free, 0 = in use
83  std::array<std::atomic<u64>, nBlocks> m_FreeMask;
84 };
85 
86 } // namespace qx
87 
Fixed-size atomic string pool.
Definition: string_pool.h:35
item acquire()
Acquire a string from the pool.
Definition: string_pool.inl:33
void release(item item)
Return a string back to the pool.
Definition: string_pool.inl:58
std::uint64_t u64
Definition: typedefs.h:26