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 © 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  @author Khrapov
29  @date 18.01.2026
30 
31 **/
32 template<size_t nSize = 32>
34 {
35  static constexpr size_t bTotalBits = 64; // bits in u64
36  static constexpr size_t nBlocks = (nSize + bTotalBits - 1) / bTotalBits;
37  static constexpr size_t bStringStartCapacity = 128;
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  @details If nIndex == nFreeString, it is ignored.
61  @param sValue - a string that does not necessarily have to be from this pool
62  @param nIndex - an index of previously acquired string
63  **/
64  void release(string sValue, int nIndex);
65 
66 private:
67  /**
68  @brief Count trailing zeros for a non-zero 64-bit value
69  @param nBit - 64-bit value
70  @retval - number of trailing zeros
71  **/
72  static int ctz64(u64 nBit) noexcept;
73 
74  /**
75  @brief Prepare a string for pooling
76  @param string - a string
77  **/
78  static void normalize(string& string);
79 
80 private:
81  std::array<string, nSize> m_Storage;
82 
83  // 1 = free, 0 = in use
84  std::array<std::atomic<u64>, nBlocks> m_FreeMask;
85 };
86 
87 } // namespace qx
88 
Fixed-size atomic string pool.
Definition: string_pool.h:34
item acquire()
Acquire a string from the pool.
Definition: string_pool.inl:33
void release(string sValue, int nIndex)
Return a string back to the pool.
Definition: string_pool.inl:58
std::uint64_t u64
Definition: typedefs.h:26