CodeSizeCache.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. This file is part of cpp-ethereum.
  3. cpp-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. cpp-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /** @file CodeSizeCache.h
  15. * @date 2016
  16. */
  17. #pragma once
  18. #include <map>
  19. #include <libdevcore/FixedHash.h>
  20. #include <libdevcore/Guards.h>
  21. namespace dev
  22. {
  23. namespace eth
  24. {
  25. /**
  26. * @brief Simple thread-safe cache to store a mapping from code hash to code size.
  27. * If the cache is full, a random element is removed.
  28. */
  29. class CodeSizeCache
  30. {
  31. public:
  32. void store(h256 const& _hash, size_t size)
  33. {
  34. UniqueGuard g(x_cache);
  35. if (m_cache.size() >= c_maxSize)
  36. removeRandomElement();
  37. m_cache[_hash] = size;
  38. }
  39. bool contains(h256 const& _hash) const
  40. {
  41. UniqueGuard g(x_cache);
  42. return m_cache.count(_hash);
  43. }
  44. size_t get(h256 const& _hash) const
  45. {
  46. UniqueGuard g(x_cache);
  47. return m_cache.at(_hash);
  48. }
  49. static CodeSizeCache& instance() { static CodeSizeCache cache; return cache; }
  50. private:
  51. /// Removes a random element from the cache.
  52. void removeRandomElement()
  53. {
  54. if (!m_cache.empty())
  55. {
  56. auto it = m_cache.lower_bound(h256::random());
  57. if (it == m_cache.end())
  58. it = m_cache.begin();
  59. m_cache.erase(it);
  60. }
  61. }
  62. static const size_t c_maxSize = 50000;
  63. mutable Mutex x_cache;
  64. std::map<h256, size_t> m_cache;
  65. };
  66. }
  67. }