jsonrpc: use ccan/membuf instead of a string for our output buffer.

This isn't a big change, since we basically dump the entire JSON
resuly string into the membuf then write it out, but it's prep for the
next changes.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
This commit is contained in:
Rusty Russell 2018-10-19 11:47:48 +10:30
parent e9fcd120f8
commit 39f0dfb664
2 changed files with 26 additions and 5 deletions

View File

@ -31,6 +31,16 @@
#include <sys/types.h>
#include <sys/un.h>
/* Realloc helper for tal membufs */
static void *membuf_tal_realloc(struct membuf *mb,
void *rawelems, size_t newsize)
{
char *p = rawelems;
tal_resize(&p, newsize);
return p;
}
/* jcon and cmd have separate lifetimes: we detach them on either destruction */
static void destroy_jcon(struct json_connection *jcon)
{
@ -266,7 +276,11 @@ static void json_done(struct json_connection *jcon,
const char *json TAKES)
{
/* Queue for writing, and wake writer. */
jcon->outbuf = tal_strdup(jcon, json);
size_t len = strlen(json);
char *p = membuf_add(&jcon->outbuf, len);
memcpy(p, json, len);
if (taken(json))
tal_free(json);
io_wake(jcon);
/* Can be NULL if we failed to parse! */
@ -496,7 +510,7 @@ static struct io_plan *locked_write_json(struct io_conn *conn,
static struct io_plan *write_json_done(struct io_conn *conn,
struct json_connection *jcon)
{
jcon->outbuf = tal_free(jcon->outbuf);
membuf_consume(&jcon->outbuf, jcon->out_amount);
if (jcon->stop) {
log_unusual(jcon->log, "JSON-RPC shutdown");
@ -516,7 +530,9 @@ static struct io_plan *write_json_done(struct io_conn *conn,
static struct io_plan *write_json(struct io_conn *conn,
struct json_connection *jcon)
{
return io_write(conn, jcon->outbuf, strlen(jcon->outbuf),
jcon->out_amount = membuf_num_elems(&jcon->outbuf);
return io_write(conn,
membuf_elems(&jcon->outbuf), jcon->out_amount,
write_json_done, jcon);
}
@ -603,7 +619,8 @@ static struct io_plan *jcon_connected(struct io_conn *conn,
jcon->buffer = tal_arr(jcon, char, 64);
jcon->stop = false;
jcon->lock = io_lock_new(jcon);
jcon->outbuf = NULL;
membuf_init(&jcon->outbuf,
tal_arr(jcon, char, 64), 64, membuf_tal_realloc);
jcon->len_read = 0;
jcon->command = NULL;

View File

@ -4,6 +4,7 @@
#include <bitcoin/chainparams.h>
#include <ccan/autodata/autodata.h>
#include <ccan/list/list.h>
#include <ccan/membuf/membuf.h>
#include <common/io_lock.h>
#include <common/json.h>
@ -62,7 +63,10 @@ struct json_connection {
struct command *command;
/* Current command's output. */
const char *outbuf;
MEMBUF(char) outbuf;
/* How much we're writing right now. */
size_t out_amount;
struct io_lock *lock;
};