Skip to content

Commit

Permalink
Added BitMap
Browse files Browse the repository at this point in the history
  • Loading branch information
matyhtf committed Oct 28, 2024
1 parent eb48e6e commit 26e0484
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
42 changes: 42 additions & 0 deletions core-tests/src/core/util.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| @link https://www.swoole.com/ |
| @contact [email protected] |
| @license https://github.com/swoole/swoole-src/blob/master/LICENSE |
| @Author Tianfeng Han <[email protected]> |
+----------------------------------------------------------------------+
*/

#include "test_core.h"

#include "swoole_util.h"

TEST(util, bitmap) {
swoole::BitMap m(4096);

m.set(199);
m.set(1234);
m.set(3048);

ASSERT_EQ(m.get(199), true);
ASSERT_EQ(m.get(1234), true);
ASSERT_EQ(m.get(3048), true);

ASSERT_EQ(m.get(2048), false);
ASSERT_EQ(m.get(128), false);

m.unset(1234);
ASSERT_EQ(m.get(1234), false);

m.clear();
}
50 changes: 50 additions & 0 deletions include/swoole_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,56 @@ class ScopeGuard {
bool _active;
};

class BitMap {
private:
uint64_t *array_;
size_t n_bits_;

size_t get_array_size(size_t n_bits) {
return (((n_bits) + 63) / 64 * 8);
}

size_t get_offset(size_t i) {
assert(i < n_bits_);
/* (i / 64) */
return i >> 6;
}

uint64_t to_int(size_t i, size_t offset) {
return ((uint64_t) 1) << (i - (offset << 6));
}

public:
BitMap(size_t n_bits) {
assert(n_bits > 0);
array_ = (uint64_t *) new uint64_t[get_array_size(n_bits)];
n_bits_ = n_bits;
}

~BitMap() {
delete[] array_;
}

void clear() {
memset(array_, 0, get_array_size(n_bits_));
}

void set(size_t i) {
const size_t off = get_offset(i);
array_[off] |= to_int(i, off);
}

void unset(size_t i) {
const size_t off = get_offset(i);
array_[off] &= ~to_int(i, off);
}

bool get(size_t i) {
const size_t off = get_offset(i);
return array_[off] & to_int(i, off);
}
};

namespace detail {
enum class ScopeGuardOnExit {};

Expand Down

0 comments on commit 26e0484

Please sign in to comment.