stream: add printf()-style covenience functions
authorMartin Willi <martin@revosec.ch>
Thu, 27 Jun 2013 09:46:41 +0000 (11:46 +0200)
committerMartin Willi <martin@revosec.ch>
Thu, 18 Jul 2013 14:00:28 +0000 (16:00 +0200)
src/libstrongswan/networking/streams/stream.c
src/libstrongswan/networking/streams/stream.h

index 43a6bd4..144792e 100644 (file)
@@ -33,6 +33,11 @@ struct private_stream_t {
         * Underlying socket
         */
        int fd;
+
+       /**
+        * FILE* for convenience functions, or NULL
+        */
+       FILE *file;
 };
 
 METHOD(stream_t, read_, ssize_t,
@@ -91,10 +96,44 @@ METHOD(stream_t, write_, ssize_t,
        }
 }
 
+METHOD(stream_t, vprint, int,
+       private_stream_t *this, char *format, va_list ap)
+{
+       if (!this->file)
+       {
+               this->file = fdopen(this->fd, "w+");
+               if (!this->file)
+               {
+                       return -1;
+               }
+       }
+       return vfprintf(this->file, format, ap);
+}
+
+METHOD(stream_t, print, int,
+       private_stream_t *this, char *format, ...)
+{
+       va_list ap;
+       int ret;
+
+       va_start(ap, format);
+       ret = vprint(this, format, ap);
+       va_end(ap);
+
+       return ret;
+}
+
 METHOD(stream_t, destroy, void,
        private_stream_t *this)
 {
-       close(this->fd);
+       if (this->file)
+       {
+               fclose(this->file);
+       }
+       else
+       {
+               close(this->fd);
+       }
        free(this);
 }
 
@@ -109,6 +148,8 @@ stream_t *stream_create_from_fd(int fd)
                .public = {
                        .read = _read_,
                        .write = _write_,
+                       .print = _print,
+                       .vprint = _vprint,
                        .destroy = _destroy,
                },
                .fd = fd,
index 219e16a..bcf7fb4 100644 (file)
@@ -65,6 +65,24 @@ struct stream_t {
        ssize_t (*write)(stream_t *this, void *buf, size_t len, bool block);
 
        /**
+        * printf() convenience function for this stream.
+        *
+        * @param format        printf format string
+        * @param ...           argument list for format string
+        * @return                      number of characters written, negative on error
+        */
+       int (*print)(stream_t *this, char *format, ...);
+
+       /**
+        * vprintf() convenience function for this stream.
+        *
+        * @param format        printf format string
+        * @param ap            argument list for format string
+        * @return                      number of characters written, negative on error
+        */
+       int (*vprint)(stream_t *this, char *format, va_list ap);
+
+       /**
         * Destroy a stream_t.
         */
        void (*destroy)(stream_t *this);