Nyx con Ejemplos

Listas en nyx-kv

nyx-kv soporta operaciones de listas compatibles con Redis: RPUSH/LPUSH agregan, LPOP/RPOP quitan, LRANGE lee un rango. Las listas se almacenan como arrays nativos con push/pop O(1).

Código

// nyx-kv lists -- LPUSH, LPOP, LRANGE, LLEN

fn resp_cmd(parts: Array) -> String {
    var sb: StringBuilder = StringBuilder.new()
    sb.append("*")
    sb.append(int_to_string(parts.length()))
    sb.append("\r\n")
    var i: int = 0
    while i < parts.length() {
        let p: String = parts[i]
        sb.append("$")
        sb.append(int_to_string(p.length()))
        sb.append("\r\n")
        sb.append(p)
        sb.append("\r\n")
        i = i + 1
    }
    return sb.to_string()
}

fn main() -> int {
    let fd: int = tcp_connect("127.0.0.1", 6380)
    if fd < 0 {
        print("connection failed")
        return 1
    }

    // Push items to a list (RPUSH appends to the right)
    tcp_write(fd, resp_cmd(["RPUSH", "tasks", "build", "test", "deploy"]))
    let push_reply: String = tcp_read_line(fd)
    print("RPUSH tasks -> " + push_reply.trim())

    // Get list length
    tcp_write(fd, resp_cmd(["LLEN", "tasks"]))
    let len_reply: String = tcp_read_line(fd)
    print("LLEN -> " + len_reply.trim())

    // LRANGE returns a RESP array. For brevity, just read the header.
    tcp_write(fd, resp_cmd(["LRANGE", "tasks", "0", "-1"]))
    let range_hdr: String = tcp_read_line(fd)
    print("LRANGE header -> " + range_hdr.trim())

    // LPOP removes from the left (FIFO queue pattern)
    tcp_write(fd, resp_cmd(["LPOP", "tasks"]))
    let pop_hdr: String = tcp_read_line(fd)
    let pop_val: String = tcp_read_line(fd)
    print("LPOP -> " + pop_val.trim())

    tcp_close(fd)
    return 0
}

Salida

RPUSH tasks -> :3
LLEN -> :3
LRANGE header -> *3
LPOP -> build

Explicación

Las listas en nyx-kv son estructuras doblemente enlazadas con push y pop O(1) en cualquiera de los extremos. RPUSH agrega al final; combinado con LPOP al inicio se obtiene una cola FIFO. Invirtiendo la dirección (LPUSH + LPOP) se obtiene una pila.

LRANGE key start stop devuelve un fragmento. Los índices negativos cuentan desde el final: -1 es el último elemento, así que LRANGE tasks 0 -1 devuelve todo. La respuesta es un array RESP — la primera línea es el encabezado *N\r\n, seguido de N bulk strings.

Las listas son ideales para colas de trabajos, líneas de tiempo de actividad, y pilas de deshacer. Como push/pop son operaciones atómicas del lado del servidor, múltiples clientes pueden encolar y desencolar de forma segura sin coordinación.

← Anterior Siguiente →

Source: examples/by-example/72-kv-lists.nx