more stdlib modules work

This commit is contained in:
Araq 2014-08-31 15:25:54 +02:00
commit 93eb9c456d
4 changed files with 213 additions and 213 deletions

View file

@ -84,14 +84,14 @@ proc decode(dest: var openArray[int8], src: openArray[int32]) =
dest[i+3] = toU8(src[j] shr 24'i32 and 0xff'i32) dest[i+3] = toU8(src[j] shr 24'i32 and 0xff'i32)
inc(i, 4) inc(i, 4)
proc transform(Buffer: pointer, State: var MD5State) = proc transform(buffer: pointer, state: var MD5State) =
var var
myBlock: MD5Block myBlock: MD5Block
encode(myBlock, cast[cstring](Buffer)) encode(myBlock, cast[cstring](buffer))
var a = State[0] var a = state[0]
var b = State[1] var b = state[1]
var c = State[2] var c = state[2]
var d = State[3] var d = state[3]
FF(a, b, c, d, myBlock[0], 7'i8, 0xD76AA478'i32) FF(a, b, c, d, myBlock[0], 7'i8, 0xD76AA478'i32)
FF(d, a, b, c, myBlock[1], 12'i8, 0xE8C7B756'i32) FF(d, a, b, c, myBlock[1], 12'i8, 0xE8C7B756'i32)
FF(c, d, a, b, myBlock[2], 17'i8, 0x242070DB'i32) FF(c, d, a, b, myBlock[2], 17'i8, 0x242070DB'i32)
@ -156,52 +156,52 @@ proc transform(Buffer: pointer, State: var MD5State) =
II(d, a, b, c, myBlock[11], 10'i8, 0xBD3AF235'i32) II(d, a, b, c, myBlock[11], 10'i8, 0xBD3AF235'i32)
II(c, d, a, b, myBlock[2], 15'i8, 0x2AD7D2BB'i32) II(c, d, a, b, myBlock[2], 15'i8, 0x2AD7D2BB'i32)
II(b, c, d, a, myBlock[9], 21'i8, 0xEB86D391'i32) II(b, c, d, a, myBlock[9], 21'i8, 0xEB86D391'i32)
State[0] = State[0] +% a state[0] = state[0] +% a
State[1] = State[1] +% b state[1] = state[1] +% b
State[2] = State[2] +% c state[2] = state[2] +% c
State[3] = State[3] +% d state[3] = state[3] +% d
proc md5Init*(c: var MD5Context) = proc md5Init*(c: var MD5Context) =
## initializes a MD5Context ## initializes a MD5Context
c.State[0] = 0x67452301'i32 c.state[0] = 0x67452301'i32
c.State[1] = 0xEFCDAB89'i32 c.state[1] = 0xEFCDAB89'i32
c.State[2] = 0x98BADCFE'i32 c.state[2] = 0x98BADCFE'i32
c.State[3] = 0x10325476'i32 c.state[3] = 0x10325476'i32
c.Count[0] = 0'i32 c.count[0] = 0'i32
c.Count[1] = 0'i32 c.count[1] = 0'i32
zeroMem(addr(c.Buffer), sizeof(MD5Buffer)) zeroMem(addr(c.buffer), sizeof(MD5buffer))
proc md5Update*(c: var MD5Context, input: cstring, len: int) = proc md5Update*(c: var MD5Context, input: cstring, len: int) =
## updates the MD5Context with the `input` data of length `len` ## updates the MD5Context with the `input` data of length `len`
var input = input var input = input
var Index = (c.count[0] shr 3) and 0x3F var Index = (c.count[0] shr 3) and 0x3F
c.Count[0] = c.count[0] +% toU32(len shl 3) c.count[0] = c.count[0] +% toU32(len shl 3)
if c.Count[0] < (len shl 3): c.Count[1] = c.count[1] +% 1'i32 if c.count[0] < (len shl 3): c.count[1] = c.count[1] +% 1'i32
c.Count[1] = c.count[1] +% toU32(len shr 29) c.count[1] = c.count[1] +% toU32(len shr 29)
var PartLen = 64 - Index var PartLen = 64 - Index
if len >= PartLen: if len >= PartLen:
copyMem(addr(c.Buffer[Index]), input, PartLen) copyMem(addr(c.buffer[Index]), input, PartLen)
transform(addr(c.Buffer), c.State) transform(addr(c.buffer), c.state)
var i = PartLen var i = PartLen
while i + 63 < len: while i + 63 < len:
transform(addr(input[i]), c.State) transform(addr(input[i]), c.state)
inc(i, 64) inc(i, 64)
copyMem(addr(c.Buffer[0]), addr(input[i]), len-i) copyMem(addr(c.buffer[0]), addr(input[i]), len-i)
else: else:
copyMem(addr(c.Buffer[Index]), addr(input[0]), len) copyMem(addr(c.buffer[Index]), addr(input[0]), len)
proc md5Final*(c: var MD5Context, digest: var MD5Digest) = proc md5Final*(c: var MD5Context, digest: var MD5Digest) =
## finishes the MD5Context and stores the result in `digest` ## finishes the MD5Context and stores the result in `digest`
var var
Bits: MD5CBits Bits: MD5CBits
PadLen: int PadLen: int
decode(Bits, c.Count) decode(Bits, c.count)
var Index = (c.Count[0] shr 3) and 0x3F var Index = (c.count[0] shr 3) and 0x3F
if Index < 56: PadLen = 56 - Index if Index < 56: PadLen = 56 - Index
else: PadLen = 120 - Index else: PadLen = 120 - Index
md5Update(c, padding, PadLen) md5Update(c, padding, PadLen)
md5Update(c, cast[cstring](addr(Bits)), 8) md5Update(c, cast[cstring](addr(Bits)), 8)
decode(digest, c.State) decode(digest, c.state)
zeroMem(addr(c), sizeof(MD5Context)) zeroMem(addr(c), sizeof(MD5Context))
proc toMD5*(s: string): MD5Digest = proc toMD5*(s: string): MD5Digest =
@ -216,8 +216,8 @@ proc `$`*(D: MD5Digest): string =
const digits = "0123456789abcdef" const digits = "0123456789abcdef"
result = "" result = ""
for i in 0..15: for i in 0..15:
add(result, Digits[(D[i] shr 4) and 0xF]) add(result, digits[(D[i] shr 4) and 0xF])
add(result, Digits[D[i] and 0xF]) add(result, digits[D[i] and 0xF])
proc getMD5*(s: string): string = proc getMD5*(s: string): string =
## computes an MD5 value of `s` and returns its string representation ## computes an MD5 value of `s` and returns its string representation

View file

@ -51,7 +51,7 @@ proc raiseEInvalidCsv(filename: string, line, col: int,
raise e raise e
proc error(my: CsvParser, pos: int, msg: string) = proc error(my: CsvParser, pos: int, msg: string) =
raiseEInvalidCsv(my.filename, my.LineNumber, getColNumber(my, pos), msg) raiseEInvalidCsv(my.filename, my.lineNumber, getColNumber(my, pos), msg)
proc open*(my: var CsvParser, input: Stream, filename: string, proc open*(my: var CsvParser, input: Stream, filename: string,
separator = ',', quote = '"', escape = '\0', separator = ',', quote = '"', escape = '\0',

View file

@ -31,7 +31,7 @@ type
type type
Redis* = object Redis* = object
socket: TSocket socket: Socket
connected: bool connected: bool
pipeline: Pipeline pipeline: Pipeline
@ -45,7 +45,7 @@ type
{.deprecated: [TSendMode: SendMode, TRedis: Redis, TRedisStatus: RedisStatus, {.deprecated: [TSendMode: SendMode, TRedis: Redis, TRedisStatus: RedisStatus,
TRedisInteger: RedisInteger, TRedisString: RedisString, TRedisInteger: RedisInteger, TRedisString: RedisString,
TRedisList: RedistList, EInvalidReply: ReplyError, ERedis: RedisError].} TRedisList: RedisList, EInvalidReply: ReplyError, ERedis: RedisError].}
proc newPipeline(): Pipeline = proc newPipeline(): Pipeline =
new(result) new(result)
@ -56,8 +56,8 @@ proc newPipeline(): Pipeline =
proc open*(host = "localhost", port = 6379.Port): Redis = proc open*(host = "localhost", port = 6379.Port): Redis =
## Opens a connection to the redis server. ## Opens a connection to the redis server.
result.socket = socket(buffered = false) result.socket = socket(buffered = false)
if result.socket == InvalidSocket: if result.socket == invalidSocket:
OSError(OSLastError()) raiseOSError(osLastError())
result.socket.connect(host, port) result.socket.connect(host, port)
result.pipeline = newPipeline() result.pipeline = newPipeline()
@ -68,9 +68,9 @@ proc raiseInvalidReply(expected, got: char) =
proc raiseNoOK(status: string, pipelineEnabled: bool) = proc raiseNoOK(status: string, pipelineEnabled: bool) =
if pipelineEnabled and not (status == "QUEUED" or status == "PIPELINED"): if pipelineEnabled and not (status == "QUEUED" or status == "PIPELINED"):
raise newException(EInvalidReply, "Expected \"QUEUED\" or \"PIPELINED\" got \"$1\"" % status) raise newException(ReplyError, "Expected \"QUEUED\" or \"PIPELINED\" got \"$1\"" % status)
elif not pipelineEnabled and status != "OK": elif not pipelineEnabled and status != "OK":
raise newException(EInvalidReply, "Expected \"OK\" got \"$1\"" % status) raise newException(ReplyError, "Expected \"OK\" got \"$1\"" % status)
template readSocket(r: Redis, dummyVal:expr): stmt = template readSocket(r: Redis, dummyVal:expr): stmt =
var line {.inject.}: TaintedString = "" var line {.inject.}: TaintedString = ""
@ -84,75 +84,75 @@ proc parseStatus(r: Redis, line: string = ""): RedisStatus =
return "PIPELINED" return "PIPELINED"
if line == "": if line == "":
raise newException(ERedis, "Server closed connection prematurely") raise newException(RedisError, "Server closed connection prematurely")
if line[0] == '-': if line[0] == '-':
raise newException(ERedis, strip(line)) raise newException(RedisError, strip(line))
if line[0] != '+': if line[0] != '+':
raiseInvalidReply('+', line[0]) raiseInvalidReply('+', line[0])
return line.substr(1) # Strip '+' return line.substr(1) # Strip '+'
proc readStatus(r:TRedis): TRedisStatus = proc readStatus(r:Redis): RedisStatus =
r.readSocket("PIPELINED") r.readSocket("PIPELINED")
return r.parseStatus(line) return r.parseStatus(line)
proc parseInteger(r: TRedis, line: string = ""): TRedisInteger = proc parseInteger(r: Redis, line: string = ""): RedisInteger =
if r.pipeline.enabled: return -1 if r.pipeline.enabled: return -1
#if line == "+QUEUED": # inside of multi #if line == "+QUEUED": # inside of multi
# return -1 # return -1
if line == "": if line == "":
raise newException(ERedis, "Server closed connection prematurely") raise newException(RedisError, "Server closed connection prematurely")
if line[0] == '-': if line[0] == '-':
raise newException(ERedis, strip(line)) raise newException(RedisError, strip(line))
if line[0] != ':': if line[0] != ':':
raiseInvalidReply(':', line[0]) raiseInvalidReply(':', line[0])
# Strip ':' # Strip ':'
if parseBiggestInt(line, result, 1) == 0: if parseBiggestInt(line, result, 1) == 0:
raise newException(EInvalidReply, "Unable to parse integer.") raise newException(ReplyError, "Unable to parse integer.")
proc readInteger(r: TRedis): TRedisInteger = proc readInteger(r: Redis): RedisInteger =
r.readSocket(-1) r.readSocket(-1)
return r.parseInteger(line) return r.parseInteger(line)
proc recv(sock: TSocket, size: int): TaintedString = proc recv(sock: Socket, size: int): TaintedString =
result = newString(size).TaintedString result = newString(size).TaintedString
if sock.recv(cstring(result), size) != size: if sock.recv(cstring(result), size) != size:
raise newException(EInvalidReply, "recv failed") raise newException(ReplyError, "recv failed")
proc parseSingleString(r: TRedis, line:string, allowMBNil = False): TRedisString = proc parseSingleString(r: Redis, line:string, allowMBNil = false): RedisString =
if r.pipeline.enabled: return "" if r.pipeline.enabled: return ""
# Error. # Error.
if line[0] == '-': if line[0] == '-':
raise newException(ERedis, strip(line)) raise newException(RedisError, strip(line))
# Some commands return a /bulk/ value or a /multi-bulk/ nil. Odd. # Some commands return a /bulk/ value or a /multi-bulk/ nil. Odd.
if allowMBNil: if allowMBNil:
if line == "*-1": if line == "*-1":
return RedisNil return redisNil
if line[0] != '$': if line[0] != '$':
raiseInvalidReply('$', line[0]) raiseInvalidReply('$', line[0])
var numBytes = parseInt(line.substr(1)) var numBytes = parseInt(line.substr(1))
if numBytes == -1: if numBytes == -1:
return RedisNil return redisNil
var s = r.socket.recv(numBytes+2) var s = r.socket.recv(numBytes+2)
result = strip(s.string) result = strip(s.string)
proc readSingleString(r: TRedis): TRedisString = proc readSingleString(r: Redis): RedisString =
r.readSocket("") r.readSocket("")
return r.parseSingleString(line) return r.parseSingleString(line)
proc readNext(r: TRedis): TRedisList proc readNext(r: Redis): RedisList
proc parseArrayLines(r: TRedis, countLine:string): TRedisList = proc parseArrayLines(r: Redis, countLine:string): RedisList =
if countLine.string[0] != '*': if countLine.string[0] != '*':
raiseInvalidReply('*', countLine.string[0]) raiseInvalidReply('*', countLine.string[0])
@ -166,24 +166,24 @@ proc parseArrayLines(r: TRedis, countLine:string): TRedisList =
for item in parsed: for item in parsed:
result.add(item) result.add(item)
proc readArrayLines(r: TRedis): TRedisList = proc readArrayLines(r: Redis): RedisList =
r.readSocket(nil) r.readSocket(nil)
return r.parseArrayLines(line) return r.parseArrayLines(line)
proc parseBulkString(r: TRedis, allowMBNil = False, line:string = ""): TRedisString = proc parseBulkString(r: Redis, allowMBNil = false, line:string = ""): RedisString =
if r.pipeline.enabled: return "" if r.pipeline.enabled: return ""
return r.parseSingleString(line, allowMBNil) return r.parseSingleString(line, allowMBNil)
proc readBulkString(r: TRedis, allowMBNil = false): TRedisString = proc readBulkString(r: Redis, allowMBNil = false): RedisString =
r.readSocket("") r.readSocket("")
return r.parseBulkString(allowMBNil, line) return r.parseBulkString(allowMBNil, line)
proc readArray(r: TRedis): TRedisList = proc readArray(r: Redis): RedisList =
r.readSocket(@[]) r.readSocket(@[])
return r.parseArrayLines(line) return r.parseArrayLines(line)
proc readNext(r: TRedis): TRedisList = proc readNext(r: Redis): RedisList =
r.readSocket(@[]) r.readSocket(@[])
var res = case line[0] var res = case line[0]
@ -192,12 +192,12 @@ proc readNext(r: TRedis): TRedisList =
of '$': @[r.parseBulkString(true,line)] of '$': @[r.parseBulkString(true,line)]
of '*': r.parseArrayLines(line) of '*': r.parseArrayLines(line)
else: else:
raise newException(EInvalidReply, "readNext failed on line: " & line) raise newException(ReplyError, "readNext failed on line: " & line)
nil nil
r.pipeline.expected -= 1 r.pipeline.expected -= 1
return res return res
proc flushPipeline*(r: TRedis, wasMulti = false): TRedisList = proc flushPipeline*(r: Redis, wasMulti = false): RedisList =
## Send buffered commands, clear buffer, return results ## Send buffered commands, clear buffer, return results
if r.pipeline.buffer.len > 0: if r.pipeline.buffer.len > 0:
r.socket.send(r.pipeline.buffer) r.socket.send(r.pipeline.buffer)
@ -216,7 +216,7 @@ proc flushPipeline*(r: TRedis, wasMulti = false): TRedisList =
r.pipeline.expected = 0 r.pipeline.expected = 0
proc startPipelining*(r: TRedis) = proc startPipelining*(r: Redis) =
## Enable command pipelining (reduces network roundtrips). ## Enable command pipelining (reduces network roundtrips).
## Note that when enabled, you must call flushPipeline to actually send commands, except ## Note that when enabled, you must call flushPipeline to actually send commands, except
## for multi/exec() which enable and flush the pipeline automatically. ## for multi/exec() which enable and flush the pipeline automatically.
@ -225,7 +225,7 @@ proc startPipelining*(r: TRedis) =
r.pipeline.expected = 0 r.pipeline.expected = 0
r.pipeline.enabled = true r.pipeline.enabled = true
proc sendCommand(r: TRedis, cmd: string, args: varargs[string]) = proc sendCommand(r: Redis, cmd: string, args: varargs[string]) =
var request = "*" & $(1 + args.len()) & "\c\L" var request = "*" & $(1 + args.len()) & "\c\L"
request.add("$" & $cmd.len() & "\c\L") request.add("$" & $cmd.len() & "\c\L")
request.add(cmd & "\c\L") request.add(cmd & "\c\L")
@ -239,7 +239,7 @@ proc sendCommand(r: TRedis, cmd: string, args: varargs[string]) =
else: else:
r.socket.send(request) r.socket.send(request)
proc sendCommand(r: TRedis, cmd: string, arg1: string, proc sendCommand(r: Redis, cmd: string, arg1: string,
args: varargs[string]) = args: varargs[string]) =
var request = "*" & $(2 + args.len()) & "\c\L" var request = "*" & $(2 + args.len()) & "\c\L"
request.add("$" & $cmd.len() & "\c\L") request.add("$" & $cmd.len() & "\c\L")
@ -258,68 +258,68 @@ proc sendCommand(r: TRedis, cmd: string, arg1: string,
# Keys # Keys
proc del*(r: TRedis, keys: varargs[string]): TRedisInteger = proc del*(r: Redis, keys: varargs[string]): RedisInteger =
## Delete a key or multiple keys ## Delete a key or multiple keys
r.sendCommand("DEL", keys) r.sendCommand("DEL", keys)
return r.readInteger() return r.readInteger()
proc exists*(r: TRedis, key: string): bool = proc exists*(r: Redis, key: string): bool =
## Determine if a key exists ## Determine if a key exists
r.sendCommand("EXISTS", key) r.sendCommand("EXISTS", key)
return r.readInteger() == 1 return r.readInteger() == 1
proc expire*(r: TRedis, key: string, seconds: int): bool = proc expire*(r: Redis, key: string, seconds: int): bool =
## Set a key's time to live in seconds. Returns `false` if the key could ## Set a key's time to live in seconds. Returns `false` if the key could
## not be found or the timeout could not be set. ## not be found or the timeout could not be set.
r.sendCommand("EXPIRE", key, $seconds) r.sendCommand("EXPIRE", key, $seconds)
return r.readInteger() == 1 return r.readInteger() == 1
proc expireAt*(r: TRedis, key: string, timestamp: int): bool = proc expireAt*(r: Redis, key: string, timestamp: int): bool =
## Set the expiration for a key as a UNIX timestamp. Returns `false` ## Set the expiration for a key as a UNIX timestamp. Returns `false`
## if the key could not be found or the timeout could not be set. ## if the key could not be found or the timeout could not be set.
r.sendCommand("EXPIREAT", key, $timestamp) r.sendCommand("EXPIREAT", key, $timestamp)
return r.readInteger() == 1 return r.readInteger() == 1
proc keys*(r: TRedis, pattern: string): TRedisList = proc keys*(r: Redis, pattern: string): RedisList =
## Find all keys matching the given pattern ## Find all keys matching the given pattern
r.sendCommand("KEYS", pattern) r.sendCommand("KEYS", pattern)
return r.readArray() return r.readArray()
proc move*(r: TRedis, key: string, db: int): bool = proc move*(r: Redis, key: string, db: int): bool =
## Move a key to another database. Returns `true` on a successful move. ## Move a key to another database. Returns `true` on a successful move.
r.sendCommand("MOVE", key, $db) r.sendCommand("MOVE", key, $db)
return r.readInteger() == 1 return r.readInteger() == 1
proc persist*(r: TRedis, key: string): bool = proc persist*(r: Redis, key: string): bool =
## Remove the expiration from a key. ## Remove the expiration from a key.
## Returns `true` when the timeout was removed. ## Returns `true` when the timeout was removed.
r.sendCommand("PERSIST", key) r.sendCommand("PERSIST", key)
return r.readInteger() == 1 return r.readInteger() == 1
proc randomKey*(r: TRedis): TRedisString = proc randomKey*(r: Redis): RedisString =
## Return a random key from the keyspace ## Return a random key from the keyspace
r.sendCommand("RANDOMKEY") r.sendCommand("RANDOMKEY")
return r.readBulkString() return r.readBulkString()
proc rename*(r: TRedis, key, newkey: string): TRedisStatus = proc rename*(r: Redis, key, newkey: string): RedisStatus =
## Rename a key. ## Rename a key.
## ##
## **WARNING:** Overwrites `newkey` if it exists! ## **WARNING:** Overwrites `newkey` if it exists!
r.sendCommand("RENAME", key, newkey) r.sendCommand("RENAME", key, newkey)
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc renameNX*(r: TRedis, key, newkey: string): bool = proc renameNX*(r: Redis, key, newkey: string): bool =
## Same as ``rename`` but doesn't continue if `newkey` exists. ## Same as ``rename`` but doesn't continue if `newkey` exists.
## Returns `true` if key was renamed. ## Returns `true` if key was renamed.
r.sendCommand("RENAMENX", key, newkey) r.sendCommand("RENAMENX", key, newkey)
return r.readInteger() == 1 return r.readInteger() == 1
proc ttl*(r: TRedis, key: string): TRedisInteger = proc ttl*(r: Redis, key: string): RedisInteger =
## Get the time to live for a key ## Get the time to live for a key
r.sendCommand("TTL", key) r.sendCommand("TTL", key)
return r.readInteger() return r.readInteger()
proc keyType*(r: TRedis, key: string): TRedisStatus = proc keyType*(r: Redis, key: string): RedisStatus =
## Determine the type stored at key ## Determine the type stored at key
r.sendCommand("TYPE", key) r.sendCommand("TYPE", key)
return r.readStatus() return r.readStatus()
@ -327,131 +327,131 @@ proc keyType*(r: TRedis, key: string): TRedisStatus =
# Strings # Strings
proc append*(r: TRedis, key, value: string): TRedisInteger = proc append*(r: Redis, key, value: string): RedisInteger =
## Append a value to a key ## Append a value to a key
r.sendCommand("APPEND", key, value) r.sendCommand("APPEND", key, value)
return r.readInteger() return r.readInteger()
proc decr*(r: TRedis, key: string): TRedisInteger = proc decr*(r: Redis, key: string): RedisInteger =
## Decrement the integer value of a key by one ## Decrement the integer value of a key by one
r.sendCommand("DECR", key) r.sendCommand("DECR", key)
return r.readInteger() return r.readInteger()
proc decrBy*(r: TRedis, key: string, decrement: int): TRedisInteger = proc decrBy*(r: Redis, key: string, decrement: int): RedisInteger =
## Decrement the integer value of a key by the given number ## Decrement the integer value of a key by the given number
r.sendCommand("DECRBY", key, $decrement) r.sendCommand("DECRBY", key, $decrement)
return r.readInteger() return r.readInteger()
proc get*(r: TRedis, key: string): TRedisString = proc get*(r: Redis, key: string): RedisString =
## Get the value of a key. Returns `redisNil` when `key` doesn't exist. ## Get the value of a key. Returns `redisNil` when `key` doesn't exist.
r.sendCommand("GET", key) r.sendCommand("GET", key)
return r.readBulkString() return r.readBulkString()
proc getBit*(r: TRedis, key: string, offset: int): TRedisInteger = proc getBit*(r: Redis, key: string, offset: int): RedisInteger =
## Returns the bit value at offset in the string value stored at key ## Returns the bit value at offset in the string value stored at key
r.sendCommand("GETBIT", key, $offset) r.sendCommand("GETBIT", key, $offset)
return r.readInteger() return r.readInteger()
proc getRange*(r: TRedis, key: string, start, stop: int): TRedisString = proc getRange*(r: Redis, key: string, start, stop: int): RedisString =
## Get a substring of the string stored at a key ## Get a substring of the string stored at a key
r.sendCommand("GETRANGE", key, $start, $stop) r.sendCommand("GETRANGE", key, $start, $stop)
return r.readBulkString() return r.readBulkString()
proc getSet*(r: TRedis, key: string, value: string): TRedisString = proc getSet*(r: Redis, key: string, value: string): RedisString =
## Set the string value of a key and return its old value. Returns `redisNil` ## Set the string value of a key and return its old value. Returns `redisNil`
## when key doesn't exist. ## when key doesn't exist.
r.sendCommand("GETSET", key, value) r.sendCommand("GETSET", key, value)
return r.readBulkString() return r.readBulkString()
proc incr*(r: TRedis, key: string): TRedisInteger = proc incr*(r: Redis, key: string): RedisInteger =
## Increment the integer value of a key by one. ## Increment the integer value of a key by one.
r.sendCommand("INCR", key) r.sendCommand("INCR", key)
return r.readInteger() return r.readInteger()
proc incrBy*(r: TRedis, key: string, increment: int): TRedisInteger = proc incrBy*(r: Redis, key: string, increment: int): RedisInteger =
## Increment the integer value of a key by the given number ## Increment the integer value of a key by the given number
r.sendCommand("INCRBY", key, $increment) r.sendCommand("INCRBY", key, $increment)
return r.readInteger() return r.readInteger()
proc setk*(r: TRedis, key, value: string) = proc setk*(r: Redis, key, value: string) =
## Set the string value of a key. ## Set the string value of a key.
## ##
## NOTE: This function had to be renamed due to a clash with the `set` type. ## NOTE: This function had to be renamed due to a clash with the `set` type.
r.sendCommand("SET", key, value) r.sendCommand("SET", key, value)
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc setNX*(r: TRedis, key, value: string): bool = proc setNX*(r: Redis, key, value: string): bool =
## Set the value of a key, only if the key does not exist. Returns `true` ## Set the value of a key, only if the key does not exist. Returns `true`
## if the key was set. ## if the key was set.
r.sendCommand("SETNX", key, value) r.sendCommand("SETNX", key, value)
return r.readInteger() == 1 return r.readInteger() == 1
proc setBit*(r: TRedis, key: string, offset: int, proc setBit*(r: Redis, key: string, offset: int,
value: string): TRedisInteger = value: string): RedisInteger =
## Sets or clears the bit at offset in the string value stored at key ## Sets or clears the bit at offset in the string value stored at key
r.sendCommand("SETBIT", key, $offset, value) r.sendCommand("SETBIT", key, $offset, value)
return r.readInteger() return r.readInteger()
proc setEx*(r: TRedis, key: string, seconds: int, value: string): TRedisStatus = proc setEx*(r: Redis, key: string, seconds: int, value: string): RedisStatus =
## Set the value and expiration of a key ## Set the value and expiration of a key
r.sendCommand("SETEX", key, $seconds, value) r.sendCommand("SETEX", key, $seconds, value)
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc setRange*(r: TRedis, key: string, offset: int, proc setRange*(r: Redis, key: string, offset: int,
value: string): TRedisInteger = value: string): RedisInteger =
## Overwrite part of a string at key starting at the specified offset ## Overwrite part of a string at key starting at the specified offset
r.sendCommand("SETRANGE", key, $offset, value) r.sendCommand("SETRANGE", key, $offset, value)
return r.readInteger() return r.readInteger()
proc strlen*(r: TRedis, key: string): TRedisInteger = proc strlen*(r: Redis, key: string): RedisInteger =
## Get the length of the value stored in a key. Returns 0 when key doesn't ## Get the length of the value stored in a key. Returns 0 when key doesn't
## exist. ## exist.
r.sendCommand("STRLEN", key) r.sendCommand("STRLEN", key)
return r.readInteger() return r.readInteger()
# Hashes # Hashes
proc hDel*(r: TRedis, key, field: string): bool = proc hDel*(r: Redis, key, field: string): bool =
## Delete a hash field at `key`. Returns `true` if the field was removed. ## Delete a hash field at `key`. Returns `true` if the field was removed.
r.sendCommand("HDEL", key, field) r.sendCommand("HDEL", key, field)
return r.readInteger() == 1 return r.readInteger() == 1
proc hExists*(r: TRedis, key, field: string): bool = proc hExists*(r: Redis, key, field: string): bool =
## Determine if a hash field exists. ## Determine if a hash field exists.
r.sendCommand("HEXISTS", key, field) r.sendCommand("HEXISTS", key, field)
return r.readInteger() == 1 return r.readInteger() == 1
proc hGet*(r: TRedis, key, field: string): TRedisString = proc hGet*(r: Redis, key, field: string): RedisString =
## Get the value of a hash field ## Get the value of a hash field
r.sendCommand("HGET", key, field) r.sendCommand("HGET", key, field)
return r.readBulkString() return r.readBulkString()
proc hGetAll*(r: TRedis, key: string): TRedisList = proc hGetAll*(r: Redis, key: string): RedisList =
## Get all the fields and values in a hash ## Get all the fields and values in a hash
r.sendCommand("HGETALL", key) r.sendCommand("HGETALL", key)
return r.readArray() return r.readArray()
proc hIncrBy*(r: TRedis, key, field: string, incr: int): TRedisInteger = proc hIncrBy*(r: Redis, key, field: string, incr: int): RedisInteger =
## Increment the integer value of a hash field by the given number ## Increment the integer value of a hash field by the given number
r.sendCommand("HINCRBY", key, field, $incr) r.sendCommand("HINCRBY", key, field, $incr)
return r.readInteger() return r.readInteger()
proc hKeys*(r: TRedis, key: string): TRedisList = proc hKeys*(r: Redis, key: string): RedisList =
## Get all the fields in a hash ## Get all the fields in a hash
r.sendCommand("HKEYS", key) r.sendCommand("HKEYS", key)
return r.readArray() return r.readArray()
proc hLen*(r: TRedis, key: string): TRedisInteger = proc hLen*(r: Redis, key: string): RedisInteger =
## Get the number of fields in a hash ## Get the number of fields in a hash
r.sendCommand("HLEN", key) r.sendCommand("HLEN", key)
return r.readInteger() return r.readInteger()
proc hMGet*(r: TRedis, key: string, fields: varargs[string]): TRedisList = proc hMGet*(r: Redis, key: string, fields: varargs[string]): RedisList =
## Get the values of all the given hash fields ## Get the values of all the given hash fields
r.sendCommand("HMGET", key, fields) r.sendCommand("HMGET", key, fields)
return r.readArray() return r.readArray()
proc hMSet*(r: TRedis, key: string, proc hMSet*(r: Redis, key: string,
fieldValues: openarray[tuple[field, value: string]]) = fieldValues: openArray[tuple[field, value: string]]) =
## Set multiple hash fields to multiple values ## Set multiple hash fields to multiple values
var args = @[key] var args = @[key]
for field, value in items(fieldValues): for field, value in items(fieldValues):
@ -460,24 +460,24 @@ proc hMSet*(r: TRedis, key: string,
r.sendCommand("HMSET", args) r.sendCommand("HMSET", args)
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc hSet*(r: TRedis, key, field, value: string): TRedisInteger = proc hSet*(r: Redis, key, field, value: string): RedisInteger =
## Set the string value of a hash field ## Set the string value of a hash field
r.sendCommand("HSET", key, field, value) r.sendCommand("HSET", key, field, value)
return r.readInteger() return r.readInteger()
proc hSetNX*(r: TRedis, key, field, value: string): TRedisInteger = proc hSetNX*(r: Redis, key, field, value: string): RedisInteger =
## Set the value of a hash field, only if the field does **not** exist ## Set the value of a hash field, only if the field does **not** exist
r.sendCommand("HSETNX", key, field, value) r.sendCommand("HSETNX", key, field, value)
return r.readInteger() return r.readInteger()
proc hVals*(r: TRedis, key: string): TRedisList = proc hVals*(r: Redis, key: string): RedisList =
## Get all the values in a hash ## Get all the values in a hash
r.sendCommand("HVALS", key) r.sendCommand("HVALS", key)
return r.readArray() return r.readArray()
# Lists # Lists
proc bLPop*(r: TRedis, keys: varargs[string], timeout: int): TRedisList = proc bLPop*(r: Redis, keys: varargs[string], timeout: int): RedisList =
## Remove and get the *first* element in a list, or block until ## Remove and get the *first* element in a list, or block until
## one is available ## one is available
var args: seq[string] = @[] var args: seq[string] = @[]
@ -486,7 +486,7 @@ proc bLPop*(r: TRedis, keys: varargs[string], timeout: int): TRedisList =
r.sendCommand("BLPOP", args) r.sendCommand("BLPOP", args)
return r.readArray() return r.readArray()
proc bRPop*(r: TRedis, keys: varargs[string], timeout: int): TRedisList = proc bRPop*(r: Redis, keys: varargs[string], timeout: int): RedisList =
## Remove and get the *last* element in a list, or block until one ## Remove and get the *last* element in a list, or block until one
## is available. ## is available.
var args: seq[string] = @[] var args: seq[string] = @[]
@ -495,8 +495,8 @@ proc bRPop*(r: TRedis, keys: varargs[string], timeout: int): TRedisList =
r.sendCommand("BRPOP", args) r.sendCommand("BRPOP", args)
return r.readArray() return r.readArray()
proc bRPopLPush*(r: TRedis, source, destination: string, proc bRPopLPush*(r: Redis, source, destination: string,
timeout: int): TRedisString = timeout: int): RedisString =
## Pop a value from a list, push it to another list and return it; or ## Pop a value from a list, push it to another list and return it; or
## block until one is available. ## block until one is available.
## ##
@ -504,32 +504,32 @@ proc bRPopLPush*(r: TRedis, source, destination: string,
r.sendCommand("BRPOPLPUSH", source, destination, $timeout) r.sendCommand("BRPOPLPUSH", source, destination, $timeout)
return r.readBulkString(true) # Multi-Bulk nil allowed. return r.readBulkString(true) # Multi-Bulk nil allowed.
proc lIndex*(r: TRedis, key: string, index: int): TRedisString = proc lIndex*(r: Redis, key: string, index: int): RedisString =
## Get an element from a list by its index ## Get an element from a list by its index
r.sendCommand("LINDEX", key, $index) r.sendCommand("LINDEX", key, $index)
return r.readBulkString() return r.readBulkString()
proc lInsert*(r: TRedis, key: string, before: bool, pivot, value: string): proc lInsert*(r: Redis, key: string, before: bool, pivot, value: string):
TRedisInteger = RedisInteger =
## Insert an element before or after another element in a list ## Insert an element before or after another element in a list
var pos = if before: "BEFORE" else: "AFTER" var pos = if before: "BEFORE" else: "AFTER"
r.sendCommand("LINSERT", key, pos, pivot, value) r.sendCommand("LINSERT", key, pos, pivot, value)
return r.readInteger() return r.readInteger()
proc lLen*(r: TRedis, key: string): TRedisInteger = proc lLen*(r: Redis, key: string): RedisInteger =
## Get the length of a list ## Get the length of a list
r.sendCommand("LLEN", key) r.sendCommand("LLEN", key)
return r.readInteger() return r.readInteger()
proc lPop*(r: TRedis, key: string): TRedisString = proc lPop*(r: Redis, key: string): RedisString =
## Remove and get the first element in a list ## Remove and get the first element in a list
r.sendCommand("LPOP", key) r.sendCommand("LPOP", key)
return r.readBulkString() return r.readBulkString()
proc lPush*(r: TRedis, key, value: string, create: bool = True): TRedisInteger = proc lPush*(r: Redis, key, value: string, create: bool = true): RedisInteger =
## Prepend a value to a list. Returns the length of the list after the push. ## Prepend a value to a list. Returns the length of the list after the push.
## The ``create`` param specifies whether a list should be created if it ## The ``create`` param specifies whether a list should be created if it
## doesn't exist at ``key``. More specifically if ``create`` is True, `LPUSH` ## doesn't exist at ``key``. More specifically if ``create`` is true, `LPUSH`
## will be used, otherwise `LPUSHX`. ## will be used, otherwise `LPUSHX`.
if create: if create:
r.sendCommand("LPUSH", key, value) r.sendCommand("LPUSH", key, value)
@ -537,42 +537,42 @@ proc lPush*(r: TRedis, key, value: string, create: bool = True): TRedisInteger =
r.sendCommand("LPUSHX", key, value) r.sendCommand("LPUSHX", key, value)
return r.readInteger() return r.readInteger()
proc lRange*(r: TRedis, key: string, start, stop: int): TRedisList = proc lRange*(r: Redis, key: string, start, stop: int): RedisList =
## Get a range of elements from a list. Returns `nil` when `key` ## Get a range of elements from a list. Returns `nil` when `key`
## doesn't exist. ## doesn't exist.
r.sendCommand("LRANGE", key, $start, $stop) r.sendCommand("LRANGE", key, $start, $stop)
return r.readArray() return r.readArray()
proc lRem*(r: TRedis, key: string, value: string, count: int = 0): TRedisInteger = proc lRem*(r: Redis, key: string, value: string, count: int = 0): RedisInteger =
## Remove elements from a list. Returns the number of elements that have been ## Remove elements from a list. Returns the number of elements that have been
## removed. ## removed.
r.sendCommand("LREM", key, $count, value) r.sendCommand("LREM", key, $count, value)
return r.readInteger() return r.readInteger()
proc lSet*(r: TRedis, key: string, index: int, value: string) = proc lSet*(r: Redis, key: string, index: int, value: string) =
## Set the value of an element in a list by its index ## Set the value of an element in a list by its index
r.sendCommand("LSET", key, $index, value) r.sendCommand("LSET", key, $index, value)
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc lTrim*(r: TRedis, key: string, start, stop: int) = proc lTrim*(r: Redis, key: string, start, stop: int) =
## Trim a list to the specified range ## Trim a list to the specified range
r.sendCommand("LTRIM", key, $start, $stop) r.sendCommand("LTRIM", key, $start, $stop)
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc rPop*(r: TRedis, key: string): TRedisString = proc rPop*(r: Redis, key: string): RedisString =
## Remove and get the last element in a list ## Remove and get the last element in a list
r.sendCommand("RPOP", key) r.sendCommand("RPOP", key)
return r.readBulkString() return r.readBulkString()
proc rPopLPush*(r: TRedis, source, destination: string): TRedisString = proc rPopLPush*(r: Redis, source, destination: string): RedisString =
## Remove the last element in a list, append it to another list and return it ## Remove the last element in a list, append it to another list and return it
r.sendCommand("RPOPLPUSH", source, destination) r.sendCommand("RPOPLPUSH", source, destination)
return r.readBulkString() return r.readBulkString()
proc rPush*(r: TRedis, key, value: string, create: bool = True): TRedisInteger = proc rPush*(r: Redis, key, value: string, create: bool = true): RedisInteger =
## Append a value to a list. Returns the length of the list after the push. ## Append a value to a list. Returns the length of the list after the push.
## The ``create`` param specifies whether a list should be created if it ## The ``create`` param specifies whether a list should be created if it
## doesn't exist at ``key``. More specifically if ``create`` is True, `RPUSH` ## doesn't exist at ``key``. More specifically if ``create`` is true, `RPUSH`
## will be used, otherwise `RPUSHX`. ## will be used, otherwise `RPUSHX`.
if create: if create:
r.sendCommand("RPUSH", key, value) r.sendCommand("RPUSH", key, value)
@ -582,106 +582,106 @@ proc rPush*(r: TRedis, key, value: string, create: bool = True): TRedisInteger =
# Sets # Sets
proc sadd*(r: TRedis, key: string, member: string): TRedisInteger = proc sadd*(r: Redis, key: string, member: string): RedisInteger =
## Add a member to a set ## Add a member to a set
r.sendCommand("SADD", key, member) r.sendCommand("SADD", key, member)
return r.readInteger() return r.readInteger()
proc scard*(r: TRedis, key: string): TRedisInteger = proc scard*(r: Redis, key: string): RedisInteger =
## Get the number of members in a set ## Get the number of members in a set
r.sendCommand("SCARD", key) r.sendCommand("SCARD", key)
return r.readInteger() return r.readInteger()
proc sdiff*(r: TRedis, keys: varargs[string]): TRedisList = proc sdiff*(r: Redis, keys: varargs[string]): RedisList =
## Subtract multiple sets ## Subtract multiple sets
r.sendCommand("SDIFF", keys) r.sendCommand("SDIFF", keys)
return r.readArray() return r.readArray()
proc sdiffstore*(r: TRedis, destination: string, proc sdiffstore*(r: Redis, destination: string,
keys: varargs[string]): TRedisInteger = keys: varargs[string]): RedisInteger =
## Subtract multiple sets and store the resulting set in a key ## Subtract multiple sets and store the resulting set in a key
r.sendCommand("SDIFFSTORE", destination, keys) r.sendCommand("SDIFFSTORE", destination, keys)
return r.readInteger() return r.readInteger()
proc sinter*(r: TRedis, keys: varargs[string]): TRedisList = proc sinter*(r: Redis, keys: varargs[string]): RedisList =
## Intersect multiple sets ## Intersect multiple sets
r.sendCommand("SINTER", keys) r.sendCommand("SINTER", keys)
return r.readArray() return r.readArray()
proc sinterstore*(r: TRedis, destination: string, proc sinterstore*(r: Redis, destination: string,
keys: varargs[string]): TRedisInteger = keys: varargs[string]): RedisInteger =
## Intersect multiple sets and store the resulting set in a key ## Intersect multiple sets and store the resulting set in a key
r.sendCommand("SINTERSTORE", destination, keys) r.sendCommand("SINTERSTORE", destination, keys)
return r.readInteger() return r.readInteger()
proc sismember*(r: TRedis, key: string, member: string): TRedisInteger = proc sismember*(r: Redis, key: string, member: string): RedisInteger =
## Determine if a given value is a member of a set ## Determine if a given value is a member of a set
r.sendCommand("SISMEMBER", key, member) r.sendCommand("SISMEMBER", key, member)
return r.readInteger() return r.readInteger()
proc smembers*(r: TRedis, key: string): TRedisList = proc smembers*(r: Redis, key: string): RedisList =
## Get all the members in a set ## Get all the members in a set
r.sendCommand("SMEMBERS", key) r.sendCommand("SMEMBERS", key)
return r.readArray() return r.readArray()
proc smove*(r: TRedis, source: string, destination: string, proc smove*(r: Redis, source: string, destination: string,
member: string): TRedisInteger = member: string): RedisInteger =
## Move a member from one set to another ## Move a member from one set to another
r.sendCommand("SMOVE", source, destination, member) r.sendCommand("SMOVE", source, destination, member)
return r.readInteger() return r.readInteger()
proc spop*(r: TRedis, key: string): TRedisString = proc spop*(r: Redis, key: string): RedisString =
## Remove and return a random member from a set ## Remove and return a random member from a set
r.sendCommand("SPOP", key) r.sendCommand("SPOP", key)
return r.readBulkString() return r.readBulkString()
proc srandmember*(r: TRedis, key: string): TRedisString = proc srandmember*(r: Redis, key: string): RedisString =
## Get a random member from a set ## Get a random member from a set
r.sendCommand("SRANDMEMBER", key) r.sendCommand("SRANDMEMBER", key)
return r.readBulkString() return r.readBulkString()
proc srem*(r: TRedis, key: string, member: string): TRedisInteger = proc srem*(r: Redis, key: string, member: string): RedisInteger =
## Remove a member from a set ## Remove a member from a set
r.sendCommand("SREM", key, member) r.sendCommand("SREM", key, member)
return r.readInteger() return r.readInteger()
proc sunion*(r: TRedis, keys: varargs[string]): TRedisList = proc sunion*(r: Redis, keys: varargs[string]): RedisList =
## Add multiple sets ## Add multiple sets
r.sendCommand("SUNION", keys) r.sendCommand("SUNION", keys)
return r.readArray() return r.readArray()
proc sunionstore*(r: TRedis, destination: string, proc sunionstore*(r: Redis, destination: string,
key: varargs[string]): TRedisInteger = key: varargs[string]): RedisInteger =
## Add multiple sets and store the resulting set in a key ## Add multiple sets and store the resulting set in a key
r.sendCommand("SUNIONSTORE", destination, key) r.sendCommand("SUNIONSTORE", destination, key)
return r.readInteger() return r.readInteger()
# Sorted sets # Sorted sets
proc zadd*(r: TRedis, key: string, score: int, member: string): TRedisInteger = proc zadd*(r: Redis, key: string, score: int, member: string): RedisInteger =
## Add a member to a sorted set, or update its score if it already exists ## Add a member to a sorted set, or update its score if it already exists
r.sendCommand("ZADD", key, $score, member) r.sendCommand("ZADD", key, $score, member)
return r.readInteger() return r.readInteger()
proc zcard*(r: TRedis, key: string): TRedisInteger = proc zcard*(r: Redis, key: string): RedisInteger =
## Get the number of members in a sorted set ## Get the number of members in a sorted set
r.sendCommand("ZCARD", key) r.sendCommand("ZCARD", key)
return r.readInteger() return r.readInteger()
proc zcount*(r: TRedis, key: string, min: string, max: string): TRedisInteger = proc zcount*(r: Redis, key: string, min: string, max: string): RedisInteger =
## Count the members in a sorted set with scores within the given values ## Count the members in a sorted set with scores within the given values
r.sendCommand("ZCOUNT", key, min, max) r.sendCommand("ZCOUNT", key, min, max)
return r.readInteger() return r.readInteger()
proc zincrby*(r: TRedis, key: string, increment: string, proc zincrby*(r: Redis, key: string, increment: string,
member: string): TRedisString = member: string): RedisString =
## Increment the score of a member in a sorted set ## Increment the score of a member in a sorted set
r.sendCommand("ZINCRBY", key, increment, member) r.sendCommand("ZINCRBY", key, increment, member)
return r.readBulkString() return r.readBulkString()
proc zinterstore*(r: TRedis, destination: string, numkeys: string, proc zinterstore*(r: Redis, destination: string, numkeys: string,
keys: openarray[string], weights: openarray[string] = [], keys: openArray[string], weights: openArray[string] = [],
aggregate: string = ""): TRedisInteger = aggregate: string = ""): RedisInteger =
## Intersect multiple sorted sets and store the resulting sorted set in ## Intersect multiple sorted sets and store the resulting sorted set in
## a new key ## a new key
var args = @[destination, numkeys] var args = @[destination, numkeys]
@ -698,8 +698,8 @@ proc zinterstore*(r: TRedis, destination: string, numkeys: string,
return r.readInteger() return r.readInteger()
proc zrange*(r: TRedis, key: string, start: string, stop: string, proc zrange*(r: Redis, key: string, start: string, stop: string,
withScores: bool): TRedisList = withScores: bool): RedisList =
## Return a range of members in a sorted set, by index ## Return a range of members in a sorted set, by index
if not withScores: if not withScores:
r.sendCommand("ZRANGE", key, start, stop) r.sendCommand("ZRANGE", key, start, stop)
@ -707,9 +707,9 @@ proc zrange*(r: TRedis, key: string, start: string, stop: string,
r.sendCommand("ZRANGE", "WITHSCORES", key, start, stop) r.sendCommand("ZRANGE", "WITHSCORES", key, start, stop)
return r.readArray() return r.readArray()
proc zrangebyscore*(r: TRedis, key: string, min: string, max: string, proc zrangebyscore*(r: Redis, key: string, min: string, max: string,
withScore: bool = false, limit: bool = False, withScore: bool = false, limit: bool = false,
limitOffset: int = 0, limitCount: int = 0): TRedisList = limitOffset: int = 0, limitCount: int = 0): RedisList =
## Return a range of members in a sorted set, by score ## Return a range of members in a sorted set, by score
var args = @[key, min, max] var args = @[key, min, max]
@ -722,30 +722,30 @@ proc zrangebyscore*(r: TRedis, key: string, min: string, max: string,
r.sendCommand("ZRANGEBYSCORE", args) r.sendCommand("ZRANGEBYSCORE", args)
return r.readArray() return r.readArray()
proc zrank*(r: TRedis, key: string, member: string): TRedisString = proc zrank*(r: Redis, key: string, member: string): RedisString =
## Determine the index of a member in a sorted set ## Determine the index of a member in a sorted set
r.sendCommand("ZRANK", key, member) r.sendCommand("ZRANK", key, member)
return r.readBulkString() return r.readBulkString()
proc zrem*(r: TRedis, key: string, member: string): TRedisInteger = proc zrem*(r: Redis, key: string, member: string): RedisInteger =
## Remove a member from a sorted set ## Remove a member from a sorted set
r.sendCommand("ZREM", key, member) r.sendCommand("ZREM", key, member)
return r.readInteger() return r.readInteger()
proc zremrangebyrank*(r: TRedis, key: string, start: string, proc zremrangebyrank*(r: Redis, key: string, start: string,
stop: string): TRedisInteger = stop: string): RedisInteger =
## Remove all members in a sorted set within the given indexes ## Remove all members in a sorted set within the given indexes
r.sendCommand("ZREMRANGEBYRANK", key, start, stop) r.sendCommand("ZREMRANGEBYRANK", key, start, stop)
return r.readInteger() return r.readInteger()
proc zremrangebyscore*(r: TRedis, key: string, min: string, proc zremrangebyscore*(r: Redis, key: string, min: string,
max: string): TRedisInteger = max: string): RedisInteger =
## Remove all members in a sorted set within the given scores ## Remove all members in a sorted set within the given scores
r.sendCommand("ZREMRANGEBYSCORE", key, min, max) r.sendCommand("ZREMRANGEBYSCORE", key, min, max)
return r.readInteger() return r.readInteger()
proc zrevrange*(r: TRedis, key: string, start: string, stop: string, proc zrevrange*(r: Redis, key: string, start: string, stop: string,
withScore: bool): TRedisList = withScore: bool): RedisList =
## Return a range of members in a sorted set, by index, ## Return a range of members in a sorted set, by index,
## with scores ordered from high to low ## with scores ordered from high to low
if withScore: if withScore:
@ -753,9 +753,9 @@ proc zrevrange*(r: TRedis, key: string, start: string, stop: string,
else: r.sendCommand("ZREVRANGE", key, start, stop) else: r.sendCommand("ZREVRANGE", key, start, stop)
return r.readArray() return r.readArray()
proc zrevrangebyscore*(r: TRedis, key: string, min: string, max: string, proc zrevrangebyscore*(r: Redis, key: string, min: string, max: string,
withScore: bool = false, limit: bool = False, withScore: bool = false, limit: bool = false,
limitOffset: int = 0, limitCount: int = 0): TRedisList = limitOffset: int = 0, limitCount: int = 0): RedisList =
## Return a range of members in a sorted set, by score, with ## Return a range of members in a sorted set, by score, with
## scores ordered from high to low ## scores ordered from high to low
var args = @[key, min, max] var args = @[key, min, max]
@ -769,20 +769,20 @@ proc zrevrangebyscore*(r: TRedis, key: string, min: string, max: string,
r.sendCommand("ZREVRANGEBYSCORE", args) r.sendCommand("ZREVRANGEBYSCORE", args)
return r.readArray() return r.readArray()
proc zrevrank*(r: TRedis, key: string, member: string): TRedisString = proc zrevrank*(r: Redis, key: string, member: string): RedisString =
## Determine the index of a member in a sorted set, with ## Determine the index of a member in a sorted set, with
## scores ordered from high to low ## scores ordered from high to low
r.sendCommand("ZREVRANK", key, member) r.sendCommand("ZREVRANK", key, member)
return r.readBulkString() return r.readBulkString()
proc zscore*(r: TRedis, key: string, member: string): TRedisString = proc zscore*(r: Redis, key: string, member: string): RedisString =
## Get the score associated with the given member in a sorted set ## Get the score associated with the given member in a sorted set
r.sendCommand("ZSCORE", key, member) r.sendCommand("ZSCORE", key, member)
return r.readBulkString() return r.readBulkString()
proc zunionstore*(r: TRedis, destination: string, numkeys: string, proc zunionstore*(r: Redis, destination: string, numkeys: string,
keys: openarray[string], weights: openarray[string] = [], keys: openArray[string], weights: openArray[string] = [],
aggregate: string = ""): TRedisInteger = aggregate: string = ""): RedisInteger =
## Add multiple sorted sets and store the resulting sorted set in a new key ## Add multiple sorted sets and store the resulting sorted set in a new key
var args = @[destination, numkeys] var args = @[destination, numkeys]
for i in items(keys): args.add(i) for i in items(keys): args.add(i)
@ -832,12 +832,12 @@ proc unsubscribe*(r: TRedis, [channel: openarray[string], : string): ???? =
# Transactions # Transactions
proc discardMulti*(r: TRedis) = proc discardMulti*(r: Redis) =
## Discard all commands issued after MULTI ## Discard all commands issued after MULTI
r.sendCommand("DISCARD") r.sendCommand("DISCARD")
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc exec*(r: TRedis): TRedisList = proc exec*(r: Redis): RedisList =
## Execute all commands issued after MULTI ## Execute all commands issued after MULTI
r.sendCommand("EXEC") r.sendCommand("EXEC")
r.pipeline.enabled = false r.pipeline.enabled = false
@ -846,106 +846,106 @@ proc exec*(r: TRedis): TRedisList =
return r.flushPipeline(true) return r.flushPipeline(true)
proc multi*(r: TRedis) = proc multi*(r: Redis) =
## Mark the start of a transaction block ## Mark the start of a transaction block
r.startPipelining() r.startPipelining()
r.sendCommand("MULTI") r.sendCommand("MULTI")
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc unwatch*(r: TRedis) = proc unwatch*(r: Redis) =
## Forget about all watched keys ## Forget about all watched keys
r.sendCommand("UNWATCH") r.sendCommand("UNWATCH")
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc watch*(r: TRedis, key: varargs[string]) = proc watch*(r: Redis, key: varargs[string]) =
## Watch the given keys to determine execution of the MULTI/EXEC block ## Watch the given keys to determine execution of the MULTI/EXEC block
r.sendCommand("WATCH", key) r.sendCommand("WATCH", key)
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
# Connection # Connection
proc auth*(r: TRedis, password: string) = proc auth*(r: Redis, password: string) =
## Authenticate to the server ## Authenticate to the server
r.sendCommand("AUTH", password) r.sendCommand("AUTH", password)
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc echoServ*(r: TRedis, message: string): TRedisString = proc echoServ*(r: Redis, message: string): RedisString =
## Echo the given string ## Echo the given string
r.sendCommand("ECHO", message) r.sendCommand("ECHO", message)
return r.readBulkString() return r.readBulkString()
proc ping*(r: TRedis): TRedisStatus = proc ping*(r: Redis): RedisStatus =
## Ping the server ## Ping the server
r.sendCommand("PING") r.sendCommand("PING")
return r.readStatus() return r.readStatus()
proc quit*(r: TRedis) = proc quit*(r: Redis) =
## Close the connection ## Close the connection
r.sendCommand("QUIT") r.sendCommand("QUIT")
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc select*(r: TRedis, index: int): TRedisStatus = proc select*(r: Redis, index: int): RedisStatus =
## Change the selected database for the current connection ## Change the selected database for the current connection
r.sendCommand("SELECT", $index) r.sendCommand("SELECT", $index)
return r.readStatus() return r.readStatus()
# Server # Server
proc bgrewriteaof*(r: TRedis) = proc bgrewriteaof*(r: Redis) =
## Asynchronously rewrite the append-only file ## Asynchronously rewrite the append-only file
r.sendCommand("BGREWRITEAOF") r.sendCommand("BGREWRITEAOF")
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc bgsave*(r: TRedis) = proc bgsave*(r: Redis) =
## Asynchronously save the dataset to disk ## Asynchronously save the dataset to disk
r.sendCommand("BGSAVE") r.sendCommand("BGSAVE")
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc configGet*(r: TRedis, parameter: string): TRedisList = proc configGet*(r: Redis, parameter: string): RedisList =
## Get the value of a configuration parameter ## Get the value of a configuration parameter
r.sendCommand("CONFIG", "GET", parameter) r.sendCommand("CONFIG", "GET", parameter)
return r.readArray() return r.readArray()
proc configSet*(r: TRedis, parameter: string, value: string) = proc configSet*(r: Redis, parameter: string, value: string) =
## Set a configuration parameter to the given value ## Set a configuration parameter to the given value
r.sendCommand("CONFIG", "SET", parameter, value) r.sendCommand("CONFIG", "SET", parameter, value)
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc configResetStat*(r: TRedis) = proc configResetStat*(r: Redis) =
## Reset the stats returned by INFO ## Reset the stats returned by INFO
r.sendCommand("CONFIG", "RESETSTAT") r.sendCommand("CONFIG", "RESETSTAT")
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc dbsize*(r: TRedis): TRedisInteger = proc dbsize*(r: Redis): RedisInteger =
## Return the number of keys in the selected database ## Return the number of keys in the selected database
r.sendCommand("DBSIZE") r.sendCommand("DBSIZE")
return r.readInteger() return r.readInteger()
proc debugObject*(r: TRedis, key: string): TRedisStatus = proc debugObject*(r: Redis, key: string): RedisStatus =
## Get debugging information about a key ## Get debugging information about a key
r.sendCommand("DEBUG", "OBJECT", key) r.sendCommand("DEBUG", "OBJECT", key)
return r.readStatus() return r.readStatus()
proc debugSegfault*(r: TRedis) = proc debugSegfault*(r: Redis) =
## Make the server crash ## Make the server crash
r.sendCommand("DEBUG", "SEGFAULT") r.sendCommand("DEBUG", "SEGFAULT")
proc flushall*(r: TRedis): TRedisStatus = proc flushall*(r: Redis): RedisStatus =
## Remove all keys from all databases ## Remove all keys from all databases
r.sendCommand("FLUSHALL") r.sendCommand("FLUSHALL")
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc flushdb*(r: TRedis): TRedisStatus = proc flushdb*(r: Redis): RedisStatus =
## Remove all keys from the current database ## Remove all keys from the current database
r.sendCommand("FLUSHDB") r.sendCommand("FLUSHDB")
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc info*(r: TRedis): TRedisString = proc info*(r: Redis): RedisString =
## Get information and statistics about the server ## Get information and statistics about the server
r.sendCommand("INFO") r.sendCommand("INFO")
return r.readBulkString() return r.readBulkString()
proc lastsave*(r: TRedis): TRedisInteger = proc lastsave*(r: Redis): RedisInteger =
## Get the UNIX time stamp of the last successful save to disk ## Get the UNIX time stamp of the last successful save to disk
r.sendCommand("LASTSAVE") r.sendCommand("LASTSAVE")
return r.readInteger() return r.readInteger()
@ -957,24 +957,24 @@ proc monitor*(r: TRedis) =
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
""" """
proc save*(r: TRedis) = proc save*(r: Redis) =
## Synchronously save the dataset to disk ## Synchronously save the dataset to disk
r.sendCommand("SAVE") r.sendCommand("SAVE")
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
proc shutdown*(r: TRedis) = proc shutdown*(r: Redis) =
## Synchronously save the dataset to disk and then shut down the server ## Synchronously save the dataset to disk and then shut down the server
r.sendCommand("SHUTDOWN") r.sendCommand("SHUTDOWN")
var s = "".TaintedString var s = "".TaintedString
r.socket.readLine(s) r.socket.readLine(s)
if s.string.len != 0: raise newException(ERedis, s.string) if s.string.len != 0: raise newException(RedisError, s.string)
proc slaveof*(r: TRedis, host: string, port: string) = proc slaveof*(r: Redis, host: string, port: string) =
## Make the server a slave of another instance, or promote it as master ## Make the server a slave of another instance, or promote it as master
r.sendCommand("SLAVEOF", host, port) r.sendCommand("SLAVEOF", host, port)
raiseNoOK(r.readStatus(), r.pipeline.enabled) raiseNoOK(r.readStatus(), r.pipeline.enabled)
iterator hPairs*(r: TRedis, key: string): tuple[key, value: string] = iterator hPairs*(r: Redis, key: string): tuple[key, value: string] =
## Iterator for keys and values in a hash. ## Iterator for keys and values in a hash.
var var
contents = r.hGetAll(key) contents = r.hGetAll(key)
@ -986,7 +986,7 @@ iterator hPairs*(r: TRedis, key: string): tuple[key, value: string] =
yield (k, i) yield (k, i)
k = "" k = ""
proc someTests(r: TRedis, how: TSendMode):seq[string] = proc someTests(r: Redis, how: SendMode):seq[string] =
var list:seq[string] = @[] var list:seq[string] = @[]
if how == pipelined: if how == pipelined:
@ -1007,10 +1007,10 @@ proc someTests(r: TRedis, how: TSendMode):seq[string] =
for r in res: for r in res:
list.add(r) list.add(r)
list.add(r.get("invalid_key")) list.add(r.get("invalid_key"))
list.add($(r.lpush("mylist","itema"))) list.add($(r.lPush("mylist","itema")))
list.add($(r.lpush("mylist","itemb"))) list.add($(r.lPush("mylist","itemb")))
r.ltrim("mylist",0,1) r.lTrim("mylist",0,1)
var p = r.lrange("mylist", 0, -1) var p = r.lRange("mylist", 0, -1)
for i in items(p): for i in items(p):
if not isNil(i): if not isNil(i):

View file

@ -6,20 +6,20 @@ discard """
#bug #1009 #bug #1009
type type
TAggRgba8* = array[4, Byte] TAggRgba8* = array[4, byte]
template R*(self: TAggRgba8): Byte = self[0] template R*(self: TAggRgba8): byte = self[0]
template G*(self: TAggRgba8): Byte = self[1] template G*(self: TAggRgba8): byte = self[1]
template B*(self: TAggRgba8): Byte = self[2] template B*(self: TAggRgba8): byte = self[2]
template A*(self: TAggRgba8): Byte = self[3] template A*(self: TAggRgba8): byte = self[3]
template `R=`*(self: TAggRgba8, val: Byte) = template `R=`*(self: TAggRgba8, val: byte) =
self[0] = val self[0] = val
template `G=`*(self: TAggRgba8, val: Byte) = template `G=`*(self: TAggRgba8, val: byte) =
self[1] = val self[1] = val
template `B=`*(self: TAggRgba8, val: Byte) = template `B=`*(self: TAggRgba8, val: byte) =
self[2] = val self[2] = val
template `A=`*(self: TAggRgba8, val: Byte) = template `A=`*(self: TAggRgba8, val: byte) =
self[3] = val self[3] = val
proc ABGR* (val: int| int64): TAggRgba8 = proc ABGR* (val: int| int64): TAggRgba8 =