cache.h 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. /*****************************************************************************
  2. Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are
  6. met:
  7. * Redistributions of source code must retain the above
  8. copyright notice, this list of conditions and the
  9. following disclaimer.
  10. * Redistributions in binary form must reproduce the
  11. above copyright notice, this list of conditions
  12. and the following disclaimer in the documentation
  13. and/or other materials provided with the distribution.
  14. * Neither the name of the University of Illinois
  15. nor the names of its contributors may be used to
  16. endorse or promote products derived from this
  17. software without specific prior written permission.
  18. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  19. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  20. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  21. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  22. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  23. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  24. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  25. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  26. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  27. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  28. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. *****************************************************************************/
  30. /*****************************************************************************
  31. written by
  32. Yunhong Gu, last updated 01/27/2011
  33. *****************************************************************************/
  34. #ifndef INC_SRT_CACHE_H
  35. #define INC_SRT_CACHE_H
  36. #include <list>
  37. #include <vector>
  38. #include "sync.h"
  39. #include "netinet_any.h"
  40. #include "udt.h"
  41. namespace srt
  42. {
  43. class CCacheItem
  44. {
  45. public:
  46. virtual ~CCacheItem() {}
  47. public:
  48. virtual CCacheItem& operator=(const CCacheItem&) = 0;
  49. // The "==" operator SHOULD only compare key values.
  50. virtual bool operator==(const CCacheItem&) = 0;
  51. /// get a deep copy clone of the current item
  52. /// @return Pointer to the new item, or NULL if failed.
  53. virtual CCacheItem* clone() = 0;
  54. /// get a random key value between 0 and MAX_INT to be used for the hash in cache
  55. /// @return A random hash key.
  56. virtual int getKey() = 0;
  57. // If there is any shared resources between the cache item and its clone,
  58. // the shared resource should be released by this function.
  59. virtual void release() {}
  60. };
  61. template<typename T> class CCache
  62. {
  63. public:
  64. CCache(int size = 1024):
  65. m_iMaxSize(size),
  66. m_iHashSize(size * 3),
  67. m_iCurrSize(0)
  68. {
  69. m_vHashPtr.resize(m_iHashSize);
  70. // Exception: -> CUDTUnited ctor
  71. srt::sync::setupMutex(m_Lock, "Cache");
  72. }
  73. ~CCache()
  74. {
  75. clear();
  76. }
  77. public:
  78. /// find the matching item in the cache.
  79. /// @param [in,out] data storage for the retrieved item; initially it must carry the key information
  80. /// @return 0 if found a match, otherwise -1.
  81. int lookup(T* data)
  82. {
  83. srt::sync::ScopedLock cacheguard(m_Lock);
  84. int key = data->getKey();
  85. if (key < 0)
  86. return -1;
  87. if (key >= m_iMaxSize)
  88. key %= m_iHashSize;
  89. const ItemPtrList& item_list = m_vHashPtr[key];
  90. for (typename ItemPtrList::const_iterator i = item_list.begin(); i != item_list.end(); ++ i)
  91. {
  92. if (*data == ***i)
  93. {
  94. // copy the cached info
  95. *data = ***i;
  96. return 0;
  97. }
  98. }
  99. return -1;
  100. }
  101. /// update an item in the cache, or insert one if it doesn't exist; oldest item may be removed
  102. /// @param [in] data the new item to updated/inserted to the cache
  103. /// @return 0 if success, otherwise -1.
  104. int update(T* data)
  105. {
  106. srt::sync::ScopedLock cacheguard(m_Lock);
  107. int key = data->getKey();
  108. if (key < 0)
  109. return -1;
  110. if (key >= m_iMaxSize)
  111. key %= m_iHashSize;
  112. T* curr = NULL;
  113. ItemPtrList& item_list = m_vHashPtr[key];
  114. for (typename ItemPtrList::iterator i = item_list.begin(); i != item_list.end(); ++ i)
  115. {
  116. if (*data == ***i)
  117. {
  118. // update the existing entry with the new value
  119. ***i = *data;
  120. curr = **i;
  121. // remove the current entry
  122. m_StorageList.erase(*i);
  123. item_list.erase(i);
  124. // re-insert to the front
  125. m_StorageList.push_front(curr);
  126. item_list.push_front(m_StorageList.begin());
  127. return 0;
  128. }
  129. }
  130. // create new entry and insert to front
  131. curr = data->clone();
  132. m_StorageList.push_front(curr);
  133. item_list.push_front(m_StorageList.begin());
  134. ++ m_iCurrSize;
  135. if (m_iCurrSize >= m_iMaxSize)
  136. {
  137. // Cache overflow, remove oldest entry.
  138. T* last_data = m_StorageList.back();
  139. int last_key = last_data->getKey() % m_iHashSize;
  140. ItemPtrList& last_item_list = m_vHashPtr[last_key];
  141. for (typename ItemPtrList::iterator i = last_item_list.begin(); i != last_item_list.end(); ++ i)
  142. {
  143. if (*last_data == ***i)
  144. {
  145. last_item_list.erase(i);
  146. break;
  147. }
  148. }
  149. last_data->release();
  150. delete last_data;
  151. m_StorageList.pop_back();
  152. -- m_iCurrSize;
  153. }
  154. return 0;
  155. }
  156. /// Specify the cache size (i.e., max number of items).
  157. /// @param [in] size max cache size.
  158. void setSizeLimit(int size)
  159. {
  160. m_iMaxSize = size;
  161. m_iHashSize = size * 3;
  162. m_vHashPtr.resize(m_iHashSize);
  163. }
  164. /// Clear all entries in the cache, restore to initialization state.
  165. void clear()
  166. {
  167. for (typename std::list<T*>::iterator i = m_StorageList.begin(); i != m_StorageList.end(); ++ i)
  168. {
  169. (*i)->release();
  170. delete *i;
  171. }
  172. m_StorageList.clear();
  173. for (typename std::vector<ItemPtrList>::iterator i = m_vHashPtr.begin(); i != m_vHashPtr.end(); ++ i)
  174. i->clear();
  175. m_iCurrSize = 0;
  176. }
  177. private:
  178. std::list<T*> m_StorageList;
  179. typedef typename std::list<T*>::iterator ItemPtr;
  180. typedef std::list<ItemPtr> ItemPtrList;
  181. std::vector<ItemPtrList> m_vHashPtr;
  182. int m_iMaxSize;
  183. int m_iHashSize;
  184. int m_iCurrSize;
  185. srt::sync::Mutex m_Lock;
  186. private:
  187. CCache(const CCache&);
  188. CCache& operator=(const CCache&);
  189. };
  190. class CInfoBlock
  191. {
  192. public:
  193. uint32_t m_piIP[4]; // IP address, machine read only, not human readable format.
  194. int m_iIPversion; // Address family: AF_INET or AF_INET6.
  195. uint64_t m_ullTimeStamp; // Last update time.
  196. int m_iSRTT; // Smoothed RTT.
  197. int m_iBandwidth; // Estimated link bandwidth.
  198. int m_iLossRate; // Average loss rate.
  199. int m_iReorderDistance; // Packet reordering distance.
  200. double m_dInterval; // Inter-packet time (Congestion Control).
  201. double m_dCWnd; // Congestion window size (Congestion Control).
  202. public:
  203. CInfoBlock() {} // NOTE: leaves uninitialized
  204. CInfoBlock& copyFrom(const CInfoBlock& obj);
  205. CInfoBlock(const CInfoBlock& src) { copyFrom(src); }
  206. CInfoBlock& operator=(const CInfoBlock& src) { return copyFrom(src); }
  207. bool operator==(const CInfoBlock& obj) const;
  208. CInfoBlock* clone();
  209. int getKey();
  210. void release() {}
  211. public:
  212. /// convert sockaddr structure to an integer array
  213. /// @param [in] addr network address
  214. /// @param [in] ver IP version
  215. /// @param [out] ip the result machine readable IP address in integer array
  216. static void convert(const sockaddr_any& addr, uint32_t ip[4]);
  217. };
  218. } // namespace srt
  219. #endif