summaryrefslogtreecommitdiff
path: root/lib/common/Guards.h
diff options
context:
space:
mode:
authorBen Summers <ben@fluffy.co.uk>2005-10-14 08:50:54 +0000
committerBen Summers <ben@fluffy.co.uk>2005-10-14 08:50:54 +0000
commit99f8ce096bc5569adbfea1911dbcda24c28d8d8b (patch)
tree049c302161fea1f2f6223e1e8f3c40d9e8aadc8b /lib/common/Guards.h
Box Backup 0.09 with a few tweeks
Diffstat (limited to 'lib/common/Guards.h')
-rwxr-xr-xlib/common/Guards.h112
1 files changed, 112 insertions, 0 deletions
diff --git a/lib/common/Guards.h b/lib/common/Guards.h
new file mode 100755
index 00000000..6efc5614
--- /dev/null
+++ b/lib/common/Guards.h
@@ -0,0 +1,112 @@
+// --------------------------------------------------------------------------
+//
+// File
+// Name: Guards.h
+// Purpose: Classes which ensure things are closed/deleted properly when
+// going out of scope. Easy exception proof code, etc
+// Created: 2003/07/12
+//
+// --------------------------------------------------------------------------
+
+#ifndef GUARDS__H
+#define GUARDS__H
+
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <new>
+
+#include "CommonException.h"
+
+#include "MemLeakFindOn.h"
+
+template <int flags = O_RDONLY, int mode = (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)>
+class FileHandleGuard
+{
+public:
+ FileHandleGuard(const char *filename)
+ : mOSFileHandle(::open(filename, flags, mode))
+ {
+ if(mOSFileHandle < 0)
+ {
+ THROW_EXCEPTION(CommonException, OSFileOpenError)
+ }
+ }
+
+ ~FileHandleGuard()
+ {
+ if(mOSFileHandle >= 0)
+ {
+ Close();
+ }
+ }
+
+ void Close()
+ {
+ if(mOSFileHandle < 0)
+ {
+ THROW_EXCEPTION(CommonException, FileAlreadyClosed)
+ }
+ if(::close(mOSFileHandle) != 0)
+ {
+ THROW_EXCEPTION(CommonException, OSFileCloseError)
+ }
+ mOSFileHandle = -1;
+ }
+
+ operator int() const
+ {
+ return mOSFileHandle;
+ }
+
+private:
+ int mOSFileHandle;
+};
+
+template<typename type>
+class MemoryBlockGuard
+{
+public:
+ MemoryBlockGuard(int BlockSize)
+ : mpBlock(::malloc(BlockSize))
+ {
+ if(mpBlock == 0)
+ {
+ throw std::bad_alloc();
+ }
+ }
+
+ ~MemoryBlockGuard()
+ {
+ free(mpBlock);
+ }
+
+ operator type() const
+ {
+ return (type)mpBlock;
+ }
+
+ type GetPtr() const
+ {
+ return (type)mpBlock;
+ }
+
+ void Resize(int NewSize)
+ {
+ void *ptrn = ::realloc(mpBlock, NewSize);
+ if(ptrn == 0)
+ {
+ throw std::bad_alloc();
+ }
+ mpBlock = ptrn;
+ }
+
+private:
+ void *mpBlock;
+};
+
+#include "MemLeakFindOff.h"
+
+#endif // GUARDS__H
+