Back
+20 XP
Concept

Redis Clone Part 1: RESP Protocol Parser

Redis uses the Redis Serialization Protocol (RESP). Data items use byte markers: `+` for simple strings, `-` for errors, `:` for integers, `$` for bulk strings (`$len\r\nvalue\r\n`), and `*` for command arrays 🔴.

python
def parse_resp_array(payload: bytes):
    lines = payload.split(b"\r\n")
    if not lines[0].startswith(b"*"):
        return None
    count = int(lines[0][1:])
    tokens = []
    idx = 1
    for _ in range(count):
        length = int(lines[idx][1:])
        tokens.append(lines[idx + 1][:length].decode())
        idx += 2
    return tokens

cmd = b"*3\r\n$3\r\nSET\r\n$4\r\nname\r\n$5\r\nalice\r\n"
print(f"Decoded Redis Command: {parse_resp_array(cmd)} 🔴")

# 107. Redis Clone Part 1: RESP Protocol Parser Redis uses the Redis Serialization Protocol (RESP). Data items use byte markers: `+` for simple strings, `-` for errors, `:` for integers, `$` for bulk strings (`$len\r\nvalue\r\n`), and `*` for command arrays 🔴. ```python def parse_resp_array(payload: bytes): lines = payload.split(b"\r\n") if not lines[0].startswith(b"*"): return None count = int(lines[0][1:]) tokens = [] idx = 1 for _ in range(count): length = int(lines[idx][1:]) tokens.append(lines[idx + 1][:length].decode()) idx += 2 return tokens cmd = b"*3\r\n$3\r\nSET\r\n$4\r\nname\r\n$5\r\nalice\r\n" print(f"Decoded Redis Command: {parse_resp_array(cmd)} 🔴") ``` RESP is human-readable yet binary-safe because bulk strings declare their exact byte length upfront, allowing arbitrary binary payloads (like images or pickled bytes) without delimiter collisions ⚡! --- ### Question Which character prefix introduces a length-prefixed Bulk String in the RESP protocol? 🧠 - [ ] a. The dollar sign `$` prefix followed by byte count and `\r\n` 🔴 - [ ] b. The asterisk `*` prefix indicating an array sequence - [ ] c. The plus sign `+` prefix indicating an error code - [ ] d. The exclamation mark `!` prefix indicating an active transaction --- ### Challenge Implement `encode_bulk(s: str) -> bytes` returning `f"${len(s)}\r\n{s}\r\n".encode()`. Encode `'PING'` and print the byte string. 🎯 <details> <summary>Solution</summary> ```python def encode_bulk(s: str) -> bytes: return f"${len(s)}\r\n{s}\r\n".encode() print(encode_bulk('PING')) ``` </details>

Checkpoint

Which character prefix introduces a length-prefixed Bulk String in the RESP protocol? 🧠

Practice

Implement `encode_bulk(s: str) -> bytes` returning `f"${len(s)}\r\n{s}\r\n".encode()`. Encode `'PING'` and print the byte string. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks