/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ART_LIBARTBASE_BASE_BIT_UTILS_ITERATOR_H_ #define ART_LIBARTBASE_BASE_BIT_UTILS_ITERATOR_H_ #include #include #include #include #include "bit_utils.h" #include "iteration_range.h" #include "stl_util.h" namespace art { // Using the Curiously Recurring Template Pattern to implement everything shared // by LowToHighBitIterator and HighToLowBitIterator, i.e. everything but operator*(). template class BitIteratorBase : public std::iterator { static_assert(std::is_integral::value, "T must be integral"); static_assert(std::is_unsigned::value, "T must be unsigned"); static_assert(sizeof(T) == sizeof(uint32_t) || sizeof(T) == sizeof(uint64_t), "Unsupported size"); public: BitIteratorBase() : bits_(0u) { } explicit BitIteratorBase(T bits) : bits_(bits) { } Iter& operator++() { DCHECK_NE(bits_, 0u); uint32_t bit = *static_cast(*this); bits_ &= ~(static_cast(1u) << bit); return static_cast(*this); } Iter& operator++(int) { Iter tmp(static_cast(*this)); ++*this; return tmp; } protected: T bits_; template friend bool operator==(const BitIteratorBase& lhs, const BitIteratorBase& rhs); }; template bool operator==(const BitIteratorBase& lhs, const BitIteratorBase& rhs) { return lhs.bits_ == rhs.bits_; } template bool operator!=(const BitIteratorBase& lhs, const BitIteratorBase& rhs) { return !(lhs == rhs); } template class LowToHighBitIterator : public BitIteratorBase> { public: using BitIteratorBase>::BitIteratorBase; uint32_t operator*() const { DCHECK_NE(this->bits_, 0u); return CTZ(this->bits_); } }; template class HighToLowBitIterator : public BitIteratorBase> { public: using BitIteratorBase>::BitIteratorBase; uint32_t operator*() const { DCHECK_NE(this->bits_, 0u); static_assert(std::numeric_limits::radix == 2, "Unexpected radix!"); return std::numeric_limits::digits - 1u - CLZ(this->bits_); } }; template IterationRange> LowToHighBits(T bits) { return IterationRange>( LowToHighBitIterator(bits), LowToHighBitIterator()); } template IterationRange> HighToLowBits(T bits) { return IterationRange>( HighToLowBitIterator(bits), HighToLowBitIterator()); } } // namespace art #endif // ART_LIBARTBASE_BASE_BIT_UTILS_ITERATOR_H_