chiark / gitweb /
socketio sink
authorRichard Kettlewell <rjk@greenend.org.uk>
Sun, 17 Nov 2013 11:22:33 +0000 (11:22 +0000)
committerRichard Kettlewell <rjk@greenend.org.uk>
Sun, 17 Nov 2013 11:22:33 +0000 (11:22 +0000)
lib/sink.c
lib/sink.h

index 84b9c2564ee987127fa31ef552d5c119037b800a..152b7dceb0516fd0da82d02adfb35a8695557f42 100644 (file)
@@ -26,6 +26,7 @@
 
 #include "mem.h"
 #include "vector.h"
+#include "socketio.h"
 #include "log.h"
 #include "sink.h"
 #include "printf.h"
@@ -185,6 +186,47 @@ struct sink *sink_error(void) {
   return s;
 }
 
+/* socket sink *************************************************************/
+
+/** @brief Sink that writes to a socket handle */
+struct socketio_sink {
+  /** @brief Base member */
+  struct sink s;
+
+  struct socketio *sio;
+};
+
+static int sink_socketio_flush(struct sink *s) {
+  struct socketio_sink *ss = (struct socketio_sink *)s;
+  return socketio_flush(ss->sio);
+}
+
+/** @brief Write callback for @ref stdio_sink */
+static int sink_socketio_write(struct sink *s, const void *buffer, int nbytes) {
+  struct socketio_sink *ss = (struct socketio_sink *)s;
+  return socketio_write(ss->sio, buffer, nbytes);
+}
+
+static int sink_socketio_error(struct sink *s) {
+  struct socketio_sink *ss = (struct socketio_sink *)s;
+  return socketio_error(ss->sio);
+}
+
+/** @brief Create a sink that writes to a socket
+ * @param sio Socket IO context
+ * @return Pointer to new sink
+ */
+struct sink *sink_socketio(struct socketio *sio) {
+  struct socketio_sink *s = xmalloc(sizeof *s);
+
+  s->s.write = sink_socketio_write;
+  s->s.flush = sink_socketio_flush;
+  s->s.error = sink_socketio_error;
+  s->s.eclass = ec_native;
+  s->sio = sio;
+  return &s->s;
+}
+
 /*
 Local Variables:
 c-basic-offset:2
index d3ab9990d61fc24db172a721976fb132336ea864..ff763a69fe9e7e27526602e1517cb935ffa68b2d 100644 (file)
@@ -25,6 +25,7 @@
 #include <stdarg.h>
 
 struct dynstr;
+struct socketio;
 
 /** @brief Sink type
  *
@@ -70,6 +71,9 @@ struct sink *sink_discard(void);
 struct sink *sink_error(void);
 /* return a sink which fails all writes */
 
+struct sink *sink_socketio(struct socketio *sio);
+/* return a sink which writes to a socket */
+
 int sink_vprintf(struct sink *s, const char *fmt, va_list ap);
 int sink_printf(struct sink *s, const char *fmt, ...)
   attribute((format (printf, 2, 3)));