summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRussell King <rmk@armlinux.org.uk>2021-04-16 15:18:57 +0100
committerRussell King <rmk@armlinux.org.uk>2021-04-16 15:18:57 +0100
commit250764731951b7a335e9425d1d939145ec129d54 (patch)
treecf16370c4de543d04536c5e288ea97472d515c27
parent2a19a0659cf3ce87ff51c20afe5bc16482e4bdf8 (diff)
resource: move the event formatting to object_v1_updateHEADmaster
Move the text/event-stream formatting to object_v1_update() from object_v1_send() to avoid the formatting and memory allocation overhead per client. Signed-off-by: Russell King <rmk@armlinux.org.uk>
-rw-r--r--resource.c42
1 files changed, 21 insertions, 21 deletions
diff --git a/resource.c b/resource.c
index c1473e7..085a66a 100644
--- a/resource.c
+++ b/resource.c
@@ -6,7 +6,7 @@
struct resource_object {
GList *client_list;
- char *str;
+ GString *string;
};
static struct resource_object position_object;
@@ -14,21 +14,12 @@ static struct resource_object signal_object;
static void object_v1_send(struct client *c, struct resource_object *obj)
{
- const char *str = obj->str;
- GString *s;
+ GString *string = obj->string;
- if (!str)
+ if (!string)
return;
- // Format the text/event-stream response
- // The double newline terminates this event
- // See https://www.html5rocks.com/en/tutorials/eventsource/basics/
- s = g_string_sized_new(1024);
- g_string_printf(s, "data:%s\n", str);
- g_string_append_c(s, '\n');
-
- respond_chunk(c, s);
- g_string_free(s, TRUE);
+ respond_chunk(c, string);
}
static int object_v1_get(struct client *c, struct resource *r)
@@ -62,14 +53,23 @@ static void object_v1_client_update(gpointer data, gpointer user_data)
static int object_v1_update(struct client *c, struct resource *r, const char *m)
{
struct resource_object *obj = r->data;
- char *n, *o;
-
- n = g_strdup(m);
- g_strchomp(n);
- o = obj->str;
- obj->str = n;
- if (o)
- g_free(o);
+ GString *string, *old;
+ char *n;
+
+ // Remove any trailing whitespace.
+ n = g_strchomp(g_strdup(m));
+
+ // Format the text/event-stream response
+ // We prefix the string with the "data:" tag in preparation for
+ // sending to via the text/event-stream connection.
+ // The double newline terminates this event
+ // See https://www.html5rocks.com/en/tutorials/eventsource/basics/
+ string = g_string_new(NULL);
+ g_string_printf(string, "data:%s\n\n", n);
+ old = obj->string;
+ obj->string = string;
+ g_string_free(old, TRUE);
+ g_free(n);
g_list_foreach(obj->client_list, object_v1_client_update, obj);