Skip to content

Commit

Permalink
Merge pull request #3 from djfroofy/bit-operations
Browse files Browse the repository at this point in the history
Bit operations
  • Loading branch information
powdahound committed Aug 8, 2012
2 parents d06c9f0 + f65c097 commit b0edc58
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
31 changes: 31 additions & 0 deletions txredis/client.py
Expand Up @@ -244,14 +244,45 @@ def get_object(self, key, refcount=False, encoding=False, idletime=False):
self._send('OBJECT', subcommand, key)
return self.getResponse()


# Bit operations
def getbit(self, key, offset):
"""
Returns the bit value at offset in the string value stored at key.
@param key: The Redis key to get bit from.
@param offset: The offset to get bit from.
"""
self._send('GETBIT', key, offset)
return self.getResponse()

def setbit(self, key, offset, value):
"""
Sets the bit value at offset in the string value stored at key.
@param key: The Redis key to set bit on.
@param offset: The offset for the bit to set.
@param value: The bit value (0 or 1)
"""
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 b0edc58

Please sign in to comment.