xref: /haiku/headers/private/kernel/util/Bitmap.h (revision e1c4049fed1047bdb957b0529e1921e97ef94770)
1 /*
2  * Copyright 2013-2022, Haiku, Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Paweł Dziepak, pdziepak@quarnos.org
7  *		Augustin Cavalier <waddlesplash>
8  */
9 #ifndef KERNEL_UTIL_BITMAP_H
10 #define KERNEL_UTIL_BITMAP_H
11 
12 
13 #ifdef _KERNEL_MODE
14 #	include <debug.h>
15 #else
16 #	include <Debug.h>
17 #endif
18 
19 #include <SupportDefs.h>
20 
21 namespace BKernel {
22 
23 class Bitmap {
24 public:
25 						Bitmap(size_t bitCount = 0);
26 						~Bitmap();
27 
28 			status_t	InitCheck();
29 
30 			status_t	Resize(size_t bitCount);
31 			void		Shift(ssize_t bitCount);
32 
33 	inline	bool		Get(size_t index) const;
34 	inline	void		Set(size_t index);
35 	inline	void		Clear(size_t index);
36 
37 			void		SetRange(size_t index, size_t count);
38 			void		ClearRange(size_t index, size_t count);
39 
40 			ssize_t		GetLowestClear(size_t fromIndex = 0) const;
41 			ssize_t		GetLowestContiguousClear(size_t count, size_t fromIndex = 0) const;
42 			ssize_t		GetHighestSet() const;
43 
44 private:
45 			size_t		fElementsCount;
46 			size_t		fSize;
47 			addr_t*		fBits;
48 
49 	static	const int	kBitsPerElement = (sizeof(addr_t) * 8);
50 };
51 
52 
53 bool
54 Bitmap::Get(size_t index) const
55 {
56 	ASSERT(index < fSize);
57 
58 	const size_t kArrayElement = index / kBitsPerElement;
59 	const addr_t kBitMask = addr_t(1) << (index % kBitsPerElement);
60 	return fBits[kArrayElement] & kBitMask;
61 }
62 
63 
64 void
65 Bitmap::Set(size_t index)
66 {
67 	ASSERT(index < fSize);
68 
69 	const size_t kArrayElement = index / kBitsPerElement;
70 	const addr_t kBitMask = addr_t(1) << (index % kBitsPerElement);
71 	fBits[kArrayElement] |= kBitMask;
72 }
73 
74 
75 void
76 Bitmap::Clear(size_t index)
77 {
78 	ASSERT(index < fSize);
79 
80 	const size_t kArrayElement = index / kBitsPerElement;
81 	const addr_t kBitMask = addr_t(1) << (index % kBitsPerElement);
82 	fBits[kArrayElement] &= ~addr_t(kBitMask);
83 }
84 
85 } // namespace BKernel
86 
87 
88 using BKernel::Bitmap;
89 
90 
91 #endif	// KERNEL_UTIL_BITMAP_H
92 
93