Skip to content

Commit

Permalink
BITCOUNT command
Browse files Browse the repository at this point in the history
  • Loading branch information
dsmathers committed Aug 6, 2012
1 parent 105dbbb commit f65c097
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
16 changes: 16 additions & 0 deletions txredis/client.py
Expand Up @@ -267,6 +267,22 @@ def setbit(self, key, offset, value):
self._send('SETBIT', key, offset, value)
return self.getResponse()

def bitcount(self, key, start=None, end=None):
"""
Count the number of set bits (population counting) in a string.
@param key: The Redis key to get bit count from.
@param start: Optional starting index for bytes to scan (inclusive)
@param end: Optional ending index for bytes to scan (inclusive). End index is
required when start is given.
"""
start_end = []
if start is not None:
start_end.append(start)
start_end.append(end)
self._send('BITCOUNT', key, *start_end)
return self.getResponse()

# Commands operating on the key space
def keys(self, pattern):
"""
Expand Down
24 changes: 24 additions & 0 deletions txredis/tests/test_client.py
Expand Up @@ -651,6 +651,30 @@ def test_getbit(self):
self.assertEqual(a, 1)


@defer.inlineCallbacks
def test_bitcount(self):
r = self.redis
# TODO tearDown or setUp should flushdb?
yield r.delete('bittest')

yield r.setbit('bittest', 10, 1)
yield r.setbit('bittest', 25, 1)
yield r.setbit('bittest', 3, 1)
ct = yield r.bitcount('bittest')
self.assertEqual(ct, 3)

@defer.inlineCallbacks
def test_bitcount_with_start_and_end(self):
r = self.redis
yield r.delete('bittest')

yield r.setbit('bittest', 10, 1)
yield r.setbit('bittest', 25, 1)
yield r.setbit('bittest', 3, 1)
ct = yield r.bitcount('bittest', 1, 2)
self.assertEqual(ct, 1)


class ListsCommandsTestCase(CommandsBaseTestCase):
"""Test commands that operate on lists.
"""
Expand Down

0 comments on commit f65c097

Please sign in to comment.