Skip to content

Commit

Permalink
Implement (named) pipes
Browse files Browse the repository at this point in the history
  • Loading branch information
dermesser committed Nov 23, 2023
1 parent 5dc985e commit 023a885
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/internal_utils.cc
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ void UvHandleDeleter::del(uv_handle_t *handle) {
case UV_UDP:
delete (uv_udp_t *)handle;
break;
case UV_NAMED_PIPE:
delete (uv_pipe_t*)handle;
break;
case UV_TTY:
delete (uv_tty_t *)handle;
break;
Expand Down
17 changes: 17 additions & 0 deletions src/stream.cc
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,21 @@ void StreamBase::OutStreamAwaiter_::onOutStreamWrite(uv_write_t *write,
state->handle_->resume();
}

std::pair<StreamBase, StreamBase> pipe(uv_loop_t *loop) {
std::array<uv_file, 2> fds;
uv_pipe(fds.data(), UV_NONBLOCK_PIPE, UV_NONBLOCK_PIPE);

auto *in = new uv_pipe_t;
auto *out = new uv_pipe_t;

uv_pipe_init(loop, in, 0);
uv_pipe_init(loop, out, 0);

uv_pipe_open(in, fds[1]);
uv_pipe_open(out, fds[0]);

return std::make_pair(StreamBase{(uv_stream_t *)out},
StreamBase{(uv_stream_t *)in});
}

} // namespace uvco
4 changes: 4 additions & 0 deletions src/stream.h
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ class StreamBase {
};
};

// Creates a pipe pair. Data can be written to the second stream and read from
// the first.
std::pair<StreamBase, StreamBase> pipe(uv_loop_t*);

class TtyStream : public StreamBase {
public:
// Takes ownership of stream.
Expand Down
19 changes: 18 additions & 1 deletion test/misc_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@

#include "test_util.h"

#include <optional>
#include <string>

#include <gtest/gtest.h>

namespace {
using namespace uvco;
using namespace uvco;
}

TEST(NameResolutionTest, resolveGoogleDotCom) {
Expand Down Expand Up @@ -37,3 +40,17 @@ TEST(TtyTest, stdinTest) {
run_loop(setup);
EXPECT_EQ(counter, 2);
}

TEST(PipeTest, pipePingPong) {
auto setup = [&](uv_loop_t *loop) -> uvco::Promise<void> {
auto [read, write] = pipe(loop);

co_await write.write("Hello\n");
co_await write.write("Hello");
EXPECT_EQ(co_await read.read(), std::make_optional("Hello\nHello"));
co_await read.close();
co_await write.close();
};

run_loop(setup);
}

0 comments on commit 023a885

Please sign in to comment.