]> git.tdb.fi Git - libs/core.git/blob - source/io/handle.cpp
Some fixes for eof handling in Memory
[libs/core.git] / source / io / handle.cpp
1 #include <cerrno>
2 #include <unistd.h>
3 #include <msp/core/systemerror.h>
4 #include "handle.h"
5 #include "handle_private.h"
6
7 namespace Msp {
8 namespace IO {
9
10 Handle::Handle():
11         priv(new Private)
12 { }
13
14 Handle::Handle(const Handle &other):
15         priv(new Private)
16 {
17         priv->handle = other.priv->handle;
18 }
19
20 Handle &Handle::operator=(const Handle &other)
21 {
22         priv->handle = other.priv->handle;
23         return *this;
24 }
25
26 Handle::~Handle()
27 {
28         delete priv;
29 }
30
31 Handle::operator const void *() const
32 {
33 #ifdef WIN32
34         return priv->handle!=INVALID_HANDLE_VALUE ? this : 0;
35 #else
36         return priv->handle!=-1 ? this : 0;
37 #endif
38 }
39
40
41 Handle::Private::Private():
42 #ifdef WIN32
43         handle(INVALID_HANDLE_VALUE)
44 #else
45         handle(-1)
46 #endif
47 { }
48
49 Handle::Private &Handle::Private::operator=(H h)
50 {
51         handle = h;
52         return *this;
53 }
54
55
56 unsigned sys_read(Handle &handle, char *buf, unsigned size)
57 {
58 #ifdef WIN32
59         DWORD ret;
60         if(ReadFile(*handle, buf, size, &ret, 0)==0)
61                 throw system_error("ReadFile");
62 #else
63         int ret = read(*handle, buf, size);
64         if(ret==-1)
65         {
66                 if(errno==EAGAIN)
67                         return 0;
68                 else
69                         throw system_error("read");
70         }
71 #endif
72
73         return ret;
74 }
75
76 unsigned sys_write(Handle &handle, const char *buf, unsigned size)
77 {
78 #ifdef WIN32
79         DWORD ret;
80         if(WriteFile(*handle, buf, size, &ret, 0)==0)
81                 throw system_error("WriteFile");
82 #else
83         int ret = write(*handle, buf, size);
84         if(ret==-1)
85         {
86                 if(errno==EAGAIN)
87                         return 0;
88                 else
89                         throw system_error("write");
90         }
91 #endif
92
93         return ret;
94 }
95
96 void sys_close(Handle &handle)
97 {
98 #ifdef WIN32
99         CloseHandle(*handle);
100 #else
101         close(*handle);
102 #endif
103 }
104
105 } // namespace IO
106 } // namespace Msp