From 6ba9774460e35a1f8933c3192b39244ddec9ad55 Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Mon, 1 Jul 2019 20:49:25 +0100 Subject: MemStream error handling and move support --- libadhocutil/memstream.cpp | 41 +++++++++++++++++++++++++++++++- libadhocutil/memstream.h | 6 +++-- libadhocutil/unittests/testMemStream.cpp | 13 ++++++++++ 3 files changed, 57 insertions(+), 3 deletions(-) diff --git a/libadhocutil/memstream.cpp b/libadhocutil/memstream.cpp index a4ce95e..ec4b1bb 100644 --- a/libadhocutil/memstream.cpp +++ b/libadhocutil/memstream.cpp @@ -1,5 +1,8 @@ #include "memstream.h" #include +#include +#include +#include namespace AdHoc { MemStream::MemStream() : @@ -7,13 +10,49 @@ namespace AdHoc { len(0), strm(open_memstream(&buf, &len)) { + if (!strm) { + // LCOV_EXCL_START no sensible way to make open_memstream fail + throw SystemException("open_memstream failed", strerror(errno), errno); + // LCOV_EXCL_STOP + } + } + + MemStream::MemStream(MemStream && o) noexcept : + buf(o.buf), + len(o.len), + strm(o.strm) + { + o.buf = nullptr; + o.len = 0; + o.strm = nullptr; } MemStream::~MemStream() { - fclose(strm); + if (strm) { + fclose(strm); + } + // NOLINTNEXTLINE(hicpp-no-malloc) + free(buf); + } + + MemStream & MemStream::operator=(MemStream && o) noexcept + { + if (strm) { + fclose(strm); + } // NOLINTNEXTLINE(hicpp-no-malloc) free(buf); + + buf = o.buf; + len = o.len; + strm = o.strm; + + o.buf = nullptr; + o.len = 0; + o.strm = nullptr; + + return *this; } MemStream::operator FILE * () diff --git a/libadhocutil/memstream.h b/libadhocutil/memstream.h index 20b65fc..ba5f1fc 100644 --- a/libadhocutil/memstream.h +++ b/libadhocutil/memstream.h @@ -15,10 +15,12 @@ namespace AdHoc { ~MemStream(); MemStream(const MemStream &) = delete; - MemStream(MemStream &&) = delete; + /// Standard move constructor + MemStream(MemStream &&) noexcept; void operator=(const MemStream &) = delete; - void operator=(MemStream &&) = delete; + /// Standard move assignment + MemStream & operator=(MemStream &&) noexcept; /// Implicit conversion to use as FILE* for writes operator FILE * (); diff --git a/libadhocutil/unittests/testMemStream.cpp b/libadhocutil/unittests/testMemStream.cpp index b244b5e..79100ee 100644 --- a/libadhocutil/unittests/testMemStream.cpp +++ b/libadhocutil/unittests/testMemStream.cpp @@ -32,3 +32,16 @@ BOOST_AUTO_TEST_CASE(simple) BOOST_AUTO_TEST_SUITE_END(); +BOOST_AUTO_TEST_CASE(move_construct) +{ + MemStream ms1; + MemStream ms2(std::move(ms1)); +} + +BOOST_AUTO_TEST_CASE(move_assign) +{ + MemStream ms1; + MemStream ms2; + ms2 = std::move(ms1); +} + -- cgit v1.2.3