forked from ravinet/mahimahi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathezio.cc
75 lines (57 loc) · 1.76 KB
/
ezio.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* -*-mode:c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
#include <unistd.h>
#include <cassert>
#include "ezio.hh"
#include "exception.hh"
using namespace std;
/* blocking write of entire buffer */
void writeall( const int fd, const string & buf )
{
auto it = buf.begin();
while ( it != buf.end() ) {
it = write_some( fd, it, buf.end() );
}
}
string::const_iterator write_some( const int fd,
const string::const_iterator & begin,
const string::const_iterator & end )
{
assert( end > begin );
ssize_t bytes_written = write( fd, &*begin, end - begin );
if ( bytes_written < 0 ) {
throw Exception( "write" );
} else if ( bytes_written == 0 ) {
throw Exception( "write returned 0" );
}
return begin + bytes_written;
}
string readall( const int fd, const size_t limit )
{
char buffer[ ezio::read_chunk_size ];
assert( limit > 0 );
ssize_t bytes_read = read( fd, &buffer, min( ezio::read_chunk_size, limit ) );
if ( bytes_read == 0 ) {
/* end of file = client has closed their side of connection */
return string();
} else if ( bytes_read < 0 ) {
throw Exception( "read" );
} else {
/* successful read */
return string( buffer, bytes_read );
}
}
long int myatoi( const string & str, const int base )
{
if ( str.empty() ) {
throw Exception( "Invalid integer string", "empty" );
}
char *end;
errno = 0;
long int ret = strtol( str.c_str(), &end, base );
if ( errno != 0 ) {
throw Exception( "strtol" );
} else if ( end != str.c_str() + str.size() ) {
throw Exception( "Invalid integer", str );
}
return ret;
}