/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see . */ /** @file BloomFilter.h * @author Vladislav Gluhovsky * @date June 2015 */ #pragma once #include "Common.h" namespace dev { namespace shh { template class TopicBloomFilterBase: public FixedHash { public: TopicBloomFilterBase() { init(); } TopicBloomFilterBase(FixedHash const& _h): FixedHash(_h) { init(); } void addBloom(dev::shh::AbridgedTopic const& _h) { addRaw(_h.template bloomPart()); } void removeBloom(dev::shh::AbridgedTopic const& _h) { removeRaw(_h.template bloomPart()); } bool containsBloom(dev::shh::AbridgedTopic const& _h) const { return this->contains(_h.template bloomPart()); } void addRaw(FixedHash const& _h); void removeRaw(FixedHash const& _h); bool containsRaw(FixedHash const& _h) const { return this->contains(_h); } enum { BitsPerBloom = 3 }; private: void init() { for (unsigned i = 0; i < CounterSize; ++i) m_refCounter[i] = 0; } static bool isBitSet(FixedHash const& _h, unsigned _index); enum { CounterSize = 8 * TopicBloomFilterBase::size }; std::array m_refCounter; }; static unsigned const c_powerOfTwoBitMmask[8] = { 1, 2, 4, 8, 16, 32, 64, 128 }; template void TopicBloomFilterBase::addRaw(FixedHash const& _h) { *this |= _h; for (unsigned i = 0; i < CounterSize; ++i) if (isBitSet(_h, i)) { if (m_refCounter[i] != std::numeric_limits::max()) m_refCounter[i]++; else BOOST_THROW_EXCEPTION(Overflow()); } } template void TopicBloomFilterBase::removeRaw(FixedHash const& _h) { for (unsigned i = 0; i < CounterSize; ++i) if (isBitSet(_h, i)) { if (m_refCounter[i]) m_refCounter[i]--; if (!m_refCounter[i]) (*this)[i / 8] &= ~c_powerOfTwoBitMmask[i % 8]; } } template bool TopicBloomFilterBase::isBitSet(FixedHash const& _h, unsigned _index) { unsigned iByte = _index / 8; unsigned iBit = _index % 8; return (_h[iByte] & c_powerOfTwoBitMmask[iBit]) != 0; } using TopicBloomFilter = TopicBloomFilterBase; } }