• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #ifndef _DEMODULARCOUNTER_HPP
2 #define _DEMODULARCOUNTER_HPP
3 /*-------------------------------------------------------------------------
4  * drawElements C++ Base Library
5  * -----------------------------
6  *
7  * Copyright 2023 Valve Corporation.
8  *
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  *//*!
22  * \file
23  * \brief Modular counter helper class.
24  *//*--------------------------------------------------------------------*/
25 
26 #include <type_traits>
27 #include <cstdint>
28 
29 namespace de
30 {
31 
32 template <typename T>
33 class ModularCounter
34 {
35 	static_assert(std::is_unsigned<T>::value, "Invalid underlying type");
36 
37 public:
38 	typedef T value_type;
39 
ModularCounter(T period,T initialValue=T{0})40 	explicit ModularCounter (T period, T initialValue = T{0})
41 		: m_period(period), m_value(initialValue)
42 	{
43 	}
44 
operator ++()45 	ModularCounter& operator++	()			{ m_value = ((m_value + T{1}) % m_period); return *this; }
operator --()46 	ModularCounter& operator--	()			{ m_value = ((m_value - T{1}) % m_period); return *this; }
operator ++(int)47 	ModularCounter  operator++	(int)		{ ModularCounter ret(*this); ++(*this); return ret; }
operator --(int)48 	ModularCounter  operator--	(int)		{ ModularCounter ret(*this); --(*this); return ret; }
operator T(void)49 	operator		T			(void)		{ return m_value; }
50 
51 protected:
52 	const T	m_period;
53 	T		m_value;
54 };
55 
56 using ModCounter64 = ModularCounter<uint64_t>;
57 using ModCounter32 = ModularCounter<uint32_t>;
58 
59 }
60 
61 #endif // _DEMODULARCOUNTER_HPP
62