2009-11-21 01:45:08 +00:00
|
|
|
#ifndef __AUTO_H__
|
|
|
|
#define __AUTO_H__
|
|
|
|
|
|
|
|
template <class T>
|
|
|
|
class auto_array
|
|
|
|
{
|
|
|
|
public:
|
|
|
|
auto_array() : _t(NULL) {}
|
|
|
|
auto_array(T *t) : _t(t) {}
|
|
|
|
~auto_array() { if (_t) delete []_t; }
|
|
|
|
|
|
|
|
|
|
|
|
T* release()
|
|
|
|
{ T *tmp = _t; _t = NULL; return tmp; }
|
|
|
|
|
|
|
|
T* get() const { return _t; }
|
|
|
|
operator T*() const { return _t; }
|
|
|
|
T& operator[](int index) { return _t[index]; }
|
|
|
|
|
2009-12-10 02:04:54 +00:00
|
|
|
void reset(T *t)
|
|
|
|
{
|
|
|
|
if (t == _t) return;
|
|
|
|
if (_t) delete[] _t;
|
|
|
|
_t = t;
|
|
|
|
}
|
|
|
|
|
2009-11-21 01:45:08 +00:00
|
|
|
private:
|
|
|
|
T *_t;
|
|
|
|
};
|
|
|
|
|
|
|
|
// ::close
|
|
|
|
#if defined(O_CREAT)
|
|
|
|
class auto_fd
|
|
|
|
{
|
|
|
|
public:
|
2009-11-23 22:36:05 +00:00
|
|
|
auto_fd(int fd = -1) : _fd(fd) { }
|
2009-11-21 01:45:08 +00:00
|
|
|
|
2009-11-23 22:36:05 +00:00
|
|
|
~auto_fd() { close(); }
|
2009-11-21 01:45:08 +00:00
|
|
|
|
|
|
|
int release()
|
|
|
|
{ int tmp = _fd; _fd = -1; return tmp; }
|
|
|
|
|
|
|
|
int get() const { return _fd; }
|
|
|
|
operator int() const { return _fd; }
|
2009-11-23 22:36:05 +00:00
|
|
|
|
|
|
|
void reset(int fd)
|
|
|
|
{
|
|
|
|
if (fd != _fd)
|
|
|
|
{
|
|
|
|
close();
|
|
|
|
_fd = fd;
|
|
|
|
}
|
|
|
|
}
|
2009-11-21 01:45:08 +00:00
|
|
|
|
|
|
|
private:
|
2009-11-23 22:36:05 +00:00
|
|
|
auto_fd& operator=(const auto_fd&);
|
|
|
|
|
|
|
|
void close()
|
|
|
|
{
|
|
|
|
if (_fd >= 0)
|
|
|
|
{
|
|
|
|
::close(_fd);
|
2009-11-24 04:46:29 +00:00
|
|
|
_fd = -1;
|
2009-11-23 22:36:05 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2009-11-21 01:45:08 +00:00
|
|
|
int _fd;
|
|
|
|
};
|
|
|
|
#endif
|
|
|
|
|
|
|
|
// ::mmap, :munmap
|
|
|
|
#if defined(MAP_FAILED)
|
|
|
|
class auto_map
|
|
|
|
{
|
|
|
|
public:
|
2009-12-11 03:28:51 +00:00
|
|
|
auto_map(void *addr, size_t size, int prot, int flags, int fd, off_t offset)
|
|
|
|
:
|
2009-11-21 01:45:08 +00:00
|
|
|
_size(size),
|
2009-12-11 03:28:51 +00:00
|
|
|
_map(::mmap(addr, size, prot, flags, fd, offset))
|
2009-11-21 01:45:08 +00:00
|
|
|
{ }
|
|
|
|
|
|
|
|
~auto_map()
|
|
|
|
{ if (_map != MAP_FAILED) ::munmap(_map, _size); }
|
|
|
|
|
|
|
|
void *release()
|
|
|
|
{ void *tmp = _map; _map = MAP_FAILED; return tmp; }
|
|
|
|
|
|
|
|
void *get() const { return _map; }
|
|
|
|
operator void *() const { return _map; }
|
|
|
|
|
|
|
|
private:
|
|
|
|
size_t _size;
|
|
|
|
void *_map;
|
|
|
|
};
|
|
|
|
#endif
|
|
|
|
|
|
|
|
|
|
|
|
#endif
|
|
|
|
|