fixed a bug in util::read_all() function and added a test for it (#23)

This commit is contained in:
mohamedAlaaK 2019-01-03 18:29:49 +02:00 committed by Arun Muralidharan
parent 7ebcd80c05
commit d74481c564
2 changed files with 18 additions and 4 deletions

View File

@ -306,9 +306,8 @@ namespace util
*
* NOTE: `class Buffer` is a exposed public class. See below.
*/
template <typename Buffer>
// Requires Buffer to be of type class Buffer
static inline int read_all(int fd, Buffer& buf)
static inline int read_all(int fd, std::vector<char>& buf)
{
auto buffer = buf.data();
int total_bytes_read = 0;
@ -329,8 +328,8 @@ namespace util
//update the buffer pointer
buffer = buf.data();
buffer += rd_bytes;
total_bytes_read += rd_bytes;
buffer += total_bytes_read;
} else { // Partial data ? Continue reading
total_bytes_read += rd_bytes;
@ -338,6 +337,7 @@ namespace util
break;
}
}
buf.erase(buf.begin()+total_bytes_read, buf.end()); // remove extra nulls
return total_bytes_read;
}

View File

@ -51,6 +51,19 @@ void test_sleep()
std::cout << "Sleep ended: ret code = " << p.retcode() << std::endl;
}
void test_read_all()
{
Popen p = Popen({"echo","12345678"}, output{PIPE});
std::vector<char> buf(6);
int rbytes = util::read_all(fileno(p.output()), buf);
std::string out(buf.begin(), buf.end());
assert(out == "12345678\n" && rbytes == 9); // echo puts a new line at the end of output
std::cout<<"read_all() succeeded"<<std::endl;
}
int main() {
test_exename();
test_input();
@ -58,5 +71,6 @@ int main() {
test_easy_piping();
test_shell();
test_sleep();
test_read_all();
return 0;
}