Last active
December 22, 2015 09:28
-
-
Save huangzworks/6451594 to your computer and use it in GitHub Desktop.
将输入字符串转换成 Redis 命令请求协议
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
def p(s): | |
"将输入字符串转换成 Redis 命令请求协议" | |
# 将输入字符串分割为列表,并移除其中的空白字符串 | |
# 比如 "SET KEY VALUE" 分为 ["SET", "KEY", "VALUE"] | |
argv = s.split() | |
# 获取参数个数 | |
argc = len(argv) | |
# 协议开头的参数个数部分,例如 *5\r\n | |
output = "*{0}\r\n".format(argc) | |
# 协议的各个参数,例如 "$3\r\nSET\r\n" | |
for arg in argv: | |
output += "${len}\r\n{arg}\r\n".format(len=len(arg), arg=arg) | |
return output | |
if __name__ == "__main__": | |
# 无参数命令 | |
assert( | |
p("PING") == "*1\r\n$4\r\nPING\r\n" | |
) | |
# 单参数命令 | |
assert( | |
p("DEL KEY") == "*2\r\n$3\r\nDEL\r\n$3\r\nKEY\r\n" | |
) | |
# 两参数命令 | |
assert( | |
p("SET KEY VALUE") == "*3\r\n$3\r\nSET\r\n$3\r\nKEY\r\n$5\r\nVALUE\r\n" | |
) | |
# 多参数命令 | |
assert( | |
p("SADD FRUITS APPLE BANANA CHERRY") == \ | |
"*5\r\n" + \ | |
"$4\r\nSADD\r\n" +\ | |
"$6\r\nFRUITS\r\n" + \ | |
"$5\r\nAPPLE\r\n" + \ | |
"$6\r\nBANANA\r\n" + \ | |
"$6\r\nCHERRY\r\n" | |
) | |
# 参数带空格的命令 | |
assert( | |
p(" SET KEY VALUE ") == "*3\r\n$3\r\nSET\r\n$3\r\nKEY\r\n$5\r\nVALUE\r\n" | |
) | |
print("ALL TEST PASSED") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment