00001
00002
#ifndef GM_MISC_H
00003
#define GM_MISC_H
00004
00005
#include <sstream>
00006
#include <string>
00007
00008
#include "gm/debug.h"
00009
00010
typedef unsigned char byte;
00011
00012
namespace GNUMessenger
00013 {
00014
using namespace std;
00015
00016
00017
00019 static string
iToA(
long int candidate)
00020 {
00021 stringstream tmp;
00022 tmp << candidate;
00023
return tmp.str();
00024 }
00025
00034 template<
typename T >
inline void checked_array_delete(T * x)
00035 {
00036
typedef char type_must_be_complete[
sizeof(T)];
00037
delete [] x;
00038 }
00039
00048
template<
typename T>
00049 class scoped_array
00050 {
00051
private:
00052
00053 T * ptr;
00054
00055
scoped_array(
scoped_array const &);
00056
scoped_array & operator=(
scoped_array const &);
00057
00058
public:
00059
00060
typedef T element_type;
00061
00062
explicit scoped_array(T * p = 0) : ptr(p)
00063 {
00064 }
00065
00066 ~
scoped_array()
00067 {
00068
checked_array_delete(ptr);
00069 }
00070
00071
void reset(T * p = 0)
00072 {
00073
if (ptr != p)
00074 {
00075
checked_array_delete(ptr);
00076 ptr = p;
00077 }
00078 }
00079
00080 T & operator[](std::ptrdiff_t i)
const
00081 {
00082 GM_ASSERT(ptr != 0);
00083 GM_ASSERT(i >= 0);
00084
return ptr[i];
00085 }
00086
00087 T * get()
const
00088 {
00089
return ptr;
00090 }
00091
00092
void swap(
scoped_array & b)
00093 {
00094 T * tmp = b.
ptr;
00095 b.
ptr = ptr;
00096 ptr = tmp;
00097 }
00098
00099 };
00100
00101
template<
class T>
inline void swap(
scoped_array<T> & a,
scoped_array<T> & b)
00102 {
00103 a.
swap(b);
00104 }
00105
00110
template <
class T>
00111 class ReferenceCounted
00112 {
00113
public:
00115 ReferenceCounted(
const ReferenceCounted<T>& other)
00116 {
00117 m_refCount = other.
m_refCount;
00118 m_data = other.
m_data;
00119
00120 ref();
00121 }
00122
00123 T& operator =(
const ReferenceCounted<T>& other)
00124 {
00125 m_refCount = other.
m_refCount;
00126 m_data = other.
m_data;
00127
00128 ref();
00129
00130
return *m_data;
00131 }
00132
00133 ~ReferenceCounted()
00134 {
00135
if (deref() == 0)
00136 {
00137
delete m_data;
00138 }
00139 }
00140
00141
int deref()
00142 {
00143
return --*m_refCount;
00144 }
00145
int ref()
00146 {
00147
return ++*m_refCount;
00148 }
00149
00150
private:
00151 T * m_data;
00152
int* m_refCount;
00153 };
00154
00155
00156
00157
00158 }
00159
00160
#endif