From 8b5e75c69ff7b1c6928cb0f389ee005d5ec35dc5 Mon Sep 17 00:00:00 2001 From: Martin Haefner Date: Sat, 6 Feb 2016 21:53:28 +0100 Subject: [PATCH] renamed namespace ipc to dbus --- CMakeLists.txt | 1 - README | 9 +- examples/CMakeLists.txt | 4 - examples/alpha/io2.cpp | 955 -------- examples/alpha/pool.cpp | 90 - examples/alpha/sigslot2.cpp | 641 ----- examples/alpha/store.cpp | 408 --- examples/cmdline/CMakeLists.txt | 5 - examples/cmdline/cmdline.cpp | 267 -- examples/cmdline/commands.cpp | 105 - examples/inifile/CMakeLists.txt | 2 - examples/inifile/inifile.cpp | 106 - examples/inifile/test.ini | 35 - examples/ipc2/CMakeLists.txt | 29 - examples/ipc2/README | 33 - examples/ipc2/TODO | 100 - examples/ipc2/attributes.cpp | 190 -- examples/ipc2/bench.txt | 50 - examples/ipc2/benchmark.cpp | 272 -- examples/ipc2/broker.cpp | 240 -- examples/ipc2/calculator.h | 30 - examples/ipc2/calculator_clnt.cpp | 115 - examples/ipc2/calculator_clnt1.cpp | 105 - examples/ipc2/calculator_cpu.cpp | 54 - examples/ipc2/except.cpp | 126 - examples/ipc2/ipc2.cpp | 236 -- examples/ipc2/ipc2_e.cpp | 290 --- examples/ipc2/session.cpp | 156 -- examples/ipc2/simple.cpp | 153 -- examples/misc/CMakeLists.txt | 2 - examples/misc/intrusive_list.cpp | 90 - examples/misc/safe_ptr.cpp | 333 --- examples/misc/tribool.cpp | 26 - examples/misc/typelist.cpp | 12 - examples/misc/variant.cpp | 118 - include/simppl/attribute.h | 4 +- include/simppl/bind_adapter.h | 128 - include/simppl/blocking.h | 40 +- include/simppl/brokerclient.h | 42 - include/simppl/callstate.h | 4 +- include/simppl/clientside.h | 12 +- include/simppl/cmdline.h | 2179 ----------------- include/simppl/cmdline_extensionpoint.h | 249 -- include/simppl/connectionstate.h | 4 +- include/simppl/detail/basicinterface.h | 4 +- include/simppl/detail/clientresponseholder.h | 4 +- include/simppl/detail/is_vector.h | 4 +- include/simppl/detail/parented.h | 8 +- include/simppl/detail/serialization.h | 44 +- include/simppl/detail/serverholder.h | 4 +- .../simppl/detail/serverrequestbasesetter.h | 4 +- include/simppl/detail/serverresponseholder.h | 4 +- include/simppl/detail/util.h | 4 +- include/simppl/detail/validation.h | 6 +- include/simppl/dispatcher.h | 4 +- include/simppl/error.h | 4 +- include/simppl/function_traits.h | 311 --- include/simppl/inifile.h | 778 ------ include/simppl/inifile_extensionpoint.h | 178 -- include/simppl/interface.h | 14 +- include/simppl/serialization.h | 4 +- include/simppl/serverrequestdescriptor.h | 4 +- include/simppl/serverside.h | 8 +- include/simppl/skeleton.h | 4 +- include/simppl/skeletonbase.h | 4 +- include/simppl/stub.h | 6 +- include/simppl/stubbase.h | 4 +- include/simppl/timeout.h | 4 +- include/simppl/tribool.h | 108 - src/clientresponseholder.cpp | 2 +- src/dispatcher.cpp | 26 +- src/error.cpp | 4 +- src/serialization.cpp | 4 +- src/serverrequestdescriptor.cpp | 4 +- src/serverresponseholder.cpp | 4 +- src/serverside.cpp | 4 +- src/skeletonbase.cpp | 4 +- src/stubbase.cpp | 4 +- src/timeout.cpp | 4 +- src/util.cpp | 4 +- tests/CMakeLists.txt | 10 +- ...ipc2_async_server.cpp => async_server.cpp} | 38 +- tests/{ipc2_attributes.cpp => attributes.cpp} | 24 +- tests/{ipc2_errors.cpp => errors.cpp} | 30 +- tests/{ipc2_simple.cpp => simple.cpp} | 56 +- tests/{ipc2_timeout.cpp => timeout.cpp} | 88 +- 86 files changed, 261 insertions(+), 9620 deletions(-) delete mode 100644 examples/CMakeLists.txt delete mode 100644 examples/alpha/io2.cpp delete mode 100644 examples/alpha/pool.cpp delete mode 100644 examples/alpha/sigslot2.cpp delete mode 100644 examples/alpha/store.cpp delete mode 100644 examples/cmdline/CMakeLists.txt delete mode 100644 examples/cmdline/cmdline.cpp delete mode 100644 examples/cmdline/commands.cpp delete mode 100644 examples/inifile/CMakeLists.txt delete mode 100644 examples/inifile/inifile.cpp delete mode 100644 examples/inifile/test.ini delete mode 100644 examples/ipc2/CMakeLists.txt delete mode 100644 examples/ipc2/README delete mode 100644 examples/ipc2/TODO delete mode 100644 examples/ipc2/attributes.cpp delete mode 100644 examples/ipc2/bench.txt delete mode 100644 examples/ipc2/benchmark.cpp delete mode 100644 examples/ipc2/broker.cpp delete mode 100644 examples/ipc2/calculator.h delete mode 100644 examples/ipc2/calculator_clnt.cpp delete mode 100644 examples/ipc2/calculator_clnt1.cpp delete mode 100644 examples/ipc2/calculator_cpu.cpp delete mode 100644 examples/ipc2/except.cpp delete mode 100644 examples/ipc2/ipc2.cpp delete mode 100644 examples/ipc2/ipc2_e.cpp delete mode 100644 examples/ipc2/session.cpp delete mode 100644 examples/ipc2/simple.cpp delete mode 100644 examples/misc/CMakeLists.txt delete mode 100644 examples/misc/intrusive_list.cpp delete mode 100644 examples/misc/safe_ptr.cpp delete mode 100644 examples/misc/tribool.cpp delete mode 100644 examples/misc/typelist.cpp delete mode 100644 examples/misc/variant.cpp delete mode 100644 include/simppl/bind_adapter.h delete mode 100644 include/simppl/brokerclient.h delete mode 100644 include/simppl/cmdline.h delete mode 100644 include/simppl/cmdline_extensionpoint.h delete mode 100644 include/simppl/function_traits.h delete mode 100644 include/simppl/inifile.h delete mode 100644 include/simppl/inifile_extensionpoint.h delete mode 100644 include/simppl/tribool.h rename tests/{ipc2_async_server.cpp => async_server.cpp} (70%) rename tests/{ipc2_attributes.cpp => attributes.cpp} (86%) rename tests/{ipc2_errors.cpp => errors.cpp} (73%) rename tests/{ipc2_simple.cpp => simple.cpp} (76%) rename tests/{ipc2_timeout.cpp => timeout.cpp} (65%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 802c7f1..49f2a24 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9,5 +9,4 @@ include_directories(/usr/include/dbus-1.0) include_directories(/usr/lib/arm-linux-gnueabihf/dbus-1.0/include) add_subdirectory(src) -add_subdirectory(examples) add_subdirectory(tests) diff --git a/README b/README index 4b84ffd..8897e9b 100644 --- a/README +++ b/README @@ -4,7 +4,7 @@ in the following functional domains: * generative commandline parser framework * generative inifile parser framework - * generative service-oriented IPC library introducing a C++ embedded DSL for + * generative DBus wrapper introducing a C++ embedded DSL for the definition of service interfaces and serializable data structures. @@ -29,13 +29,6 @@ Status: The parser frameworks should do their work. I use it sucessfully in my own projects. -The IPC library is feature complete and works as far as I already have -written tests for it. There are certainly some problems with resource -cleanup and services shutdown but if you have a project that need IPC -and you just once connect your binaries through the simppl library you -should get a system that is doing well. I plan to spend some time in -resource tracking so one day, it should really become 'production ready'. - CopyLeft: diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt deleted file mode 100644 index 26ee019..0000000 --- a/examples/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -add_subdirectory(ipc2) -add_subdirectory(cmdline) -add_subdirectory(inifile) -add_subdirectory(misc) diff --git a/examples/alpha/io2.cpp b/examples/alpha/io2.cpp deleted file mode 100644 index 943501d..0000000 --- a/examples/alpha/io2.cpp +++ /dev/null @@ -1,955 +0,0 @@ -#include -#include - -#include -#include -#include -#include - -template -struct if_ -{ - typedef TrueT type; -}; - -template -struct if_ -{ - typedef FalseT type; -}; - -// Policies: do not loop on EINTR on blocking functions, but loop on asynchronous function calls since there data -// should be ready to read so we do not block infinitely if we return to the action due to an EINTR. - -// unix sockets -#include - -// ip sockets -#include -#include - -#include - -#define DEFAULT_BACKLOG 10 - - -// forward decl -struct Dispatcher; - - -struct NormalDescriptorTraits -{ - typedef int fd_type; - enum { Invalid = -1 }; -}; - - -namespace IPv4 -{ - -struct EndpointTraits -{ - typedef struct sockaddr_in addr_type; - - enum { - Domain = PF_INET, - AddressFamily = AF_INET - }; -}; - -} // namespace IPv4 - - -namespace Unix -{ - -struct EndpointTraits -{ - typedef struct sockaddr_un addr_type; - - enum { - Domain = PF_UNIX, - AddressFamily = AF_UNIX - }; -}; - -} // namespace Unix - - -struct StreamTraits -{ - enum { socket_type = SOCK_STREAM }; -}; - - -struct DatagramTraits -{ - enum { socket_type = SOCK_DGRAM }; -}; - - -template -struct ReadEventTraits -{ - typedef void* buffer_type; - typedef IOCompletionRoutineT completion_routine_type; - - enum { poll_mask = POLLIN }; -}; - - -template -struct WriteEventTraits -{ - typedef const void* buffer_type; - typedef IOCompletionRoutineT completion_routine_type; - - enum { poll_mask = POLLOUT }; -}; - - -struct AcceptEventTraits -{ - enum { poll_mask = POLLIN }; -}; - - -template -struct Device : TraitsT -{ - explicit - Device(Dispatcher& dispatcher) - : dispatcher_(&dispatcher) - , fd_(TraitsT::Invalid) - { - // NOOP - } - - Device() - : dispatcher_(0) - , fd_(TraitsT::Invalid) - { - // NOOP - } - - Dispatcher* dispatcher_; - typename TraitsT::fd_type fd_; -}; - - -struct EventBase -{ - virtual ~EventBase() { /* NOOP */ } - virtual void eval(int fd) = 0; -}; - - -template -struct IOEvent : EventBase, TraitsT -{ - IOEvent(typename TraitsT::buffer_type buf, size_t len, typename TraitsT::completion_routine_type func) - : buf_(buf) - , len_(len) - , func_(func) - { - // NOOP - } - - typedef TraitsT traits_type; - - typename traits_type::buffer_type buf_; - size_t len_; - - typename traits_type::completion_routine_type func_; -}; - - -template -struct ReadEvent : IOEvent > -{ - typedef IOEvent > base_type; - - ReadEvent(typename base_type::buffer_type buf, size_t len, IOCompletionRoutineT func) - : base_type(buf, len, func) - { - // NOOP - } - - void eval(int fd) - { - ssize_t len = 0; - - do - { - len = ::recv(fd, this->buf_, this->len_, MSG_NOSIGNAL); - } - while (len < 0 && errno == EINTR); - - // FIXME better return enums (errnos) here instead of bool - this->func_(len, len >= 0); - } -}; - - -template -struct WriteEvent : IOEvent > -{ - typedef IOEvent > base_type; - - WriteEvent(typename base_type::buffer_type buf, size_t len, IOCompletionRoutineT func) - : base_type(buf, len, func) - { - // NOOP - } - - int getPollMask() const - { - return POLLOUT | POLLHUP; - } - - void eval(int fd) - { - ssize_t len = 0; - - do - { - len = ::send(fd, base_type::buf_, base_type::len_, MSG_NOSIGNAL); - } - while (len < 0 && errno == EINTR); - - // FIXME better return enums (errnos) here instead of bool - this->func_(len, len >= 0); - } -}; - - -template -struct AcceptEvent : public EventBase -{ - typedef AcceptEventTraits traits_type; - - inline - AcceptEvent(DeviceT& dev, AcceptCompletionRoutineT func) - : dev_(dev) - , func_(func) - { - // NOOP - } - - void eval(int fd) - { - typename DeviceT::endpoint_type address; - socklen_t len = sizeof(typename DeviceT::endpoint_type::traits_type::addr_type); - do - { - dev_.fd_ = ::accept(fd, (struct sockaddr*)&address.address_, &len); - } - while(dev_.fd_ < 0 && errno == EINTR); - - func_(address, dev_.fd_ >= 0); - } - - DeviceT& dev_; - AcceptCompletionRoutineT func_; -}; - - -struct Dispatcher // mixin the event loop via mixin interface... -{ - Dispatcher(size_t capa = 128) - : max_(0) - , capa_(capa) - , fds_table_(new pollfd[capa_]) - , events_table_(new EventBase*[capa_]) - , finished_(false) - , rc_(0) - { - for (int i=0; i - void enqueueEvent(int fd, EventT* evt) - { - int pos = -1; - - for(int i=0; i= max_); - pos = max_; - ++max_; - } - - fds_table_[pos].fd = fd; - fds_table_[pos].events = EventT::traits_type::poll_mask; - events_table_[pos] = evt; - } - - - template - void removeEvent(int fd) - { - for (int i=0; i 0) - { - for(int i=0; i= 0 && (fds_table_[i].revents & (POLLIN|POLLOUT))) - { - events_table_[i]->eval(fds_table_[i].fd); - - clearSlot(i); - } - } - } - else if (ret < 0) - { - if (errno == EINTR) - ret = 0; - } - - return ret; - } - - int run() - { - int ret = 0; - - while(!finished_ && ret >= 0) - { - ret = this->poll(1000); - } - - if (!finished_ && ret < 0) - rc_ = -1; - - return rc_; - } - - void stop(int rc = 0) - { - finished_ = true; - rc_ = rc; - } - - size_t max_; - size_t capa_; - - pollfd* fds_table_; - EventBase** events_table_; - - bool finished_; - int rc_; -}; - - -typedef struct sockaddr sockaddr_t; - - -template -struct Endpoint -{ - template - friend struct AcceptEvent; - - typedef TraitsT traits_type; - - // do not initialize the endpoint - Endpoint() - { - // NOOP - } - - // zero out the endpoint - explicit - inline - Endpoint(bool /*zero*/) - { - ::memset(&address_, 0, sizeof(address_)); - } - - inline - operator const sockaddr_t*() const - { - return (const struct sockaddr*)&address_; - } - - inline - operator sockaddr_t*() - { - return (struct sockaddr*)&address_; - } - - inline - InheriterT& operator=(const typename traits_type::addr_type& rhs) - { - address_ = rhs; - return *(InheriterT*)this; - } - - inline - socklen_t getSockAddrSize() const - { - return sizeof(address_); - } - -protected: - typename traits_type::addr_type address_; -}; - - -namespace IPv4 -{ - -struct Endpoint : public ::Endpoint, EndpointTraits -{ - // construct an uninitialized (invalid) endpoint - inline - Endpoint() - : ::Endpoint(true) - { - // NOOP - } - -public: - - Endpoint(const char* addr, int port) - : ::Endpoint() - { - address_.sin_family = EndpointTraits::AddressFamily; - inet_aton(addr, &address_.sin_addr); - address_.sin_port = htons(port); - } - - // any address - explicit - Endpoint(int port) - : ::Endpoint() - { - address_.sin_family = EndpointTraits::AddressFamily; - address_.sin_addr.s_addr = INADDR_ANY; - address_.sin_port = htons(port); - } - - inline - int getPort() const - { - return ntohs(address_.sin_port); - } - - using ::Endpoint::operator=; -}; - -} // namespace IPv4 - - -namespace Unix -{ - -struct Endpoint : public ::Endpoint, EndpointTraits -{ - // construct an uninitialized (invalid) endpoint - inline - Endpoint() - : ::Endpoint(true) - { - // NOOP - } - - Endpoint(const char* name) - : ::Endpoint() - { - address_.sun_family = EndpointTraits::AddressFamily; - memset(address_.sun_path, 0, sizeof(address_.sun_path)); - strncpy(address_.sun_path, name, sizeof(address_.sun_path) - 1); - } -}; - -} // namespace Unix - - -template -struct DatagramSocketMixin -{ - ssize_t write_some_to(const AddressT& to, const void* buf, size_t len) - { - return ::sendto(((InheriterT*)this)->fd_, buf, len, MSG_NOSIGNAL, to, to.getSockAddrSize()); - } - - ssize_t read_some_from(AddressT& from, void* buf, size_t len) - { - socklen_t slen = from.getSockAddrSize(); - return ::recvfrom(((InheriterT*)this)->fd_, buf, len, MSG_NOSIGNAL, from, &slen); - } -}; - - -struct EmptySocketMixin -{ -}; - - -template -struct Socket - : Device - , TraitsT - , if_< TraitsT::socket_type == (int)SOCK_DGRAM, - DatagramSocketMixin > - , EmptySocketMixin>::type -{ - typedef Device base_type; - typedef AddressT endpoint_type; - - explicit - Socket(Dispatcher& dispatcher) - : base_type(dispatcher) - { - // NOOP - } - - Socket() - : base_type() - { - // NOOP - } - - ~Socket() - { - (void)close(); - } - - bool open() - { - fd_ = ::socket(AddressT::Domain, TraitsT::socket_type, 0); - } - - bool close() - { - int rc = 0; - - if (fd_) - { - // TODO keep flag if something is registered on the event loop and remove the events only if necessary - if (this->dispatcher_) - this->dispatcher_->removeAll(fd_); - - do - { - rc = ::close(fd_); - } - while(rc < 0 && errno == EINTR); - } - - return rc == 0; - } - - bool is_open() const - { - return fd_ != Invalid; - } - - operator const void*() const - { - return is_open() ? this : 0; - } - - bool connect(const AddressT& addr) - { - struct sockaddr* tmp = addr; - return connect(fd_, tmp, addr.getSockAddrSize()); - } - -#if FIXME - template - void async_connect(const AddressT& addr, ConnectCompletionRoutineT func) - { - assert(this->dispatcher_); - // set socket nonblocking - // call connect - // evaluate return state and probably enqueue event - this->dispatcher_->enqueueEvent(fd_, new ConnectEvent(addr, func)); - } -#endif - - template - void async_read_some(void* buf, size_t len, IOCompletionRoutineT func) - { - // FIXME use member pointer to store that can hold a readEvent. This store should - // keep in mind if the event is already enqueued and return false then... - assert(this->dispatcher_); - this->dispatcher_->enqueueEvent(fd_, new ReadEvent(buf, len, func)); - } - - template - void async_write_some(const void* buf, size_t len, IOCompletionRoutineT func) - { - assert(this->dispatcher_); - this->dispatcher_->enqueueEvent(fd_, new WriteEvent(buf, len, func)); - } - - void cancel_read() - { - assert(this->dispatcher_); - this->dispatcher_->template removeEvent >(fd_); - } - - void cancel_write() - { - assert(this->dispatcher_); - this->dispatcher_->template removeEvent >(fd_); - } - - ssize_t read_some(void* buf, size_t len) - { - return ::recv(fd_, buf, len, MSG_NOSIGNAL); - } - - ssize_t write_some(const void* buf, size_t len) - { - return ::send(fd_, buf, len, MSG_NOSIGNAL); - } -}; - - -template -struct StreamSocket : public Socket -{ - explicit - StreamSocket(Dispatcher& dispatcher) - : Socket(dispatcher) - { - // NOOP - } - - StreamSocket() - : Socket() - { - // NOOP - } -}; - - -template -struct DatagramSocket : public Socket -{ - explicit - DatagramSocket(Dispatcher& dispatcher) - : Socket(dispatcher) - { - // NOOP - } - - DatagramSocket() - : Socket() - { - // NOOP - } -}; - - -namespace IPv4 -{ - -typedef ::StreamSocket StreamSocket; -typedef ::DatagramSocket DatagramSocket; - -} // namespace IPv4 - - -namespace Unix -{ - -typedef ::StreamSocket StreamSocket; -typedef ::DatagramSocket DatagramSocket; - -} // namespace Unix - -template -struct Acceptor : private Socket -{ - typedef Socket base_type; - - using Socket::fd_; - - Acceptor() - : base_type() - { - base_type::open(); - } - - explicit - Acceptor(Dispatcher& dispatcher) - : base_type(dispatcher) - { - base_type::open(); - } - - bool accept(Socket& sock, AddressT* addr) - { - typename AddressT::traits_type::addr_type tmp; - socklen_t len = sizeof(tmp); - - sock.fd_ = ::accept(fd_, (struct sockaddr*)&tmp, &len); - - if (sock.fd_ >= 0 && addr) - (*addr) = tmp; - - return (sock.fd_ >= 0); - } - - template - void async_accept(DeviceT& dev, AcceptCompletionRoutineT func) - { - assert(this->dispatcher_); - this->dispatcher_->enqueueEvent(fd_, new AcceptEvent(dev, func)); - } - - void cancel_accept() - { - assert(this->dispatcher_); - this->dispatcher_->template removeEventAcceptEventTraits>(fd_); - } - - bool listen(size_t backlog = DEFAULT_BACKLOG) - { - return ::listen(fd_, backlog) == 0; - } - - bool bind(const AddressT& address) - { - return ::bind(fd_, address, address.getSockAddrSize()) == 0; - } -}; - - -namespace IPv4 -{ -typedef ::Acceptor Acceptor; -} -namespace Unix -{ -typedef ::Acceptor Acceptor; -} - - -// --------------------------------------------------------------- - - -template -struct s_mem_fun_2 -{ - inline - s_mem_fun_2(ObjT* obj, FuncT func) - : obj_(obj) - , func_(func) - { - // NOOP - } - - template - inline - void operator()(T1 t1, T2 t2) - { - (obj_->*func_)(t1, t2); - } - - ObjT* obj_; - FuncT func_; -}; - -template -inline -s_mem_fun_2 -mem_fun_2(ObjT* obj, FuncT func) -{ - return s_mem_fun_2(obj, func); -} - - -// --- Test and other code -------------------------------------------------------------- - - -// Echo server state machine -struct EchoSession -{ - EchoSession(Dispatcher& dispatcher) - : sock_(dispatcher) - , package_(0) - , cur_(0) - { - // NOOP - } - - void start() // start the sessions internal statemachine - { - sock_.async_read_some(buf, sizeof(buf), mem_fun_2(this, &EchoSession::handleRead)); - } - - void handleRead(size_t len, bool ok) - { - if (ok) - { - package_ = len; - cur_ = 0; - - sock_.async_write_some(buf, package_, mem_fun_2(this, &EchoSession::handleWrite)); - } - else - delete this; - } - - void handleWrite(size_t len, bool ok) - { - if (ok) - { - if (cur_ + len < package_) - { - sock_.async_write_some(buf + cur_, package_ - cur_, mem_fun_2(this, &EchoSession::handleWrite)); - cur_ += len; - } - else - sock_.async_read_some(buf, sizeof(buf), mem_fun_2(this, &EchoSession::handleRead)); - } - else - delete this; - } - - IPv4::StreamSocket sock_; - char buf[128]; - size_t package_; - size_t cur_; -}; - - -// classical server socket acceptor -struct EchoServer -{ - EchoServer(int port) - : d_() - , a_(d_) - , next_(0) - { - if (a_.bind(IPv4::Endpoint(9999))) - { - a_.listen(); - arm(); - } - } - - void run() - { - d_.run(); - } - -private: - - void arm() - { - // rearm acceptor - next_ = new EchoSession(d_); - a_.async_accept(next_->sock_, mem_fun_2(this, &EchoServer::accepthandler)); - } - -public: - - void accepthandler(IPv4::Endpoint& address, bool ok) - { - if (ok) - { - next_->start(); - arm(); - } - else - d_.stop(); - } - - Dispatcher d_; - IPv4::Acceptor a_; - EchoSession* next_; -}; - - -int main() -{ -#if 1 - //UDPSocket u; - //char buf[2]; - //EndpointIPv4 addr1; - //u.read_some_from(addr1, buf, 2); - //u.write_some_to(EndpointIPv4("127.0.0.1", 9999), "HallO", 5); - - IPv4::StreamSocket s; - IPv4::Acceptor a; - - a.bind(IPv4::Endpoint("127.0.0.1", 9999)); - a.listen(); - - IPv4::Endpoint addr; - a.accept(s, &addr); - - if (s) - { - char buf[80]; - ssize_t len = 0; - while(len = s.read_some(buf, sizeof(buf))) - { - s.write_some(buf, len); - write(STDOUT_FILENO, buf, len); - } - //s.cancel_read(); - } -#else - EchoServer s(7777); - s.run(); -#endif - return 0; -} diff --git a/examples/alpha/pool.cpp b/examples/alpha/pool.cpp deleted file mode 100644 index e109467..0000000 --- a/examples/alpha/pool.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include - - -// FIXME rethink alignment issues -template -struct pool -{ - struct entry - { - void* next_; - }; - - pool(int count) - : p_((entry*)new char[count * Size]) - { - for(int i=0; i p_(5); - void* ptr = p_.get(); - new(ptr) derived(); - base* b = (base*)ptr; - b->hello(); - return 0; -}; diff --git a/examples/alpha/sigslot2.cpp b/examples/alpha/sigslot2.cpp deleted file mode 100644 index c115c69..0000000 --- a/examples/alpha/sigslot2.cpp +++ /dev/null @@ -1,641 +0,0 @@ -#include -#include -#include -#include - -#include - - -// forward decl -class slot; - - -// slot lifetime tracking base class for connections -struct tracking_base -{ - friend class slot; - -protected: - - tracking_base(slot* slot); - - void release(slot* slot); - - inline - bool isValid() const - { - return valid_; - } - -private: - - tracking_base* next_; - bool valid_; - - inline - void slotDied() - { - valid_ = false; - } -}; - - -struct slot -{ - friend class tracking_base; - -protected: - - inline - slot() - : cns_(0) - { - // NOOP - } - - ~slot() - { - tracking_base* cn = cns_; - while(cn) - { - cn->slotDied(); - cn = cn->next_; - } - } - -private: - - inline - void add(tracking_base* cn) - { - tracking_base* next = cns_; - cns_ = cn; - cn->next_ = next; - } - - void remove(tracking_base* cn) - { - tracking_base* iter = cns_; - tracking_base* last = 0; - - while(iter && iter != cn) - { - last = iter; ++iter; - } - - if (iter == cn) - { - if (last) - { - last->next_ = cn->next_; - } - else - cns_ = cn->next_; - } - } - - tracking_base* cns_; -}; - - -inline -tracking_base::tracking_base(slot* slot) - : next_(0) - , valid_(true) -{ - slot->add(this); -} - - -inline -void tracking_base::release(slot* slot) -{ - slot->remove(this); -} - - -// --------------------------------------------------------------------------- - -// FIXME maybe find a way to send 4-byte values within the pointer area and not reference and again reference it -// so this should again be a bit faster... -template -struct call_helper -{ - static inline - void* toVoidPtr(T& t) - { - return &t; - } - - static inline - T fromVoidPtr(void* p) - { - return *(T*)p; - } -}; - - -template -struct call_helper -{ - static inline - void* toVoidPtr(T* t) - { - return t; - } - - static inline - T* fromVoidPtr(void* p) - { - return (T*)p; - } -}; - - -template -struct call_helper -{ - static inline - void* toVoidPtr(const T* t) - { - return const_cast(t); - } - - static inline - const T* fromVoidPtr(void* p) - { - return (T*)p; - } -}; - - -template -struct call_helper -{ - static inline - void* toVoidPtr(T& t) - { - return &t; - } - - static inline - T& fromVoidPtr(void* p) - { - return *(T*)p; - } -}; - - -template -struct call_helper -{ - static inline - void* toVoidPtr(const T& t) - { - return const_cast(&t); - } - - static inline - const T& fromVoidPtr(void* p) - { - return *(T*)p; - } -}; - - -// --------------------------------------------------------------------------- - - -// non-slot-lifetime tracking base for connections -struct non_tracking_base -{ - inline - non_tracking_base(...) - { - // do nothing, not a slot base class - } - - inline - void release(...) - { - // do nothing, there is no slot - } - - inline - bool isValid() const - { - return true; - } -}; - - -template -struct connection_base : protected if_::value, tracking_base, non_tracking_base>::type -{ - typedef typename if_::value, tracking_base, non_tracking_base>::type base_type; - -protected: - - SlotT* slot_; - FuncT func_; - - connection_base(SlotT* slot, FuncT func) - : base_type(slot) - , slot_(slot) - , func_(func) - { - // NOOP - } - - ~connection_base() - { - base_type::release(slot_); - } - - connection_base* np_; // need this here? -}; - - -struct abstract_connection_0 -{ - template class U> friend struct signal_base; - friend struct signal_0; - -protected: - - virtual ~abstract_connection_0() - { - // NOOP - } - - abstract_connection_0* np_; - - virtual void call() = 0; -}; - - -struct abstract_connection_1 -{ - template class U> friend struct signal_base; - template friend struct signal_1; - -protected: - - virtual ~abstract_connection_1() - { - // NOOP - } - - abstract_connection_1* np_; - - virtual void call(void*) = 0; -}; - - -template -struct connection_0 : public abstract_connection_0, private connection_base -{ - template class U> friend struct signal_base; - friend struct signal_0; - - typedef connection_base cbase_type; - -private: - - connection_0(SlotT* slot, FuncT func) - : connection_base(slot, func) - { - // NOOP - } - - void call() - { - if (cbase_type::isValid()) - ((cbase_type::slot_)->*cbase_type::func_)(); - } -}; - - -template -struct connection_1 : public abstract_connection_1, private connection_base -{ - template class U> friend struct signal_base; - template friend struct signal_1; - - typedef connection_base cbase_type; - -private: - - connection_1(SlotT* slot, FuncT func) - : connection_base(slot, func) - { - // NOOP - } - - void call(void* arg) - { - if (cbase_type::isValid()) - ((cbase_type::slot_)->*cbase_type::func_) - (call_helper::param_type>::type>::fromVoidPtr(arg)); - } -}; - -/* -template -struct Connection2 : private connection_base -{ -}; - - -template -struct Connection3 : private connection_base -{ -}; -*/ - - -template class ConcreteConnT> -struct signal_base -{ -protected: - - signal_base() - : conns_(0) - { - // NOOP - } - - ~signal_base() - { - disconnect(); - } - -public: - - template - void connect(SlotT* slot, FuncT func) - { - STATIC_CHECK((is_same::param_type>::type>::type>::value), object_type_mismatch); - - // take connections out of memory pool? - AbsConnT* cn = conns_; - conns_ = new ConcreteConnT(slot, func); - conns_->np_ = cn; - } - - template - void disconnect(SlotT* slot, FuncT func) - { - // FIXME - } - - void disconnect() - { - AbsConnT* cn = conns_; - AbsConnT* next = 0; - while(cn) - { - next = cn->np_; - delete cn; - cn = next; - } - } - -protected: - - // FIXME make copyable - signal_base(const signal_base&); - signal_base& operator=(const signal_base&); - - AbsConnT* conns_; -}; - - -struct signal_0 : public signal_base -{ - void emit() - { - abstract_connection_0* cn = conns_; - while(cn) - { - cn->call(); - cn = cn->np_; - } - } -}; - - -template -struct signal_1 : private signal_base -{ -private: - - typedef signal_base base_type; - -public: - - template - void connect(SlotT* slot, FuncT func) - { - STATIC_CHECK((is_same::param_type>::type>::value), type_mismatch_on_first_argument); - STATIC_CHECK((Size::param_type>::value == 2), argument_count_mismatch); - - base_type::connect(slot, func); - } - - // FIXME maybe leave the signal non-templated and only template this member function would - // be fine too for the compiler. But what about the user? - void emit(T t) - { - abstract_connection_1* cn = conns_; - while(cn) - { - cn->call(call_helper::toVoidPtr(t)); - cn = cn->np_; - } - } - - using base_type::disconnect; - - // FIXME make sure, an inheriter cannot access the protected connections... -}; - - -// ----------------------------------------------------------------- - - -template -struct signal2 -{ -}; - - -template -struct signal3 -{ -}; - - -// ----------------------------------------------------------------------- - - -template -struct signalchooser; - -template<> -struct signalchooser -{ - typedef signal_0 type; -}; - -template -struct signalchooser -{ - typedef signal_1 type; -}; - -template -struct signalchooser -{ - typedef signal2 type; -}; - -template -struct signalchooser -{ - typedef signal3 type; -}; - - -template -struct signal : public signalchooser::type -{ - // all public member functions inherited... -}; - - -// ----------------------------------------------------------------- - - -// this should work too -struct Myslot : public slot -{ - void hello0() - { - std::cout << "Hello World" << std::endl; - } - - void hello(int i) - { - std::cout << "Hallo " << i << std::endl; - } - - void doIt(const int& i) - { - std::cout << "doIt " << i << std::endl; - } - - void doIt2(int& i) - { - std::cout << "doIt2 " << i << std::endl; - i = 42; - } - - void doItPtr(int* i) - { - std::cout << "doItPtr " << *i << std::endl; - *i = 777; - } - - void doItPtr2(const int* i) - { - std::cout << "doItPtr2 " << *i << std::endl; - } -}; - - -struct Anotherslot : public slot -{ - void welt(int i) - { - std::cout << "Welt " << i << std::endl; - } -}; - - -struct tester -{ - explicit - tester(int i) - : i(i) - { - std::cout << "ctor" << std::endl; - } - - tester(const tester& t) - { - std::cout << "cctor" << std::endl; - } - - tester& operator=(const tester& t) - { - std::cout << "op=" << std::endl; - } - - ~tester() - { - std::cout << "dtor" << std::endl; - } - - int i; -}; - - -struct testerslot -{ - void test(const tester& t) - { - std::cout << t.i << std::endl; - } -}; - - -int main() -{ - // FIXME this is how 4-byte rule could work when casted... - tester i(42); - void* p = (void*&)i; - tester& k = (tester&)p; - - signal s; - Myslot* myslot = new Myslot; - Anotherslot a; - s.connect(&a, &Anotherslot::welt); - s.connect(myslot, &Myslot::hello); - //delete myslot; - s.emit(42); - - signal<> s0; - s0.connect(myslot, &Myslot::hello0); - s0.emit(); - - signal s1; -// s1.connect(myslot, &Myslot::doIt); - s1.connect(myslot, &Myslot::doIt2); - int j = 777; - s1.emit(j); - std::cout << "Now: " << j << std::endl; - - signal s2; - //s2.connect(myslot, &Myslot::doItPtr); - s2.connect(myslot, &Myslot::doItPtr2); - s2.emit(&j); - std::cout << "Now: " << j << std::endl; - - testerslot t; - signal s3; - s3.connect(&t, &testerslot::test); - s3.emit(tester(33)); - - return EXIT_SUCCESS; -} diff --git a/examples/alpha/store.cpp b/examples/alpha/store.cpp deleted file mode 100644 index 2ac4b07..0000000 --- a/examples/alpha/store.cpp +++ /dev/null @@ -1,408 +0,0 @@ -#include -#include -#include - - -struct storage_chunk -{ - friend struct memory_pool; - - - storage_chunk(size_t size, size_t count) - : free_(count) - , capacity_(size * count) - , freelist_(this + 1) - , next_(0) -#ifdef NDEBUG - , elemsize_(size) - , elemcount_(count) -#endif - { - char* ptr = (char*)(this + 1); - - for(int i=0; i(ptr + size); - ptr += size; - } - - *ptr = 0; // last entry - } - - - inline - ~storage_chunk() - { -#ifdef NDEBUG - if (free_ != elemcount_) - { - std::cerr << "Memory leak detected in storage_chunk " << this << std::endl; - abort(); - } -#endif - - free_ = 0; - capacity_ = 0; - freelist_ = 0; - next_ = 0; - } - - - void* allocate() - { - void* rc = 0; - - if (freelist_) - { - rc = freelist_; - freelist_ = (void*)*reinterpret_cast(freelist_); - --free_; - } - - return rc; - } - - - bool free(void* ptr) - { - bool rc = false; - - if (ptr >= this + 1 && ptr < (char*)(this + 1) + capacity_) - { - // do a freelist check for detecting double frees when NDEBUG is set -#ifdef NDEBUG - void* freeptr = freelist_; - while(freeptr) - { - if (ptr == freeptr) - { - std::cerr << "Double free detected in storage_chunk " << this << " for " << ptr << std::endl; - abort(); - } - - freeptr = (void*)*reinterpret_cast(freeptr); - } -#endif // NDEBUG - - *(intptr_t*)ptr = - reinterpret_cast(freelist_); - freelist_ = ptr; - - ++free_; - - rc = true; - } - - return rc; - } - - - inline - size_t available() const - { - return free_; - } - - -private: - - size_t free_; - size_t capacity_; ///< in bytes, not element count, only good for pointer check - - void* freelist_; - storage_chunk* next_; - -#ifdef NDEBUG - size_t elemsize_; - size_t elemcount_; -#endif - - // make sure to keep 8 byte alignment here... -}; - - -/** - * Simple light weight fixed-size allocation container. - */ -struct memory_pool -{ - enum { - Initial = 100, - Increment = 100 - }; - - memory_pool(size_t size, size_t elements = Initial, size_t increment = Increment) - : chunks_(0) - , size_(size < sizeof(intptr_t) ? sizeof(intptr_t) : size) - , increment_(increment) - { - assert(size); - assert(elements); - - chunks_ = createNewChunk(elements); - } - - - ~memory_pool() - { - storage_chunk* chunk = chunks_; - while(chunk != 0) - { - chunk = deleteChunk(chunk); - } - } - - - inline - void* allocate() - { - void* rc = quick_allocate(); - if (rc == 0) - rc = full_allocate(); - return rc; - } - - - inline - void free(void* ptr) - { - if (!quick_free(ptr)) - full_free(ptr); - } - - - /** - * Free all unused memory chunks and sort them in a certain order (e.g. by most free - * chunks for fast access when allocation occurres). - */ - void gc() - { - // FIXME - } - - - /** - * Number of elements which can currently be allocated without any OS interaction. - */ - size_t available() const - { - size_t rc = 0; - for(storage_chunk* chunk = chunks_; chunk != 0; chunk = chunk->next_) - { - rc += chunk->available(); - } - return rc; - } - - -private: - - inline - void* quick_allocate() - { - return chunks_->allocate(); - } - - - void* full_allocate() - { - // As precondition, the first chunk is already viewed for new memory and obviously returned 0. - // Therefore we start with the second chunk. - void* rc = 0; - - storage_chunk* chunk = chunks_->next_; - while(chunk != 0) - { - if ((rc = chunk->allocate()) != 0) - break; - - chunk = chunk->next_; - } - - if (rc == 0 && increment_ > 0) - { - storage_chunk* newchunk = createNewChunk(increment_); - newchunk->next_ = chunks_; - chunks_ = newchunk; - - rc = newchunk->allocate(); - } - - return rc; - } - - - inline - bool quick_free(void* ptr) - { - return chunks_->free(ptr); - } - - - void full_free(void* ptr) - { - if (ptr) - { - // As precondition, the first chunk is already viewed for new memory and obviously returned false. - // Therefore we start with the second chunk. - storage_chunk* chunk = chunks_->next_; - bool found = false; - - while(chunk != 0 && !found) - { - if (chunk->free(ptr)) - found = true; - - chunk = chunk->next_; - } - -#ifdef NDEBUG - if (!found) - { - std::cerr << "Dangling pointer " << this << " encountered by segregated_storage " << this << std::endl; - abort(); - } -#endif - } - } - - - storage_chunk* deleteChunk(storage_chunk* chunk) - { - storage_chunk* rc = chunk->next_; - - chunk->~storage_chunk(); - ::free(chunk); - - return rc; - } - - - storage_chunk* createNewChunk(size_t count) - { - storage_chunk* rc = (storage_chunk*)::malloc(sizeof(storage_chunk) + size_ * count); - new(rc) storage_chunk(size_, count); - return rc; - } - - storage_chunk* chunks_; - - size_t size_; ///< element size - size_t increment_; ///< increment size for new chunks -}; - - -template -struct object_pool -{ - object_pool(size_t initial = memory_pool::Initial, size_t increment = memory_pool::Increment) - : store_(sizeof(T), initial, increment) - { - // NOOP - } - - inline - T* allocate() - { - T* t = (T*)store_.allocate(); - new(t) T(); - return t; - } - - template - inline - T* allocate(T1 t1) - { - T* t = (T*)store_.allocate(); - new(t) T(t1); - return t; - } - - template - inline - T* allocate(T1 t1, T2 t2) - { - T* t = (T*)store_.allocate(); - new(t) T(t1, t2); - return t; - } - - template - inline - T* allocate(T1 t1, T2 t2, T3 t3) - { - T* t = (T*)store_.allocate(); - new(t) T(t1, t2, t3); - return t; - } - - inline - void free(T* t) - { - assert(t); - t->~T(); - store_.free(t); - } - - memory_pool store_; -}; - - -// ------------------------------------------------------------------------------------------ - - -struct nix -{ - nix() - : i(0) - { - // NOOP - } - - nix(int argi) - : i(argi) - { - // NOOP - } - - int i; - double d; -}; - - -int main() -{ - memory_pool store(sizeof(nix), 4, 4); - - //nix* n1 = new(store.allocate()) nix; - void* p1 = store.allocate(); - void* p2 = store.allocate(); - void* p3 = store.allocate(); - void* p4 = store.allocate(); - void* p5 = store.allocate(); - std::cout << store.available() << std::endl; - - std::cout << p1 << " " << p2 << " " << p3 << " " << p4 << " " << p5 << std::endl; - - store.free(p1); - store.free(p2); - store.free(p3); - p3 = store.allocate(); - store.free(p4); - store.free(p5); - std::cout << store.available() << std::endl; - - p5 = store.allocate(); - store.free(p3); - store.free(p5); - std::cout << store.available() << std::endl; - - object_pool alloc; - nix* n1 = alloc.allocate(); - nix* n2 = alloc.allocate(45); - alloc.free(n1); - alloc.free(n2); - - return 0; -} diff --git a/examples/cmdline/CMakeLists.txt b/examples/cmdline/CMakeLists.txt deleted file mode 100644 index 4526b00..0000000 --- a/examples/cmdline/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_executable(cmdline cmdline.cpp) -target_link_libraries(cmdline simppl) - -add_executable(commands commands.cpp) -target_link_libraries(commands simppl) diff --git a/examples/cmdline/cmdline.cpp b/examples/cmdline/cmdline.cpp deleted file mode 100644 index 70654d4..0000000 --- a/examples/cmdline/cmdline.cpp +++ /dev/null @@ -1,267 +0,0 @@ -#include "simppl/cmdline_extensionpoint.h" - -#include -#include - -#include "simppl/bind_adapter.h" - -#pragma clang diagnostic ignored "-Woverloaded-shift-op-parentheses" - -using std::placeholders::_1; - -namespace cmd = simppl::cmdline; - - -//#define USE_GETOPT_PARSER - - -// ----------------------------------------------------------------------------------------------------- - - -bool gFlag = false; - - -void f() -{ - gFlag = true; -} - - -void g(int value) -{ - std::cout << "j says " << value << std::endl; -} - - -struct Nix -{ - void sayHello(int i) - { - std::cout << i << std::endl; - } -}; - -Nix n; - -std::string theOption; - -void g1(const std::string& value) -{ - theOption = value; - std::cout << "theOption=" << theOption << std::endl; -} - - -cmd::ExtensionPoint globalExtensionPoint = - cmd::Option()["jiji1"].doc("Tolle Show, hier!") >> g1 - <= cmd::Switch()["kurios"] >> simppl::bind(&Nix::sayHello, n, 42) - <= cmd::Option()["jiji2"].doc("Tolle Show, hier123!") >> g - ; - -cmd::ExtensionPoint secondExtensionPoint = - cmd::Option()["jiji4"].doc("Tolle Show, hier!") >> g - <= cmd::Option()["jiji5"].doc("Tolle Show, hier123!") >> g - ; - -// yet another argument to be added here -bool registerExtension() -{ - globalExtensionPoint += cmd::Option()["jiji3"].doc("Noch ne tolle Show, hier!") >> g; - return true; -} - -static bool registered = registerExtension(); - - -struct A -{ - A(bool& flag) - : flag_(flag) - { - } - - void hello(bool value) - { - flag_ = value; - } - - void store(int value) - { - flag_ = value > 0; - } - - void store1(const char* what) - { - printf("cmdline says '%s'\n", what); - } - - void store2(const char* what) - { - printf("now it says '%s'\n", what); - } - - bool& flag_; -}; - - -void h(int j) -{ - printf("from z: %d\n", j); -} - - -struct MyUsage : /*Noop*/cmd::DefaultUsagePrinter -{ - inline - void operator()(std::ostream& os) - { - os << "This is an absolutely senseless program." << std::endl; - } - - inline - void operator()(FILE* f) - { - fprintf(f, "This is an absolutely senseless program.\n"); - } -}; - - -int main(int argc, char** argv) -{ - A a(gFlag); - int i; - int k; - const char* ptr = 0; - char what[255] = { 0 }; - std::string strng; - std::vector vec; - - std::function func(h); - -#ifdef USE_GETOPT_PARSER - - bool rc = true; - - int c; - bool have_z = false; - - while((c = getopt(argc, argv, "z:yx:v:w:u:")) != -1) - { - switch(c) - { - case 'z': - { - int i=0; - if ((i = atoi(optarg)) != 0) - { - have_z = true; - h(i); - } - else - rc = false; - } - break; - - case 'y': - gFlag = true; - break; - - case 'x': - { - int i=0; - if ((i = atoi(optarg)) != 0) - { - k = i; - } - else - rc = false; - } - break; - - case 'v': - ptr = optarg; - break; - - case 'w': - strcpy(what, optarg); - break; - - case 'u': - strng = optarg; - break; - - default: - rc = false; - break; - } - } - - if (rc && optind == argc-1) - { - a.store1(argv[optind]); - } - -#else -//# define _ERASE(a) -# define _ERASE(a) a -#if 0 - bool rc = cmd::Parser - ::parse(argc, argv, - cmd::Switch<'v'>().doc("super") >> cmd::inc(k) - <= globalExtensionPoint - /*<= Switch<'w'>().doc("super") >> inc(k) - <= secondExtensionPoint - <= cmd::Switch<'x'>().doc("super") >> inc(k)*/ - ); -#endif - // #if 0 - bool rc = cmd::Parser - ::parse(argc, argv, - //cmd::Switch<'v'>().doc("super") >> cmd::inc(k) || - //cmd::MultiOption<>()["bp"].doc("toll") >> h - - cmd::Option()_ERASE(["gaga"].doc("Hallo welt")) >> h - <= cmd::Switch<'y'>() >> gFlag - <= cmd::Switch<>()["gagaga"].doc("super") >> gFlag - <= cmd::Option<'x'>()_ERASE(["haha"].doc("Super Ding fuer int")) >> k // integer - <= cmd::Option<'v'>()_ERASE(["hehe"].doc("Super Ding fuer ptr")) >> &ptr // const char ptrs - <= cmd::Option<'w'>()_ERASE(["hihi"].doc("Super Ding fuer char arrays")) >> what // char arrays - <= cmd::Option<'u'>()_ERASE(["huhu"].doc("Super Ding fuer std::string")) >> strng // std::strings - <= cmd::ExtraOption()_ERASE(.doc("tolles Argument, echt super")) >> simppl::bind(&A::store1, &a, _1) - //ExtraOption()_ERASE(.doc("tolles Argument, echt super")) >> bind(&std::vector::push_back, &vec, _1) - <= cmd::MultiExtraOption()_ERASE(.doc("tolles Argument, echt super")) >> vec - //cmd::ExtraOption()_ERASE(.doc("tolles Argument, echt super")) >> what - //cmd::ExtraOption<>()_ERASE(.doc("tolles Argument, ehrlich, wirklich")) >> bind(&A::store2, &a, _1) - <= globalExtensionPoint - - ); -//#endif -#endif - - if (rc) - { - printf("verbosity: %d\n", k); - - printf("y: %s set\n", gFlag?"is":"not"); - - if (ptr) - printf("v: %s\n", ptr); - - if (what[0]) - printf("w: %s\n", what); - - if (vec.size() > 0) - { - printf("vec: "); - for (int i=0; i -#include - - -using std::placeholders::_1; - -namespace cmd = simppl::cmdline; - - -struct MyUsagePrinter : cmd::DefaultUsagePrinter -{ - template - static - void eval(InheriterT* usage, cmd::detail::stream_type& os, const ParserT& parser, const char* command) - { - if (usage) - (*usage)(os); - - simppl::cmdline::detail::extraOptionCounter = 0; - - os << std::endl; - os << "Usage: commands " << command << ' '; - parser.genCmdline(os); - os << std::endl << std::endl; - - simppl::cmdline::detail::extraOptionCounter = 0; - parser.doDoc(os); - } -}; - - -bool parse_tuple(std::tuple& tup, const char* value) -{ - int rc = sscanf(value, "%d,%d", &std::get<0>(tup), &std::get<0>(tup)); - return rc == 2; -} - - -int main(int argc, char** argv) -{ - bool rc; - - std::string command; - - bool debug = false; - bool from_shared_memory; - - std::tuple em; - std::tuple tt; - std::string serial; - - if (argc > 1) - { - command = argv[1]; - - --argc; - ++argv; - - rc = true; - } - - if (rc) - { - cmd::ExtensionPoint options = cmd::Switch<'d'>()["debug"] >> debug; - - if (!command.compare("temp")) - { - options += cmd::Switch<'s'>()["shared"] >> from_shared_memory; - } - else if (!command.compare("info")) - { - options += cmd::Switch<'s'>()["shared"] >> from_shared_memory; - } - else if (!command.compare("store")) - { - options += cmd::Option()["tt"] >> simppl::bind(&parse_tuple, std::ref(tt), _1) - <= cmd::Option()["em"] >> simppl::bind(&parse_tuple, std::ref(em), _1) - <= cmd::Option()["serial"] >> serial; - } - else if (!command.compare("-h") || !command.compare("--help")) - { - std::cout << "usage: commands [args]" << std::endl; - } - else - { - std::cerr << "Unknown command '" << command << "'" << std::endl; - return EXIT_FAILURE; - } - - rc = cmd::Parser::parse(argc, argv, options); - - if (rc) - { - if (debug) - std::cout << "debug enabled" << std::endl; - } - } - - return rc; -} diff --git a/examples/inifile/CMakeLists.txt b/examples/inifile/CMakeLists.txt deleted file mode 100644 index d000e63..0000000 --- a/examples/inifile/CMakeLists.txt +++ /dev/null @@ -1,2 +0,0 @@ -add_executable(inifile inifile.cpp) -target_link_libraries(inifile simppl) diff --git a/examples/inifile/inifile.cpp b/examples/inifile/inifile.cpp deleted file mode 100644 index 00ffb71..0000000 --- a/examples/inifile/inifile.cpp +++ /dev/null @@ -1,106 +0,0 @@ -#include - -// test extensions -#define EX 1 - -#include "simppl/inifile.h" - -#ifdef EX -# include "simppl/inifile_extensionpoint.h" -#endif - -#include "simppl/bind_adapter.h" - - -using namespace std::placeholders; -namespace ini = simppl::inifile; - - -void funca(const char* text, int i) -{ - std::cout << text << ": " << i << std::endl; -} - -bool funci(bool b) -{ - std::cout << "Hallo " << (b?"Welt":"Shit") << "!" << std::endl; - return true; -} - -bool b(const char* what) -{ - std::cout << "Gell, " << what << "?" << std::endl; - return true; -} - -bool f(const char* what) -{ - std::cout << "Super " << what << "!" << std::endl; - return true; -} - -bool local(const char* what) -{ - std::cout << "Local is '" << what << "'" << std::endl; - return (strcmp(what, "super")); -} - -bool forward(const char*) -{ - return true; -} - - -#ifdef EX -ini::ExtensionPoint extensionpoint1 = ini::Section("gurgel") >> f; - -ini::ExtensionPoint extensionpoint2; -#endif - - -int main() -{ - const char* filename = "./test.ini"; - std::vector v; - short bl = 0; - bool b1 = false; - unsigned int i2 = 0; - char c = 0; - char buf[255]; - std::string str1; - - ini::Result rc = ini::Parser< - ini::NoopHeaderParser, - ini::ReportUnknownSection, - ini::ReportUnknownKey> - ::parse( - ini::File(filename, "/etc/test.ini")[ - ini::Key<>("one") >> simppl::bind(&funca, "one", _1) - || ini::Key("two") >> simppl::bind(&funca, "two", _1) - || ini::Key<>("three") >> simppl::bind(&funca, "three", _1) - || ini::Key("four") >> simppl::bind(&funca, "four", _1) - ] - <= ini::Section("gaga")[ - ini::Key<>("hallo") >> v - || ini::Key<>("hehe") >> bl - || ini::Key<>("gell") >> b1 - || ini::Key<>("gell1") >> i2 - || ini::Key<>("gell4") >> c - || ini::Key<>("gell2") >> simppl::bind(strncpy, buf, _1, sizeof(buf)) - || ini::Key<>("gell5") >> buf - || ini::Key<>("gell3") >> str1 - ] - <= ini::Section("jepp") >> local -#ifdef EX - <= extensionpoint1 - <= extensionpoint2 -#endif - ); - - if (!rc) - std::cout << "Failed to parse ini-File in line " << rc.line() << ": " << rc.toString() << ". Must exit." << std::endl; - - std::cout << bl << std::endl; - - return EXIT_SUCCESS; -} diff --git a/examples/inifile/test.ini b/examples/inifile/test.ini deleted file mode 100644 index 460ea7d..0000000 --- a/examples/inifile/test.ini +++ /dev/null @@ -1,35 +0,0 @@ - # comment=here -super=true #super -gaga=123 -hurra=456 # 456" -one=1 -two=2 -three=3 -four=4 - -[gaga1] - [gaga2] -[ gaga3] -[gaga4 ] -[gaga5] - -# gaga6] -#[gaga7 -#[gaga8 -#[gaga9]] -#[[gaga10]] -#[gaga11 ] ] -#[gaga11 ] ] -#[gaga -gell=was -hallo=welt - -[gaga] -hehe=0x1FFF -hallo=1,3,2,4,5,7,6,8 - -[jepp] -toll # comment here -#gell -#super -#jepp diff --git a/examples/ipc2/CMakeLists.txt b/examples/ipc2/CMakeLists.txt deleted file mode 100644 index 253c18d..0000000 --- a/examples/ipc2/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -#add_executable(ipc2 ipc2.cpp) -#target_link_libraries(ipc2 simppl) - -#add_executable(ipc2_e ipc2_e.cpp) -#target_link_libraries(ipc2_e simppl) - -#add_executable(session session.cpp) -#target_link_libraries(session simppl) - -#add_executable(attributes attributes.cpp) -#target_link_libraries(attributes simppl) - -#add_executable(except except.cpp) -#target_link_libraries(except simppl) - -#add_executable(calculator_cpu calculator_cpu.cpp) -#target_link_libraries(calculator_cpu simppl) - -#add_executable(calculator_clnt calculator_clnt.cpp) -#target_link_libraries(calculator_clnt simppl) - -#add_executable(calculator_clnt1 calculator_clnt1.cpp) -#target_link_libraries(calculator_clnt1 simppl) - -#add_executable(benchmark benchmark.cpp) -#target_link_libraries(benchmark simppl) - -add_executable(simple simple.cpp) -target_link_libraries(simple simppl dbus-1) diff --git a/examples/ipc2/README b/examples/ipc2/README deleted file mode 100644 index d7721dd..0000000 --- a/examples/ipc2/README +++ /dev/null @@ -1,33 +0,0 @@ -Generic service oriented IPC libary framework for generating skeleton and stub code -from a high-level interface description directly in C++ by the C++ compiler so -there is no need for external code generator tools necessary. - - -Features -======== - -Interface level - - * shoot-and-forget requests - * requests with associated responses or error responses - * signals - * attributes with appropriate notifications (value changes, always, user-requested) - * event driven interface - * blocking (RPC) call interface - * session handling - * request timeouts - - -Transport level - - * Unix domain socket transport, including inotify notifications - * TCP/IP transport - * service broker for automatic service resolution - - -Possible future features - - * UDP/datagram transport (perhaps broadcast/multicast) for signals and shoot-and-forget requests - * multithread support - * send requests from other threads - * receive events in thread-pool diff --git a/examples/ipc2/TODO b/examples/ipc2/TODO deleted file mode 100644 index 161fb95..0000000 --- a/examples/ipc2/TODO +++ /dev/null @@ -1,100 +0,0 @@ -TODOs - - -ThreadingModel as a Policy -========================== - - * SingleThreaded (as-is) - * MultiThreaded (thread-pool) - * server side (skeletons) - * client side (stubs) - - server side: requests are handled within a thread pool, the sockets are handled by the main thread, but - all request handlers are called within the pool. Therefore, the requests are queued and the threads will - take the requests in a FIFO order. For response dispatch we need a way back to the dispatcher since in - this case the thread may _never_ send anything blocking on any socket (in order to avoid event scattering - on the wire). - - poll loop -------------> queue <------------- thread 1 - (request) ^ ^ - | +--------------- thread 2 - +------------------thread 3 - - thread x --------------> back-queue <----------- poll loop - (response) - - The Stubs and Skeletons (-> Policy) thereby may be - - * reentrant - -> we have nothing to be concerned about (just catch the event from the queue) - - * non-reentrant - -> the same server may not be called twice if it is already active in a thread - * need activity flag - * events may only be extracted from the queue if the corresponding stub is ready - - -Add further interaction device to event-loop -============================================ - -Add a generic fd based device to the dispatcher interface. This would be much easier if I base the whole -thing on top of the async IO framework. - -Then, we can add further endpoints to the dispatcher to allow to handle also tcp based requests. - - -Tranport -======== - -Implement non-blocking write operations. In case of blocks queue the data and let the dispatcher -send the rest of it. The second variant can be used when clients call requests from other thread -contexts. One has to see if there is any state on clients side - if not, I can indeed trivially -use clients in multithreaded environments. - -Servers are much more complex since they have some state during the answering process (currentRequest, -currentSession, ...). In case of servers running within multiple threads we would need to store this -stuff in thread-local variables and have some locking on the dispatcher in order to access queues -and global data. - - -Error support -============= - -How could an interface designer introduce other exception classes? Currently, I think -there is no need for this since either the user-defined exception is trivial or must again -be modeled like a complete response and therefore could just be a modeled as-so. The interface -designer could use any self-written enum to use this instead of the implementation used integer. - - -Transport error detection -========================= - -Still missing. No concept yet. - - -Session support -=============== - - * clients may send explicit detach calls to the server - * maybe have handlers to be implemented to see if clients attach to a server - * Allow to send events to a certain client only (by adding the session_id - of the client to the emit() call of the event. Any further functionality - must be implemented by the user logic (e.g. how to register/unregister - and when to send the event to a certain client). - - -Next Steps -========== - - Transport - - * introduce socket class with internal queue - * if queue empty -> send directly nonblocking - * if queue is full -> enqueue and arm fd slot for POLLOUT - * if nonblocking send fails -> enqueue (the rest) - - ThreadingModel - - * mutex for dispatcher, must be used by all socket classes - when sending data - * receiving data only in one thread diff --git a/examples/ipc2/attributes.cpp b/examples/ipc2/attributes.cpp deleted file mode 100644 index 2599839..0000000 --- a/examples/ipc2/attributes.cpp +++ /dev/null @@ -1,190 +0,0 @@ -#include "simppl/stub.h" -#include "simppl/skeleton.h" -#include "simppl/interface.h" -#include "simppl/dispatcher.h" - - - -using namespace std::placeholders; - -namespace spl = simppl::ipc; - - -struct MyStruct -{ - typedef spl::make_serializer::type serializer_type; - - inline - MyStruct() - : i(-1) - { - // NOOP - } - - inline - MyStruct(int _i, const std::string& _str) - : i(_i) - , str(_str) - { - // NOOP - } - - inline - bool operator!=(const MyStruct& rhs) const - { - return i != rhs.i; - } - - int i; - std::string str; -}; - - -INTERFACE(Interface) -{ - Request doSomething; - Response resultOfDoSomething; - - Attribute myInt; - Attribute myStruct; - Attribute > myVector; - Attribute comInt; - - inline - Interface() - : INIT_REQUEST(doSomething) - , INIT_RESPONSE(resultOfDoSomething) - , INIT_ATTRIBUTE(myInt) - , INIT_ATTRIBUTE(myStruct) - , INIT_ATTRIBUTE(myVector) - , INIT_ATTRIBUTE(comInt) - { - doSomething >> resultOfDoSomething; - } -}; - - -struct Server : spl::Skeleton<::Interface> -{ - Server(const char* role) - : spl::Skeleton<::Interface>(role) - { - myInt = 99; - myStruct = MyStruct(0, "No answer yet."); - comInt = 41; - - doSomething >> std::bind(&Server::handleDoSomething, this, _1); - } - - void handleDoSomething(int i) - { - std::cout << "handleDoSomething with i=" << i << std::endl; - - comInt = 42; - comInt = 43; - comInt = 44; - comInt.commit(); - comInt = 45; - - // these assignments raise signals if there is anybody connected to them - myInt = i; - myVector.push_back(i); - myStruct = MyStruct(i, "The answer to all questions."); - - respondWith(resultOfDoSomething(i)); - } -}; - - -struct Client : spl::Stub<::Interface> -{ - Client(const char* role) - : Stub<::Interface>(role, "unix:myserver") // connect the client to 'myserver' - { - connected >> std::bind(&Client::handleConnected, this, _1); - - std::cout << "Initial attribute myStruct is [" << myStruct.value().i << ", '" << myStruct.value().str << "']" << std::endl; - - resultOfDoSomething >> std::bind(&Client::handleResultDoSomething, this, _1, _2); - } - - void handleConnected(spl::ConnectionState) - { - myInt.attach() >> std::bind(&Client::attributeChanged, this, _1); - myStruct.attach(); // here receive status updates, but no direct change notification - myVector.attach() >> std::bind(&Client::vectorChanged, this, _1, _2, _3, _4); - - comInt.attach() >> std::bind(&Client::commAttributeChanged, this, _1); - doSomething(42); - } - - void handleResultDoSomething(const spl::CallState& state, int response) - { - std::cout << "Response is " << response << std::endl; - std::cout << "Attribute myStruct is now [" << myStruct.value().i << ", '" << myStruct.value().str << "']" << std::endl; - std::cout << "Finishing..." << std::endl; - disp().stop(); - } - - void attributeChanged(int i) - { - std::cout << "Attribute myStruct is initialized from server side [" << myStruct.value().i << ", '" << myStruct.value().str << "']" << std::endl; - std::cout << "attribute myInt changed: new value=" << i << ", or new value=" << myInt.value() << " respectively." << std::endl; - } - - void commAttributeChanged(int i) - { - std::cout << "Attribute was committed: value=" << i << std::endl; - } - - void vectorChanged(const std::vector& iv, spl::How how, uint32_t where, uint32_t len) - { - std::cout << "Yes, vector changed(" << how << "," << where << "," << len << "): "; - - if (iv.empty()) - { - std::cout << "[empty]"; - } - else - std::cout << iv.front(); - - std::cout << std::endl; - } -}; - - -void* server(void* dispatcher) -{ - spl::Dispatcher& d = *(spl::Dispatcher*)dispatcher; - - Server s1("myrole"); - d.addServer(s1); - - d.run(); - return 0; -} - - -int main() -{ - // start server dispatcher thread on unix path 'myserver' - spl::Dispatcher server_dispatcher("unix:myserver"); - - pthread_t tid; - pthread_create(&tid, 0, server, &server_dispatcher); - while(!server_dispatcher.isRunning()); // wait for other thread - -// run client in separate thread (not really necessary, just for blocking interfaces) - spl::Dispatcher d; - - Client c("myrole"); - d.addClient(c); - - d.run(); - - server_dispatcher.stop(); - pthread_join(tid, 0); - - return 0; - -} diff --git a/examples/ipc2/bench.txt b/examples/ipc2/bench.txt deleted file mode 100644 index ff8b9e1..0000000 --- a/examples/ipc2/bench.txt +++ /dev/null @@ -1,50 +0,0 @@ -Benchmark ---------- - -* Optimierung des Streamings (andere Argumentübergabe, Rückgabewerte) bringt nichts - - -Noch mit StreamSockets ----------------------- - -./client --pings=50000 -Proxy connected to server -No arg: 50000 calls in 3614 ms, 27670 msgs/s -1 struct: 50000 calls in 3768 ms, 26539 msgs/s -10 x struct: 50000 calls in 3911 ms, 25568 msgs/s -100 x struct: 50000 calls in 5107 ms, 19580 msgs/s -1000 x struct: 50000 calls in 29732 ms, 3363 msgs/s - -./client --pings=150000 -Proxy connected to server -No arg: 150000 calls in 10223 ms, 29345 msgs/s -1 struct: 150000 calls in 11012 ms, 27243 msgs/s -10 x struct: 150000 calls in 12031 ms, 24935 msgs/s - - -Mit SeqPacket Socket und 4 kB Static-Recv-RAM ---------------------------------------------- - -./client --pings=50000 -Proxy connected to server -No arg: 50000 calls in 3523 ms, 28384 msgs/s -1 struct: 50000 calls in 3697 ms, 27048 msgs/s -10 x struct: 50000 calls in 4385 ms, 22805 msgs/s -100 x struct: 50000 calls in 6317 ms, 15830 msgs/s -1000 x struct: 50000 calls in 29876 ms, 3347 msgs/s - -./client --pings=150000 -Proxy connected to server -No arg: 150000 calls in 10346 ms, 28996 msgs/s -1 struct: 150000 calls in 11001 ms, 27270 msgs/s -10 x struct: 150000 calls in 12348 ms, 24295 msgs/s -100 x struct: 150000 calls in 16115 ms, 18616 msgs/s - -Man sieht: sobald er den Buffer intern kopieren muss bleibt von der Performance nichts übrig. -Das memcpy zum Kopieren des initialen Frames in den dynamischen Speicher ist sehr teuer -(sobald 4kB überschritten werden). - - -Mit size calculation before allocation in serializer and static RAM of 4 kB ---------------------------------------------------------------------------- - diff --git a/examples/ipc2/benchmark.cpp b/examples/ipc2/benchmark.cpp deleted file mode 100644 index 39eb75f..0000000 --- a/examples/ipc2/benchmark.cpp +++ /dev/null @@ -1,272 +0,0 @@ -#define SIMPPL_HAVE_VALIDATION -//#define SIMPPL_HAVE_BOOST_FUSION - -#include "simppl/stub.h" -#include "simppl/skeleton.h" -#include "simppl/dispatcher.h" -#include "simppl/interface.h" - -#include - - -using namespace std::placeholders; - - -static -unsigned int current_time_ms() -{ - struct timespec current_time ; - clock_gettime(CLOCK_REALTIME, ¤t_time); - - return (current_time.tv_sec * 1000) + (current_time.tv_nsec / 1000000) ; -} - - -#ifdef SIMPPL_HAVE_BOOST_FUSION -BOOST_FUSION_DEFINE_STRUCT( - (), PODStruct, - (int32_t, anInt32) - (double, aDouble) - (double, anotherDouble) - (std::string, aString) -) -#else -struct PODStruct -{ - typedef simppl::ipc::make_serializer::type serializer_type; - - int32_t anInt32; - double aDouble; - double anotherDouble; - std::string aString; -}; -#endif - - -typedef std::vector PODStructVector; - - - -INTERFACE(DSIBenchmark) -{ - Request<> shutdown; - - Request<> callNoArg; - Request callStruct; - Request callStructVector; - - Signal<> rCallNoArg; // must be modeled like this here - Response rCallStruct; - Response rCallStructVector; - - inline - DSIBenchmark() - : INIT_REQUEST(shutdown) - , INIT_REQUEST(callNoArg) - , INIT_REQUEST(callStruct) - , INIT_REQUEST(callStructVector) - , INIT_SIGNAL(rCallNoArg) - , INIT_RESPONSE(rCallStruct) - , INIT_RESPONSE(rCallStructVector) - { - //callNoArg >> rCallNoArg; not possible since the response is a signal - callStruct >> rCallStruct; - callStructVector >> rCallStructVector; - } -}; - - -struct Client : simppl::ipc::Stub -{ - Client(int calls = 1) - : simppl::ipc::Stub("bench", "unix:DSIBenchmark") - , mCalls(calls) - , mCounter(0u) - , mFactor(10u) - , mStartTime(0u) - { - rCallNoArg >> std::bind(&Client::handleCallNoArg, this); - rCallStruct >> std::bind(&Client::handleCallStruct, this, _1, _2); - rCallStructVector >> std::bind(&Client::handleCallStructVector, this, _1, _2); - - mPodStruct.anInt32 = 1; - mPodStruct.aDouble = 2; - mPodStruct.anotherDouble = 3; - mPodStruct.aString = "01234567890123456789"; - - connected >> std::bind(&Client::handleConnected, this, _1); - } - - void handleConnected(simppl::ipc::ConnectionState) - { - rCallNoArg.attach(); - - std::cout << "Proxy connected to server" << std::endl; - std::cout << "No arg: " << std::flush; - - mStartTime = current_time_ms(); - callNoArg(); - } - - void handleCallNoArg() - { - if (mCounter++ < mCalls) - { - callNoArg(); - } - else - { - snapshot(); - std::cout << "1 struct: " << std::flush; - - mCounter = 0u; - mStartTime = current_time_ms(); - callStruct(mPodStruct); - } - } - - void handleCallStruct(const simppl::ipc::CallState& state, const PODStruct& s) - { - if (mCounter++ < mCalls) - { - callStruct(mPodStruct); - } - else - { - snapshot(); - std::cout << mFactor << " x struct: " << std::flush; - while (mPodStructVector.size() < mFactor) - { - mPodStructVector.push_back(mPodStruct); - } - - mCounter = 0u; - mStartTime = current_time_ms(); - callStructVector(mPodStructVector); - } - } - - void handleCallStructVector(const simppl::ipc::CallState& state, const PODStructVector& v) - { - if (mCounter++ < mCalls) - { - callStructVector(mPodStructVector); - } - else - { - snapshot(); - if (mFactor < 1000u) - { - mFactor *= 10u; - std::cout << mFactor << " x struct: " << std::flush; - while (mPodStructVector.size() < mFactor) - { - mPodStructVector.push_back(mPodStruct); - } - mCounter = 0u; - mStartTime = current_time_ms(); - callStructVector(mPodStructVector); - } - else - { - shutdown(); - exit(1); - } - } - } - - void snapshot() - { - const unsigned int totalTime = current_time_ms() - mStartTime; - - // a ping-pong loop has 2 messages - std::cout << mCalls << " calls in " << totalTime << " ms, " <<(mCalls * 1000 * 2) / totalTime << " msgs/s" - << std::endl; - } - - unsigned int mCalls; - unsigned int mCounter; - unsigned int mFactor; - unsigned int mStartTime; - - PODStruct mPodStruct; - PODStructVector mPodStructVector; -}; - - -struct Server : simppl::ipc::Skeleton -{ - Server() - : simppl::ipc::Skeleton("bench") - { - shutdown >> std::bind(&Server::handleShutdown, this); - callNoArg >> std::bind(&Server::handleNoArg, this); - callStruct >> std::bind(&Server::handleStruct, this, _1); - callStructVector >> std::bind(&Server::handleStructVector, this, _1); - } - - void handleShutdown() - { - exit(0); - } - - void handleNoArg() - { - rCallNoArg.emit(); - } - - void handleStruct(const PODStruct& s) - { - respondWith(rCallStruct(s)); - } - - void handleStructVector(const PODStructVector& v) - { - respondWith(rCallStructVector(v)); - } -}; - - -#define PING_COUNT 100 - - -template -struct isValidType -{ - typedef typename boost::mpl::if_c::value, boost::mpl::true_, boost::mpl::false_>::type type; -}; - - -int main(int argc, char** argv) -{ - int calls = PING_COUNT; // take this as default count of calls - if (argc >= 2) - { - if (!strncmp(argv[1], "--pings=", 8)) - { - calls = atoi(argv[1] + 8); - assert(calls > 0); - - simppl::ipc::Dispatcher d; - Client c(calls); - d.addClient(c); - d.run(); - - return EXIT_SUCCESS; - } - - if (!strcmp(argv[1], "--server")) - { - simppl::ipc::Dispatcher d("unix:DSIBenchmark"); - Server s; - d.addServer(s); - d.run(); - - return EXIT_SUCCESS; - } - } - - std::cout << "Invalid command line options: either '--server' or '--pings='" << std::endl; - return EXIT_FAILURE; -} - diff --git a/examples/ipc2/broker.cpp b/examples/ipc2/broker.cpp deleted file mode 100644 index 04e9bfe..0000000 --- a/examples/ipc2/broker.cpp +++ /dev/null @@ -1,240 +0,0 @@ -#include "simppl/ipc2.h" - -/* - * build the four types of servers: - * - * g++ -I../../ -DBROKER -o broker broker.cpp - * g++ -I../../ -DSERVER -o server broker.cpp - * g++ -I../../ -DBLOCKCLIENT -o blocking_client broker.cpp - * g++ -I../../ -o client broker.cpp - * - * Make sure the broker is the first server to run! - */ - - -INTERFACE(Broker) -{ - Request waitForService; - Request registerService; - - Response serviceReady; - - inline - Broker() - : INIT_REQUEST(waitForService) - , INIT_REQUEST(registerService) - , INIT_RESPONSE(serviceReady) - { - waitForService >> serviceReady; - } -}; - - -INTERFACE(HelloWorld) -{ - Request sayHello; - - inline - HelloWorld() - : INIT_REQUEST(sayHello) - { - // NOOP - } -}; - - -// ----------------------------------------------------------------------------------------------------- - - -struct BrokerImpl : Skeleton -{ - typedef std::map servicemap_type; - typedef std::multimap waitersmap_type; - - BrokerImpl() - : Skeleton("broker") - { - waitForService >> std::bind(&BrokerImpl::handleWaitForService, this, _1); - registerService >> std::bind(&BrokerImpl::handleRegisterService, this, _1, _2); - } - - void handleRegisterService(const std::string& serv, const std::string& loc) - { - std::cout << "Registering " << serv << " at location " << loc << std::endl; - - services_[serv] = loc; - - std::pair p = waiters_.equal_range(serv); - - for(waitersmap_type::iterator iter = p.first; iter != p.second; ++iter) - { - respondOn(iter->second, serviceReady(serv, loc)); - } - } - - void handleWaitForService(const std::string& serv) - { - std::cout << "Client waits for " << serv << std::endl; - - servicemap_type::iterator iter = services_.find(serv); - if (iter != services_.end()) - { - respondWith(serviceReady(serv, iter->second)); - } - else - waiters_.insert(std::pair(serv, deferResponse())); - - } - - servicemap_type services_; - waitersmap_type waiters_; -}; - - -struct HelloWorldImpl : Skeleton -{ - HelloWorldImpl() - : Skeleton("helloworld") - { - sayHello >> std::bind(&HelloWorldImpl::handleSayHello, this, _1); - } - - void handleSayHello(const std::string& str) - { - std::cout << "Client says '" << str << "'" << std::endl; - } -}; - - -// ----------------------------------------------------------------------------------------------------- - - -struct HelloWorldClient : Stub -{ - HelloWorldClient(const char* loc) - : Stub("helloworld", loc) - { - connected >> std::bind(&HelloWorldClient::handleConnected, this, _1); - } - - void handleConnected(ConnectionState) - { - sayHello("Hello World!"); - } -}; - - -struct BrokerClientOnServerSide : Stub -{ - BrokerClientOnServerSide() - : Stub("broker", "unix:the_broker") - { - connected >> std::bind(&BrokerClientOnServerSide::handleConnected, this, _1); - } - - void handleConnected(ConnectionState) - { - std::cout << "Got connected to broker, registering..." << std::endl; - registerService("HelloWorld::helloworld", "unix:the_server"); - } -}; - - -struct BrokerClientOnClientSide : Stub -{ - BrokerClientOnClientSide() - : Stub("broker", "unix:the_broker") - { - serviceReady >> std::bind(&BrokerClientOnClientSide::handleServiceReady, this, _1, _2); - connected >> std::bind(&BrokerClientOnClientSide::handleConnected, this, _1); - } - - void handleConnected(ConnectionState) - { - std::cout << "Got connected to broker, waiting..." << std::endl; - - waitForService("HelloWorld::helloworld"); - } - - void handleServiceReady(const std::string& service, const std::string& loc) - { - std::cout << "Got service ready signal from broker, connecting to '" << service << "' at location '" << loc << "'" << std::endl; - - HelloWorldClient* impl = new HelloWorldClient(loc.c_str()); - disp().addClient(*impl); - } -}; - - -// ----------------------------------------------------------------------------------------------------- - - -#ifdef BROKER - -int main() -{ - Dispatcher d("unix:the_broker"); - - BrokerImpl brk; - d.addServer(brk); - - return d.run(); -} - -#elif defined(SERVER) - -int main() -{ - Dispatcher d("unix:the_server"); - - HelloWorldImpl hwi; - d.addServer(hwi); - - BrokerClientOnServerSide brk; - d.addClient(brk); - - return d.run(); -} - -#elif defined(BLOCKCLIENT) - -int main() -{ - Dispatcher d; - - Stub brk("broker", "unix:the_broker"); - d.addClient(brk); - - if (brk.connect()) - { - std::string loc; - d.waitForResponse(brk.waitForService("HelloWorld::helloworld"), loc); - - if (!loc.empty()) - { - HelloWorldClient impl(loc.c_str()); - d.addClient(impl); - - if (impl.connect()) - { - impl.sayHello("Hello blocking World!"); - } - } - } - - return EXIT_SUCCESS; -} - -#else // CLIENT - -int main() -{ - Dispatcher d; - - BrokerClientOnClientSide brk; - d.addClient(brk); - - return d.run(); -} - -#endif diff --git a/examples/ipc2/calculator.h b/examples/ipc2/calculator.h deleted file mode 100644 index 4804bc8..0000000 --- a/examples/ipc2/calculator.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef SIMPPL_CALCULATOR_H -#define SIMPPL_CALCULATOR_H - - -#include "simppl/interface.h" - - -/// servicebroker -INTERFACE(Calculator) -{ - Request<> clear; - - Request add; - Request sub; - - Attribute value; - - inline - Calculator() - : INIT_REQUEST(clear) - , INIT_REQUEST(add) - , INIT_REQUEST(sub) - , INIT_ATTRIBUTE(value) - { - // NOOP - } -}; - - -#endif // SIMPPL_CALCULATOR_H diff --git a/examples/ipc2/calculator_clnt.cpp b/examples/ipc2/calculator_clnt.cpp deleted file mode 100644 index b6afb20..0000000 --- a/examples/ipc2/calculator_clnt.cpp +++ /dev/null @@ -1,115 +0,0 @@ -// -// example of self-made broker interface handling -// - -#include "simppl/dispatcher.h" -#include "simppl/brokerclient.h" - -#include "calculator.h" - -#include - - -using namespace std::placeholders; - -namespace spl = simppl::ipc; - - -struct CalculatorClient; -static CalculatorClient* calc = 0; - -static const char* rolename = "calculator"; - - -struct CalculatorClient : spl::Stub<::Calculator> -{ - CalculatorClient(const char* location) - : spl::Stub<::Calculator>(rolename, location) - { - connected >> std::bind(&CalculatorClient::handleConnected, this, _1); - } - - void handleConnected(spl::ConnectionState) - { - value.attach() >> std::bind(&CalculatorClient::valueChanged, this, _1); - } - - void valueChanged(double d) - { - std::cout << "Now having " << d << std::endl; - } -}; - - -void ClientsFactory(spl::Dispatcher* disp, const std::string& fullName, const std::string& location) -{ - if (fullName == disp->fullQualifiedName("Calculator", rolename)) - { - CalculatorClient* new_calc = new CalculatorClient(location.c_str()); - disp->addClient(*new_calc); - - calc = new_calc; - } -} - - -void* threadRunner(void* arg) -{ - spl::Dispatcher disp; - - spl::BrokerClient broker(disp); - broker.waitForService(disp.fullQualifiedName("Calculator", rolename), std::bind(ClientsFactory, &disp, _1, _2)); - - disp.run(); - return 0; -} - - -int main(int argc, char** argv) -{ - if (argc > 1) - rolename = argv[1]; - - pthread_t thread; - pthread_create(&thread, 0, threadRunner, 0); - - // wait for calculator to be ready - while(!calc) - usleep(100); - - char arg; - double d; - - bool finished = false; - while(!finished) - { - std::cin >> arg; - switch(arg) - { - case '+': - // FIXME make this inherent thread-safe if configured so - std::cin >> d; - calc->add(d); - break; - - case '-': - std::cin >> d; - calc->sub(d); - break; - - case 'c': - std::cout << "Clear" << std::endl; - calc->clear(); - break; - - case 'q': - std::cout << "Quit" << std::endl; - finished = true; - break; - - default: - std::cout << "Unknown command:" << std::endl; - break; - } - } -} diff --git a/examples/ipc2/calculator_clnt1.cpp b/examples/ipc2/calculator_clnt1.cpp deleted file mode 100644 index e47177a..0000000 --- a/examples/ipc2/calculator_clnt1.cpp +++ /dev/null @@ -1,105 +0,0 @@ -// -// example of integrated broker interface handling -// - -#include "simppl/dispatcher.h" - -#include "calculator.h" - -#include - - -using namespace std::placeholders; - -namespace spl = simppl::ipc; - - -static const char* rolename = "calculator"; - -struct CalculatorClient; -static CalculatorClient* calc = 0; - - -struct CalculatorClient : spl::Stub<::Calculator> -{ - CalculatorClient() - : spl::Stub<::Calculator>(rolename, "auto:") - { - connected >> std::bind(&CalculatorClient::handleConnected, this, _1); - } - - void handleConnected(spl::ConnectionState) - { - value.attach() >> std::bind(&CalculatorClient::valueChanged, this, _1); - calc = this; - } - - void valueChanged(double d) - { - std::cout << "Now having " << d << std::endl; - } -}; - - -void* threadRunner(void* arg) -{ - spl::Dispatcher disp; - disp.enableBrokerage(); - - CalculatorClient clnt; - disp.addClient(clnt); - - disp.run(); - return 0; -} - - -int main(int argc, char** argv) -{ - if (argc > 1) - rolename = argv[1]; - - pthread_t thread; - pthread_create(&thread, 0, threadRunner, 0); - - // wait for calculator to be ready - while(!calc) - usleep(100); - - char arg; - double d; - - bool finished = false; - while(!finished) - { - std::cout << "Input: q(uit),c(lear),+- > "; - std::cin >> arg; - switch(arg) - { - case '+': - // FIXME make this inherent thread-safe if configured so - std::cin >> d; - calc->add(d); - break; - - case '-': - std::cin >> d; - calc->sub(d); - break; - - case 'c': - std::cout << "Clear" << std::endl; - calc->clear(); - break; - - case 'q': - std::cout << "Quit" << std::endl; - finished = true; - break; - - default: - std::cout << "Unknown command: " << arg << std::endl; - break; - } - } -} diff --git a/examples/ipc2/calculator_cpu.cpp b/examples/ipc2/calculator_cpu.cpp deleted file mode 100644 index 95ba6d3..0000000 --- a/examples/ipc2/calculator_cpu.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include "simppl/dispatcher.h" -#include "simppl/skeleton.h" - -#include "calculator.h" - - -using namespace std::placeholders; - -namespace spl = simppl::ipc; - - -struct CalculatorImpl : spl::Skeleton<::Calculator> -{ - CalculatorImpl(const char* role) - : spl::Skeleton<::Calculator>(role) - { - clear >> std::bind(&CalculatorImpl::handleClear, this); - add >> std::bind(&CalculatorImpl::handleAdd, this, _1); - sub >> std::bind(&CalculatorImpl::handleSub, this, _1); - } - - void handleClear() - { - value = 0; - } - - void handleAdd(double d) - { - double oldValue = value.value(); - value = oldValue + d; - } - - void handleSub(double d) - { - double oldValue = value.value(); - value = oldValue - d; - } -}; - - -int main(int argc, char** argv) -{ - const char* role = "calculator"; - if (argc > 1) - role = argv[1]; - - spl::Dispatcher disp("unix:calculator"); - disp.enableBrokerage(); - - CalculatorImpl calc(role); - disp.addServer(calc); - - return disp.run(); -} diff --git a/examples/ipc2/except.cpp b/examples/ipc2/except.cpp deleted file mode 100644 index 9763c89..0000000 --- a/examples/ipc2/except.cpp +++ /dev/null @@ -1,126 +0,0 @@ -#include "simppl/stub.h" -#include "simppl/skeleton.h" -#include "simppl/dispatcher.h" -#include "simppl/interface.h" - - -using namespace std::placeholders; - -namespace spl = simppl::ipc; - - -INTERFACE(Interface) -{ - Request doSomething; - Response resultOfDoSomething; - - Request doSomethingElse; - Response<> resultOfDoSomethingElse; - - inline - Interface() - : INIT_REQUEST(doSomething) - , INIT_REQUEST(doSomethingElse) - , INIT_RESPONSE(resultOfDoSomething) - , INIT_RESPONSE(resultOfDoSomethingElse) - { - doSomething >> resultOfDoSomething /*|| throwing()*/; - doSomethingElse >> resultOfDoSomethingElse; - } -}; - - -struct Server : spl::Skeleton<::Interface> -{ - Server(const char* role) - : spl::Skeleton<::Interface>(role) - { - doSomething >> std::bind(&Server::handleDoSomething, this, _1); - } - - void handleDoSomething(int i) - { - std::cout << "doing something with i=" << i << std::endl; - - //throw RuntimeError(-i, "Shit also happens"); // also possible here - if (i == 42) - { - respondWith(spl::RuntimeError(-i, "Shit happens")); - } - else - respondWith(resultOfDoSomething(i)); - } -}; - - -struct Client : spl::Stub<::Interface> -{ - Client(const char* role) - : spl::Stub<::Interface>(role, "unix:myserver") // connect the client to 'myserver' - { - connected >> std::bind(&Client::handleConnected, this, _1); - - // must distinuish between normal response and error handler - // another possible solution would be to wrap the binder in an OnError(...) Function - // which then could be used for type switching in the >> operator via specialization - - resultOfDoSomething >> std::bind(&Client::handleResultDoSomething, this, _1, _2); - } - - void handleConnected(spl::ConnectionState) - { - doSomething(42); - } - - void handleResultDoSomething(const spl::CallState& state, int response) - { - if (state) - { - std::cout << "Response is " << response << std::endl; - disp().stop(); - } - else - { - std::cout << "Error transmitted from server: request failed, message: " << state.what() << std::endl; - - doSomething(7); - } - } -}; - - -void* server(void* dispatcher) -{ - spl::Dispatcher& d = *(spl::Dispatcher*)dispatcher; - - Server s1("myrole"); - d.addServer(s1); - - d.run(); - return 0; -} - - -int main() -{ - // start server dispatcher thread on unix path 'myserver' - spl::Dispatcher server_dispatcher("unix:myserver"); - - pthread_t tid; - pthread_create(&tid, 0, server, &server_dispatcher); - while(!server_dispatcher.isRunning()); // wait for other thread - - // run client in separate thread (not really necessary, just for blocking interfaces) - spl::Dispatcher d; - - Client c("myrole"); - d.addClient(c); - - d.run(); - - server_dispatcher.stop(); - pthread_join(tid, 0); - - return 0; - -} diff --git a/examples/ipc2/ipc2.cpp b/examples/ipc2/ipc2.cpp deleted file mode 100644 index f59eb9d..0000000 --- a/examples/ipc2/ipc2.cpp +++ /dev/null @@ -1,236 +0,0 @@ -#include "simppl/interface.h" -#include "simppl/skeleton.h" -#include "simppl/stub.h" -#include "simppl/dispatcher.h" -#include "simppl/blocking.h" - -#include - -using std::placeholders::_1; - -namespace spl = simppl::ipc; - - -struct Complex -{ - typedef spl::make_serializer::type serializer_type; - - // you always need the default constructor - inline - Complex() - : re_(0) - , im_(0) - { - // NOOP - } - - // any other constructor may additionally be defined - inline - Complex(double re, double im) - : re_(re) - , im_(im) - { - // NOOP - } - - double re_; - double im_; -}; - - -INTERFACE(Interface) -{ - Request add; - Request sub; - - Request addBoth; - Request addTriple; - - Request<> clear; - - Request display; - Request addComplex; - - Response resultOfAdd; - Response resultOfSub; - - Signal sig1; - Signal<> cleared; - - Request > reqt; - - inline - Interface() - : INIT_REQUEST(add) - , INIT_REQUEST(sub) - , INIT_REQUEST(addBoth) - , INIT_REQUEST(addTriple) - , INIT_REQUEST(clear) - , INIT_REQUEST(display) - , INIT_REQUEST(addComplex) - , INIT_RESPONSE(resultOfAdd) - , INIT_RESPONSE(resultOfSub) - , INIT_SIGNAL(sig1) - , INIT_SIGNAL(cleared) - , INIT_REQUEST(reqt) - { - add >> resultOfAdd; - sub >> resultOfSub; - } -}; - - -struct InterfaceClient : spl::Stub<::Interface> -{ - InterfaceClient(const char* role) - : spl::Stub<::Interface>(role, "unix:myserver") // connect the client to 'myserver' - { - // NOOP - } -}; - - -void cleared() -{ - std::cout << "Got cleared" << std::endl; -} - - -struct InterfaceServer : spl::Skeleton<::Interface> -{ - InterfaceServer(const char* role) - : spl::Skeleton<::Interface>(role) - , result_(0) - { - add >> std::bind(&InterfaceServer::handleAdd, this, _1); - sub >> std::bind(&InterfaceServer::handleSub, this, _1); - clear >> std::bind(&InterfaceServer::handleClear, this); - display >> std::bind(&InterfaceServer::handleDisplay, this, _1); - addComplex >> std::bind(&InterfaceServer::handleAddComplex, this, _1); - reqt >> std::bind(&InterfaceServer::handleReqt, this, _1); - } - - void handleAdd(int i) - { - result_ += i; - std::cout << "adding " << i << ", result=" << result_ << std::endl; - - respondWith(resultOfAdd(result_)); - } - - void handleSub(int i) - { - result_ -= i; - std::cout << "subtracting " << i << ", result=" << result_ << std::endl; - - sleep(5); - - if (i < 0) - { - respondWith(spl::RuntimeError(-1, "negative value is invalid")); - } - else - { - spl::ServerRequestDescriptor rq = deferResponse(); - respondOn(rq, resultOfSub(result_)); // rq will be invalidated here-in - - sig1.emit(result_); - } - } - - void handleReqt(const std::tuple& tup) - { - std::cout << "Tuple result: int=" << std::get<0>(tup) << ", double=" << std::get<1>(tup) << ", string=" << std::get<2>(tup) << std::endl; - } - - void handleClear() - { - result_ = 0; - std::cout << "reset, result=" << result_ << std::endl; - cleared.emit(); - } - - void handleDisplay(const std::string& str) - { - std::cout << "Message from client: '" << str << "'" << std::endl; - } - - void handleAddComplex(const Complex& c) - { - std::cout << "Got complex number re=" << c.re_ << ", im=" << c.im_ << std::endl; - } - - int result_; -}; - - -void* server(void* dispatcher) -{ - spl::Dispatcher& d = *(spl::Dispatcher*)dispatcher; - - InterfaceServer s1("myrole1"); - d.addServer(s1); - - d.run(); - return 0; -} - - -int main() -{ - // start server dispatcher thread on unix path 'myserver' - spl::Dispatcher server_dispatcher("unix:myserver"); - - pthread_t tid; - pthread_create(&tid, 0, server, &server_dispatcher); - while(!server_dispatcher.isRunning()); // wait for other thread - - // run client in separate thread (not really necessary, just for blocking interfaces) - spl::Dispatcher d; - d.setRequestTimeout(std::chrono::milliseconds(1000)); - - InterfaceClient c1("myrole1"); - d.addClient(c1); - - c1.connect(); - - int result; - c1.add(42) >> result; - std::cout << "Result of add is " << result << std::endl; - - c1.cleared.attach() >> cleared; - c1.clear(); - - c1.sub(21) >> result; - std::cout << "Result of sub is " << result << std::endl; - - c1.reqt(std::make_tuple(42, 3.1415, std::string("Hallo Welt"))); - - try - { - d.waitForResponse(c1.sub(-1), result); - } - catch(const spl::RuntimeError& err) - { - std::cout << "Result of sub is invalid: " << err.what() << std::endl; - } - catch(const simppl::ipc::TransportError& ex) - { - std::cout << "ooh: " << ex.what() << std::endl; - } - catch(const std::exception& ex) - { - std::cout << "ooh: " << ex.what() << std::endl; - } - catch(...) - { - std::cout << "Hey" << std::endl; - } - - sleep(1); - - server_dispatcher.stop(); - pthread_join(tid, 0); - - return 0; -} diff --git a/examples/ipc2/ipc2_e.cpp b/examples/ipc2/ipc2_e.cpp deleted file mode 100644 index 6664c0f..0000000 --- a/examples/ipc2/ipc2_e.cpp +++ /dev/null @@ -1,290 +0,0 @@ -#include "simppl/interface.h" -#include "simppl/skeleton.h" -#include "simppl/stub.h" -#include "simppl/dispatcher.h" - -#include - -using std::placeholders::_1; -using std::placeholders::_2; - -namespace spl = simppl::ipc; - - -struct Complex -{ - typedef spl::make_serializer::type serializer_type; - - // you always need the default constructor - inline - Complex() - : re_(0) - , im_(0) - { - // NOOP - } - - // any other constructor may additionally be defined - inline - Complex(double re, double im) - : re_(re) - , im_(im) - { - // NOOP - } - - double re_; - double im_; -}; - - -INTERFACE(Interface) -{ - Request add; - Request sub; - - Request addBoth; - Request addTriple; - - Request<> clear; - - Request display; - Request addComplex; - - Response resultOfAdd; - Response resultOfSub; - - Signal sig1; - Signal<> cleared; - - Attribute myInt; - - Request > reqt; - - inline - Interface() - : INIT_REQUEST(add) - , INIT_REQUEST(sub) - , INIT_REQUEST(addBoth) - , INIT_REQUEST(addTriple) - , INIT_REQUEST(clear) - , INIT_REQUEST(display) - , INIT_REQUEST(addComplex) - , INIT_RESPONSE(resultOfAdd) - , INIT_RESPONSE(resultOfSub) - , INIT_SIGNAL(sig1) - , INIT_SIGNAL(cleared) - , INIT_ATTRIBUTE(myInt) - , INIT_REQUEST(reqt) - { - add >> resultOfAdd; - sub >> resultOfSub; - } -}; - - -struct InterfaceClient : spl::Stub<::Interface> -{ - InterfaceClient(const char* role) - : spl::Stub<::Interface>(role, "tcp:127.0.0.1:9978") // connect the client to 'myserver' - { - resultOfAdd >> std::bind(&InterfaceClient::handleResultAdd, this, _1, _2); - resultOfSub >> std::bind(&InterfaceClient::handleResultSub, this, _1, _2); - - connected >> std::bind(&InterfaceClient::handleConnected, this, _1); - } - - void handleCleared() - { - std::cout << "CPU was cleared..." << std::endl; - } - - void handleConnected(spl::ConnectionState) - { - // attach to all wanted signals here - sig1.attach() >> std::bind(&InterfaceClient::handleSig1, this, _1); - add(42); - } - - void handleResultAdd(const spl::CallState& state, int response) - { - std::cout << "Response is " << response << std::endl; - sub(21); - } - - void handleResultSub(const spl::CallState& state, int response) - { - std::cout << "Response is " << response << std::endl; - display("Hello World!"); - } - - void handleSig1(int data) - { - std::cout << "Got signal 'sig1' with data '" << data << "'" << std::endl; - } -}; - - -struct InterfaceClient2 : spl::Stub<::Interface> -{ - InterfaceClient2(const char* role) - : spl::Stub<::Interface>(role, "tcp:127.0.0.1:9978") // connect the client to 'myserver' - { - connected >> std::bind(&InterfaceClient2::handleConnected, this, _1); - } - - void handleConnected(spl::ConnectionState) - { - sig1.attach() >> std::bind(&InterfaceClient2::handleSig1, this, _1); - } - - void handleSig1(int data) - { - std::cout << "IC2: got signal 'sig1' with data '" << data << "'" << std::endl; - clear(); - } -}; - - -struct InterfaceClient3 : spl::Stub<::Interface> -{ - InterfaceClient3(const char* role) - : spl::Stub<::Interface>(role, "tcp:127.0.0.1:9978") // connect the client to 'myserver' - { - connected >> std::bind(&InterfaceClient3::handleConnected, this, _1); - } - - void handleConnected(spl::ConnectionState) - { - cleared.attach() >> std::bind(&InterfaceClient3::handleCleared, this); - } - - void handleCleared() - { - std::cout << "CPU was cleared...stopping..." << std::endl; - disp().stop(); - } -}; - - -struct InterfaceServer : spl::Skeleton<::Interface> -{ - InterfaceServer(const char* role) - : spl::Skeleton<::Interface>(role) - , result_(0) - { - add >> std::bind(&InterfaceServer::handleAdd, this, _1); - sub >> std::bind(&InterfaceServer::handleSub, this, _1); - clear >> std::bind(&InterfaceServer::handleClear, this); - display >> std::bind(&InterfaceServer::handleDisplay, this, _1); - addComplex >> std::bind(&InterfaceServer::handleAddComplex, this, _1); - } - - void handleAdd(int i) - { - result_ += i; - std::cout << "adding " << i << ", result=" << result_ << std::endl; - - respondWith(resultOfAdd(result_)); - } - - void handleSub(int i) - { - result_ -= i; - std::cout << "subtracting " << i << ", result=" << result_ << std::endl; - - spl::ServerRequestDescriptor rq = deferResponse(); - respondOn(rq, resultOfSub(result_)); // rq will be invalidated here-in - - sig1.emit(result_); - } - - void handleClear() - { - result_ = 0; - std::cout << "reset, result=" << result_ << std::endl; - cleared.emit(); - } - - void handleDisplay(const std::string& str) - { - std::cout << "Message from client: '" << str << "'" << std::endl; - } - - void handleAddComplex(const Complex& c) - { - std::cout << "Got complex number re=" << c.re_ << ", im=" << c.im_ << std::endl; - } - - int result_; -}; - - -void* server(void* dispatcher) -{ - spl::Dispatcher& d = *(spl::Dispatcher*)dispatcher; - - InterfaceServer s1("myrole1"); - d.addServer(s1); - - InterfaceServer s2("myrole2"); - d.addServer(s2); - - d.run(); - return 0; -} - - -struct CheckMeToo -{ - typedef spl::make_serializer >::type serializer_type; - - int i; - std::map s; -}; - - -struct CheckMe -{ - typedef spl::make_serializer::type serializer_type; - - int i; - double d; - CheckMeToo t; -}; - - -int main() -{ - // start server dispatcher thread on unix path 'myserver' - spl::Dispatcher server_dispatcher("tcp:127.0.0.1:9978"); - - pthread_t tid; - pthread_create(&tid, 0, server, &server_dispatcher); - while(!server_dispatcher.isRunning()); // wait for other thread - - // run client in separate thread (not really necessary, just for blocking interfaces) - spl::Dispatcher d; - - InterfaceClient c1("myrole1"); - d.addClient(c1); - - InterfaceClient2 c2("myrole1"); - d.addClient(c2); - - InterfaceClient2 c3("myrole2"); - d.addClient(c3); - - InterfaceClient3 c4("myrole1"); - d.addClient(c4); - - d.run(); - - sleep(1); - - server_dispatcher.stop(); - pthread_join(tid, 0); - - static_assert(spl::detail::isValidType::value, "ooops"); - return 0; -} diff --git a/examples/ipc2/session.cpp b/examples/ipc2/session.cpp deleted file mode 100644 index 8a564da..0000000 --- a/examples/ipc2/session.cpp +++ /dev/null @@ -1,156 +0,0 @@ -#include "simppl/stub.h" -#include "simppl/skeleton.h" -#include "simppl/dispatcher.h" -#include "simppl/interface.h" - -#include - - -using namespace std::placeholders; - -namespace spl = simppl::ipc; - - -struct SessionSpec -{ - /// destruction helper function - static void destruct(void* ptr) - { - delete (SessionSpec*)ptr; - } - - int returnvalue_; ///< the account information -}; - - -INTERFACE(BankAccount) -{ - Request login; - - Request<> getDeposit; - Response resultOfGetDeposit; - - inline - BankAccount() - : INIT_REQUEST(login) - , INIT_REQUEST(getDeposit) - , INIT_RESPONSE(resultOfGetDeposit) - { - getDeposit >> resultOfGetDeposit; - } -}; - - -struct Server : spl::Skeleton<::BankAccount> -{ - Server(const char* role) - : spl::Skeleton<::BankAccount>(role) - { - login >> std::bind(&Server::handleLogin, this, _1, _2); - getDeposit >> std::bind(&Server::handleGetDeposit, this); - } - - - void handleLogin(const std::string& user, const std::string& pass) - { - std::cout << "Login as " << user << "/" << pass << std::endl; - - SessionSpec* session = (SessionSpec*)currentSessionData(); - if (!session) - { - if (user == "hinz") - { - session = new SessionSpec(); - registerSession(session, SessionSpec::destruct); - - session->returnvalue_ = 42; - } - else if (user == "kunz") - { - session = new SessionSpec(); - registerSession(session, SessionSpec::destruct); - - session->returnvalue_ = 21; - } - } - } - - void handleGetDeposit() - { - std::cout << "handleGetDeposit" << std::endl; - - SessionSpec* session = (SessionSpec*)currentSessionData(); - - if (session) - { - respondWith(resultOfGetDeposit(session->returnvalue_)); - } - else - respondWith(spl::RuntimeError(-1, "invalid session")); - } -}; - - -struct Client : spl::Stub<::BankAccount> -{ - Client(const char* user, const char* role) - : spl::Stub<::BankAccount>(role, "unix:myserver") // connect the client to 'myserver' - , user_(user) - { - connected >> std::bind(&Client::handleConnected, this, _1); - resultOfGetDeposit >> std::bind(&Client::handleGetDeposit, this, _1, _2); - } - - void handleConnected(simppl::ipc::ConnectionState) - { - login(user_, "passwd"); - getDeposit(); - } - - void handleGetDeposit(const spl::CallState& state, int value) - { - if (state) - { - std::cout << "Deposit is " << value << std::endl; - } - else - std::cout << "Error returning deposit of user '" << user_ << "': " << state.what() << std::endl; - } - - std::string user_; -}; - - -int main() -{ - // start server dispatcher thread on unix path 'myserver' - spl::Dispatcher server_dispatcher("unix:myserver"); - - std::thread server_thread([&server_dispatcher](){ - Server s1("myrole"); - server_dispatcher.addServer(s1); - server_dispatcher.run(); - }); - - while(!server_dispatcher.isRunning()); // wait for other thread - - // run client in separate thread (not really necessary, just for blocking interfaces) - spl::Dispatcher d; - - Client c1("hinz", "myrole"); - d.addClient(c1); - - Client c2("kunz", "myrole"); - d.addClient(c2); - - Client c3("gaga", "myrole"); - d.addClient(c3); - - d.run(); - - server_dispatcher.stop(); - server_thread.join(); - - return 0; - -} diff --git a/examples/ipc2/simple.cpp b/examples/ipc2/simple.cpp deleted file mode 100644 index 3cd676c..0000000 --- a/examples/ipc2/simple.cpp +++ /dev/null @@ -1,153 +0,0 @@ -#include "simppl/stub.h" -#include "simppl/skeleton.h" -#include "simppl/interface.h" -#include "simppl/dispatcher.h" -#include "simppl/blocking.h" - -#include -#include - -using namespace std::placeholders; - -namespace spl = simppl::ipc; - -using namespace std::literals::chrono_literals; - - -namespace test -{ - -INTERFACE(Simple) -{ - Request<> oneway; - - Request echo; - Response rEcho; - - Signal<> sig; - - Simple() - : INIT_REQUEST(oneway) - , INIT_REQUEST(echo) - , INIT_RESPONSE(rEcho) - , INIT_SIGNAL(sig) - { - echo >> rEcho; - } -}; - -} // namespace - - -// --------------------------------------------------------------------- - -//#define BLOCKING_ONEWAY -#define TEST_SIG - -struct Client : spl::Stub -{ - Client() - : spl::Stub("mysimple") - { - connected >> std::bind(&Client::handle_conn, this, _1); - rEcho >> std::bind(&Client::handle_recho, this, _1, _2); - } - - void handle_conn(spl::ConnectionState s) - { - if (s == spl::ConnectionState::Connected) - { -#ifdef TEST_SIG - sig.attach() >> std::bind(&Client::handle_sig, this); - oneway(); -#else - echo("Hallo Welt"); -#endif - } - } - - void handle_recho(spl::CallState c, const std::string& str) - { - echo("Hallo Welt"); - } - - void handle_sig() - { - oneway(); - } -}; - - -int client() -{ - Client c; - - spl::Dispatcher disp("dbus:session"); - disp.addClient(c); - -#ifdef BLOCKING_ONEWAY - c.connect(); - - while(true) - { - c.oneway(); - std::this_thread::sleep_for(50ms); - } -#else - disp.run(); -#endif - -} - - -// --------------------------------------------------------------------- - - -struct SimpleServer : spl::Skeleton -{ - SimpleServer() - : spl::Skeleton("mysimple") - { - oneway >> std::bind(&SimpleServer::handle_oneway, this); - echo >> std::bind(&SimpleServer::handle_echo, this, _1); - } - - - void handle_oneway() - { - static int count = 0; - - if (++count % 20 == 0) - std::cout << "Client saying " << count << std::endl; - - sig.emit(); - } - - - void handle_echo(const std::string& str) - { - static int cnt = 0; - - if (++cnt % 20 == 0) - std::cout << "Echo " << str << " " << cnt << std::endl; - - respondWith(rEcho("Super")); - } -}; - - -int server() -{ - SimpleServer serv; - - spl::Dispatcher disp("dbus:session"); - disp.addServer(serv); - - return disp.run(); -} - - -int main(int argc, char** argv) -{ - return argc > 1 ? server() : client(); -} diff --git a/examples/misc/CMakeLists.txt b/examples/misc/CMakeLists.txt deleted file mode 100644 index 70a78dd..0000000 --- a/examples/misc/CMakeLists.txt +++ /dev/null @@ -1,2 +0,0 @@ -add_executable(variant variant.cpp) -target_link_libraries(variant simppl) diff --git a/examples/misc/intrusive_list.cpp b/examples/misc/intrusive_list.cpp deleted file mode 100644 index 7665380..0000000 --- a/examples/misc/intrusive_list.cpp +++ /dev/null @@ -1,90 +0,0 @@ -// Intrusive List - -#include -#include - -#include "intrusive_list.h" - - -// TODO access by typedef'd iterator (e.g. pointer or index for SHM or offset or anything other) -struct MyData : public intrusive::ListBaseHook -{ - int i_; -}; - -struct MyOtherData -{ - ~MyOtherData() - { - std::cout << "+MyOtherData" << std::endl; - } - - int d_; - intrusive::ListMemberHook thehook_; -}; - - -int main() -{ - MyData data[40]; - for (unsigned int i = 0; i dt; - const intrusive::List& empty(dt); - - dt.push_back(data[0]); - dt.push_back(data[4]); - dt.push_back(data[3]); - dt.push_back(data[1]); - dt.push_back(data[2]); - - std::cout << "size=" << empty.size() << std::endl; - - for (intrusive::List::const_iterator iter = empty.begin(); - iter != empty.end(); - ++iter) - { - std::cout << (*iter).i_ << std::endl; - //(*iter).i_ = 4; // const_iterator... - } - - //MyOtherData od[10]; - MyOtherData* od0 = new MyOtherData(); - od0->d_ = 1; - MyOtherData* od1 = new MyOtherData(); - od1->d_ = 2; - MyOtherData* od2 = new MyOtherData(); - od2->d_ = 3; - - typedef intrusive::List< - MyOtherData, - intrusive::ListMemberHookAccessor, - intrusive::CalculatingPolicy, - intrusive::OperatorDeleteDestructionPolicy - > another_type; - - another_type another; - another.push_back(*od2); - another.push_back(*od1); - another.push_back(*od0); - std::cout << "size=" << another.size() << std::endl; - - for (another_type::const_iterator iter = another.begin(); iter != another.end(); ++iter) - { - std::cout << (*iter).d_ << std::endl; - } - - std::cout << "next=" << another.erase(another.begin())->d_ << std::endl; - - for (another_type::const_iterator iter = another.begin(); iter != another.end(); ++iter) - { - std::cout << (*iter).d_ << std::endl; - } - - another.clear(); - - return 0; -} diff --git a/examples/misc/safe_ptr.cpp b/examples/misc/safe_ptr.cpp deleted file mode 100644 index a3cdd30..0000000 --- a/examples/misc/safe_ptr.cpp +++ /dev/null @@ -1,333 +0,0 @@ -#include -#include - - -static const unsigned int FLAG_PREPARE_DELETE = 0x08000000; - - -#ifdef __QNX__ -# include - -# define __sync_fetch_and_sub(where, count) (atomic_sub_value(where, count)) -# define __sync_sub_and_fetch(where, count) (atomic_sub_value(where, count) - count) -# define __sync_fetch_and_add(where, count) (atomic_add_value(where, count)) -# define set_to_zero(where) (atomic_clr_value((volatile unsigned*)where, 0xFFFFFFFF)) -# define __sync_fetch_and_or(where, bits) (atomic_set_value(where, bits)) -# define __sync_synchronize() /*noop for now*/ -#else -# define set_to_zero(where) (__sync_fetch_and_and(&t_, 0)) -#endif - - -template -struct SafePtrAccessor; - -template -struct SafePtr -{ - friend struct SafePtrAccessor; - -private: - - void release() - { - int rc = __sync_fetch_and_sub(&h_->accessState_, 1); - { - if (rc & FLAG_PREPARE_DELETE) - h_->try_destruct(); - } - } - - bool acquire(int) - { - // FIXME maybe check for 0 pointer?! - int rc = __sync_fetch_and_add(&h_->accessState_, 1); - - if (rc & FLAG_PREPARE_DELETE) - { - (void)__sync_fetch_and_sub(&h_->accessState_, 1); - h_->try_destruct(); - - return false; - } - - return true; - } - - -public: - - SafePtr(T* t) - : h_(new Holder(t)) - { - // NOOP - } - - ~SafePtr() - { - if (h_->release() == 0) - delete h_; - } - - SafePtr(const SafePtr& rhs) - : h_(0) - { - if (rhs.h_) - { - SafePtr* that = const_cast(&rhs); - - that->h_->acquire(); - h_ = that->h_; - } - } - - SafePtr& operator=(const SafePtr& rhs) - { - if (&rhs != this && rhs.h_ != h_) - { - if (h_->release() == 0) - delete h_; - - SafePtr* that = const_cast(&rhs); - h_ = that->h_; - - if (h_) - h_->acquire(); - } - - return *this; - } - - SafePtrAccessor acquire(); - - - void destruct() - { - if (h_) - h_->prepare_destruct(); - } - - void dump() - { - if (h_) - std::cout << "share: " << h_->refcount_ << ", access: " << std::hex << h_->accessState_ << std::dec << std::endl; - } - - -private: - - struct Holder - { - Holder(T* t) - : t_(t) - , refcount_(1) - , accessState_(0) - { - __sync_synchronize(); // make refcount_ visible to others - } - - ~Holder() - { - delete t_; - } - - void acquire() - { - (void)__sync_fetch_and_add(&refcount_, 1); - } - - int release() - { - return __sync_sub_and_fetch(&refcount_, 1); - } - - void prepare_destruct() - { - std::cerr << "prepare" << std::endl; - (void)__sync_fetch_and_or(&accessState_, FLAG_PREPARE_DELETE); - } - - void try_destruct() - { - if (t_ != 0) - { - std::cerr << "try" << std::endl; - volatile T* t; - - t = (T*)set_to_zero(&t_); - if (t != 0) - { - delete t; - } - } - } - - volatile T* t_; - - volatile unsigned int refcount_; - volatile unsigned int accessState_; - }; - - Holder* h_; -}; - - -template -struct SafePtrAccessor -{ - friend class SafePtr; - -private: - - SafePtrAccessor(const SafePtrAccessor&) = delete; - SafePtrAccessor& operator=(const SafePtrAccessor&) = delete; - - SafePtrAccessor(SafePtr& s) - : s_(0) - { - if (s.acquire(42)) - s_ = &s; - } - -public: - - SafePtrAccessor() - : s_(0) - { - // NOOP - } - - SafePtrAccessor(SafePtrAccessor&& rhs) - : s_(0) - { - s_ = rhs.s_; - rhs.s_ = 0; - } - - SafePtrAccessor& operator=(SafePtrAccessor&& rhs) - { - s_ = rhs.s_; - rhs.s_ = 0; - - return *this; - } - - ~SafePtrAccessor() - { - if (s_) - s_->release(); - } - - operator bool() - { - return s_; - } - - T* operator->() - { - assert(s_); - return (T*)s_->h_->t_; - } - - T& operator*() - { - assert(s_); - return *(T*)s_->h_->t_; - } - - -private: - - SafePtr* s_; -}; - - -template -SafePtrAccessor SafePtr::acquire() -{ - SafePtrAccessor acc(*this); - return std::move(acc); -} - - -// ------------------------------------------------------------------------------------------ - - -#include -#include - - -struct S -{ - S(int i) - : i_(i) - { - // NOOP - } - - ~S() - { - std::cout << "~~~" << std::endl; - } - - int i_; -}; - - -void* runner(void* p) -{ - // FIXME making the copy in a separate thread is not really safe - // but since we join that thread we can be sure that the object - // is not destructed in-between - SafePtr s1 = *(SafePtr*)p; - int j=0; - - for(int i=0; i<1000; ++i) - { - usleep(1); - sched_yield(); - - { - auto p = s1.acquire(); - if (p) - { - //s1.dump(); - j += p->i_; - } - else - { - std::cout << "He's dead at " << i << std::endl; - break; - } - } - - if (i==999) - std::cout << "Got to the end" << std::endl; - } - - usleep(300); - s1.destruct(); - - return 0; -} - - -int main() -{ - SafePtr ip(new S(42)); - - const int num_threads = 30; - - pthread_t tids[num_threads]; - for (int i=0; i - - -int main() -{ - tribool b1(false); - tribool b2(indeterminate); - - if (b1) - { - std::cout << "true" << std::endl; - } - else if (!b1) - { - std::cout << "false" << std::endl; - } - else - { - std::cout << "indet" << std::endl; - } - - std::cout << std::boolalpha << (b1 || b2) << std::endl; - return 0; -} diff --git a/examples/misc/typelist.cpp b/examples/misc/typelist.cpp deleted file mode 100644 index 440d2cd..0000000 --- a/examples/misc/typelist.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include "typelist.h" - - -int main() -{ - PopFront::type>::type gaga; - - PopBack::type>::type gaga1; - //int i = gaga1; - - return 0; -} diff --git a/examples/misc/variant.cpp b/examples/misc/variant.cpp deleted file mode 100644 index f29642d..0000000 --- a/examples/misc/variant.cpp +++ /dev/null @@ -1,118 +0,0 @@ -#include - -#include "simppl/variant.h" - -using namespace simppl; - - -struct MyVisitor : StaticVisitor<> -{ - inline - void operator()(int i) - { - std::cout << "is int: " << i << std::endl; - } - - inline - void operator()(const std::string& s) - { - std::cout << "is string: " << s << std::endl; - } - - inline - void operator()(double d) - { - std::cout << "is double: " << d << std::endl; - } -}; - - -struct CheckVisitor : StaticVisitor -{ - inline - bool operator()(int i) - { - return i > 0; - } - - inline - bool operator()(const std::string& s) - { - return s.size() > 0; - } - - inline - bool operator()(double d) - { - return d > 0; - } -}; - - -struct First -{ - int i; - void sayHello() const - { - std::cout << "Say Hello" << std::endl; - } -}; - -struct Second -{ - int i; - void saySomething() const - { - std::cout << "Say Something" << std::endl; - } -}; - - -struct StrategyVisitor : StaticVisitor<> -{ - inline - void operator()(const First& f) - { - f.sayHello(); - } - - inline - void operator()(const Second& s) - { - s.saySomething(); - } -}; - - -int main() -{ - Variant the_switch; - the_switch = First(); - //the_switch.get()->sayHello(); - staticVisit(StrategyVisitor(), the_switch); - - Variant v(std::string("Hallo Welt")); - std::cout << "Sizeof = " << sizeof(v) << std::endl; - std::cout << v.get() << std::endl; // must be 0 - std::cout << *v.get() << std::endl; // must be "Hallo Welt" - staticVisit(MyVisitor(), v); - - v = 42; - std::cout << *v.get() << std::endl; // must be 42 - std::cout << v.get() << std::endl; // must be 0 - staticVisit(MyVisitor(), v); - - ++(*v.get()); - std::cout << "Now 43: " << *v.get() << std::endl; // must be 43 - - v = -1; - std::cout << "is > 0: " << std::boolalpha << staticVisit(CheckVisitor(), v) << std::endl; - - v = 1; // do not destruct, use assignment operator here - std::cout << "is > 0: " << std::boolalpha << staticVisit(CheckVisitor(), v) << std::endl; - - v = std::string("Hallo"); - std::cout << "is > 0: " << std::boolalpha << staticVisit(CheckVisitor(), v) << std::endl; - - return 0; -} diff --git a/include/simppl/attribute.h b/include/simppl/attribute.h index 036a74f..4b1bb51 100644 --- a/include/simppl/attribute.h +++ b/include/simppl/attribute.h @@ -8,7 +8,7 @@ namespace simppl { -namespace ipc +namespace dbus { /// partial update mode for container attributes of type vector @@ -62,7 +62,7 @@ struct Committed } }; -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/bind_adapter.h b/include/simppl/bind_adapter.h deleted file mode 100644 index 05563a2..0000000 --- a/include/simppl/bind_adapter.h +++ /dev/null @@ -1,128 +0,0 @@ -#ifndef SIMPPL_BIND_ADAPTER_H -#define SIMPPL_BIND_ADAPTER_H - - -#include - -#include "simppl/function_traits.h" -#include "simppl/if.h" - -#define BIND_ std::bind -#define IS_PLACEHOLDER_ std::is_placeholder - - -namespace simppl -{ - -namespace detail -{ - -template -struct f1_wrapper -{ - typedef ReturnT return_type; - - typedef Arg1T argument_type; - typedef Arg1T arg1_type; - - - explicit inline - f1_wrapper(const FunctorT& f) - : f_(f) - { - // NOOP - } - - inline - ReturnT operator()(Arg1T arg) - { - return f_(arg); - } - - inline - ReturnT operator()() - { - return f_(); - } - - FunctorT f_; -}; - - -/// deduce argument_type from placeholder position -template -struct get_argument_type_2 -{ - typedef typename if_::value, - typename TypeAt<0, typename FunctionTraits::param_type>::type, - typename TypeAt<1, typename FunctionTraits::param_type>::type>::type type; -}; - - -template -struct get_argument_type_3 -{ - typedef - typename if_::value, - typename TypeAt<0, typename FunctionTraits::param_type>::type, - typename if_::value, - typename TypeAt<1, typename FunctionTraits::param_type>::type, - typename TypeAt<2, typename FunctionTraits::param_type>::type>::type>::type - type; -}; - -} // namespace detail - - -// ordinary function forwarder - one argument function -template -inline -auto bind(FuncT func, Arg1T arg) - -> decltype(detail::f1_wrapper::return_type, typename TypeAt<0, typename FunctionTraits::param_type>::type, decltype(BIND_(func, arg))>(BIND_(func, arg))) -{ - typedef typename FunctionTraits::return_type return_type; - typedef typename TypeAt<0, typename FunctionTraits::param_type>::type arg_type; - - return detail::f1_wrapper(BIND_(func, arg)); -} - - -// binder for 2-argument functions (i.e. member functions with one argument - and 'this') -template -inline -auto bind(FunctionT f, Arg1T arg1, Arg2T arg2) - -> decltype(detail::f1_wrapper< - typename FunctionTraits::return_type, - typename detail::get_argument_type_2::type, - decltype(BIND_(f, arg1, arg2)) - >(BIND_(f, arg1, arg2))) -{ - typedef typename FunctionTraits::return_type return_type; - typedef typename detail::get_argument_type_2::type argument_type; - typedef decltype(BIND_(f, arg1, arg2)) functor_type; - - return detail::f1_wrapper(BIND_(f, arg1, arg2)); -} - - -// binder for 3-argument functions (i.e. member functions with two arguments - and 'this') -template -inline -auto bind(FunctionT f, Arg1T arg1, Arg2T arg2, Arg3T arg3) - -> decltype(detail::f1_wrapper< - typename FunctionTraits::return_type, - typename detail::get_argument_type_3::type, - decltype(BIND_(f, arg1, arg2, arg3)) - >(BIND_(f, arg1, arg2, arg3))) -{ - typedef typename FunctionTraits::return_type return_type; - typedef typename detail::get_argument_type_3::type argument_type; - typedef decltype(BIND_(f, arg1, arg2, arg3)) functor_type; - - return detail::f1_wrapper(BIND_(f, arg1, arg2, arg3)); -} - -} // namespace simppl - - -#endif // SIMPPL_BIND_ADAPTER_H diff --git a/include/simppl/blocking.h b/include/simppl/blocking.h index ffc899c..42bd3fb 100644 --- a/include/simppl/blocking.h +++ b/include/simppl/blocking.h @@ -5,7 +5,7 @@ namespace simppl { -namespace ipc +namespace dbus { struct Dispatcher; @@ -18,35 +18,35 @@ namespace detail template struct BlockingResponseHandler { - BlockingResponseHandler(simppl::ipc::Dispatcher& disp, simppl::ipc::ClientResponse& r, T& t); + BlockingResponseHandler(simppl::dbus::Dispatcher& disp, simppl::dbus::ClientResponse& r, T& t); - void operator()(const simppl::ipc::CallState& state, typename CallTraits::param_type t); + void operator()(const simppl::dbus::CallState& state, typename CallTraits::param_type t); private: T& t_; - simppl::ipc::Dispatcher& disp_; - simppl::ipc::ClientResponse& r_; + simppl::dbus::Dispatcher& disp_; + simppl::dbus::ClientResponse& r_; }; template struct BlockingResponseHandlerN { - BlockingResponseHandlerN(simppl::ipc::Dispatcher& disp, simppl::ipc::ClientResponse& r, std::tuple& t); + BlockingResponseHandlerN(simppl::dbus::Dispatcher& disp, simppl::dbus::ClientResponse& r, std::tuple& t); - void operator()(const simppl::ipc::CallState& state, typename CallTraits::param_type... t); + void operator()(const simppl::dbus::CallState& state, typename CallTraits::param_type... t); private: std::tuple& t_; - simppl::ipc::Dispatcher& disp_; - simppl::ipc::ClientResponse& r_; + simppl::dbus::Dispatcher& disp_; + simppl::dbus::ClientResponse& r_; }; } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl @@ -57,7 +57,7 @@ struct BlockingResponseHandlerN namespace simppl { -namespace ipc +namespace dbus { @@ -93,7 +93,7 @@ namespace detail template inline -BlockingResponseHandler::BlockingResponseHandler(simppl::ipc::Dispatcher& disp, simppl::ipc::ClientResponse& r, T& t) +BlockingResponseHandler::BlockingResponseHandler(simppl::dbus::Dispatcher& disp, simppl::dbus::ClientResponse& r, T& t) : t_(t) , disp_(disp) , r_(r) @@ -103,7 +103,7 @@ BlockingResponseHandler::BlockingResponseHandler(simppl::ipc::Dispatcher& dis template -void BlockingResponseHandler::operator()(const simppl::ipc::CallState& state, typename CallTraits::param_type t) +void BlockingResponseHandler::operator()(const simppl::dbus::CallState& state, typename CallTraits::param_type t) { disp_.stop(); r_.handledBy(std::nullptr_t()); @@ -119,7 +119,7 @@ void BlockingResponseHandler::operator()(const simppl::ipc::CallState& state, template inline -BlockingResponseHandlerN::BlockingResponseHandlerN(simppl::ipc::Dispatcher& disp, simppl::ipc::ClientResponse& r, std::tuple& t) +BlockingResponseHandlerN::BlockingResponseHandlerN(simppl::dbus::Dispatcher& disp, simppl::dbus::ClientResponse& r, std::tuple& t) : t_(t) , disp_(disp) , r_(r) @@ -129,7 +129,7 @@ BlockingResponseHandlerN::BlockingResponseHandlerN(simppl::ipc::Dispatcher template -void BlockingResponseHandlerN::operator()(const simppl::ipc::CallState& state, typename CallTraits::param_type... t) +void BlockingResponseHandlerN::operator()(const simppl::dbus::CallState& state, typename CallTraits::param_type... t) { disp_.stop(); r_.handledBy(std::nullptr_t()); @@ -143,7 +143,7 @@ void BlockingResponseHandlerN::operator()(const simppl::ipc::CallState& st } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl @@ -158,7 +158,7 @@ void BlockingResponseHandlerN::operator()(const simppl::ipc::CallState& st * bool rc = stub.func() >> ret; */ inline -void operator>>(simppl::ipc::detail::ClientResponseHolder holder, std::nullptr_t) +void operator>>(simppl::dbus::detail::ClientResponseHolder holder, std::nullptr_t) { holder.dispatcher_.waitForResponse(holder); } @@ -172,7 +172,7 @@ void operator>>(simppl::ipc::detail::ClientResponseHolder holder, std::nullptr_t */ template inline -void operator>>(simppl::ipc::detail::ClientResponseHolder holder, T& rArg) +void operator>>(simppl::dbus::detail::ClientResponseHolder holder, T& rArg) { holder.dispatcher_.waitForResponse(holder, rArg); } @@ -186,7 +186,7 @@ void operator>>(simppl::ipc::detail::ClientResponseHolder holder, T& rArg) */ template inline -void operator>>(simppl::ipc::detail::ClientResponseHolder holder, std::tuple& rArgs) +void operator>>(simppl::dbus::detail::ClientResponseHolder holder, std::tuple& rArgs) { holder.dispatcher_.waitForResponse(holder, rArgs); } @@ -201,7 +201,7 @@ void operator>>(simppl::ipc::detail::ClientResponseHolder holder, std::tuple inline -void operator>>(simppl::ipc::detail::ClientResponseHolder holder, std::tuple rArgs) +void operator>>(simppl::dbus::detail::ClientResponseHolder holder, std::tuple rArgs) { std::tuple t; holder.dispatcher_.waitForResponse(holder, t); diff --git a/include/simppl/brokerclient.h b/include/simppl/brokerclient.h deleted file mode 100644 index d33d53d..0000000 --- a/include/simppl/brokerclient.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef SIMPPL_BROKERCLIENT_H -#define SIMPPL_BROKERCLIENT_H - - -#include - - -namespace simppl -{ - -namespace ipc -{ - -// forward decl -struct Dispatcher; - - -struct BrokerClient -{ - BrokerClient(Dispatcher& disp); - ~BrokerClient(); - - void registerService(const std::string& fullName, const std::string& location); - - void waitForService(const std::string& fullName, std::function func); - - -private: - - BrokerClient(const BrokerClient&) = delete; - BrokerClient& operator=(const BrokerClient&) = delete; - - struct BrokerStub; - BrokerStub* stub_; -}; - -} // namespace ipc - -} // namespace simppl - - -#endif // SIMPPL_BROKERCLIENT_H diff --git a/include/simppl/callstate.h b/include/simppl/callstate.h index b11073c..24ee3bb 100644 --- a/include/simppl/callstate.h +++ b/include/simppl/callstate.h @@ -11,7 +11,7 @@ namespace simppl { -namespace ipc +namespace dbus { struct CallState @@ -100,7 +100,7 @@ struct CallState uint32_t sequence_nr_; }; -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/clientside.h b/include/simppl/clientside.h index e0d7967..8c6fa7f 100644 --- a/include/simppl/clientside.h +++ b/include/simppl/clientside.h @@ -22,7 +22,7 @@ namespace simppl { -namespace ipc +namespace dbus { // forward decl @@ -272,7 +272,7 @@ struct ClientRequest : ClientRequestBase { StubBase* stub = dynamic_cast(parent_); - std::function f(std::bind(&simppl::ipc::detail::serializeN::param_type...>, std::placeholders::_1, t...)); + std::function f(std::bind(&simppl::dbus::detail::serializeN::param_type...>, std::placeholders::_1, t...)); return detail::ClientResponseHolder(stub->disp(), handler_, stub->sendRequest(*this, f)); } @@ -356,14 +356,14 @@ struct ClientResponse : ClientResponseBase }; -} // namespace ipc +} // namespace dbus } // namespace simppl template inline -simppl::ipc::ClientResponse& operator>>(simppl::ipc::ClientResponse& r, const FunctorT& f) +simppl::dbus::ClientResponse& operator>>(simppl::dbus::ClientResponse& r, const FunctorT& f) { r.handledBy(f); return r; @@ -372,7 +372,7 @@ simppl::ipc::ClientResponse& operator>>(simppl::ipc::ClientResponse& template inline -void operator>>(simppl::ipc::ClientAttribute& attr, const FuncT& func) +void operator>>(simppl::dbus::ClientAttribute& attr, const FuncT& func) { attr.handledBy(func); } @@ -380,7 +380,7 @@ void operator>>(simppl::ipc::ClientAttribute& attr, const Fun template inline -void operator>>(simppl::ipc::ClientSignal& sig, const FuncT& func) +void operator>>(simppl::dbus::ClientSignal& sig, const FuncT& func) { sig.handledBy(func); } diff --git a/include/simppl/cmdline.h b/include/simppl/cmdline.h deleted file mode 100644 index 6ed74c2..0000000 --- a/include/simppl/cmdline.h +++ /dev/null @@ -1,2179 +0,0 @@ -#ifndef SIMPPL_CMDLINE_H -#define SIMPPL_CMDLINE_H - - -#include -#include -#include - -// add support for string and vector in option handlers -#define CMDLINE_HAVE_STD_STRING 1 -#define CMDLINE_HAVE_STD_VECTOR 1 - -// undefine this if you want to generate parser output via printf instead of STL streams -#define CMDLINE_HAVE_STL_STREAMS 1 - -#ifdef CMDLINE_HAVE_STD_STRING -# include -#endif - -#ifdef CMDLINE_HAVE_STD_VECTOR -# include -#endif - -#ifndef NDEBUG -# define CMDLINE_ENABLE_RUNTIME_CHECK 1 -# include -#endif - -#ifdef CMDLINE_HAVE_STL_STREAMS -# include -# include - -// that's how the parser help output is formatted - change the define prior to the inclusion to a value that -// fits your needs if you want to change the indentation. -# ifndef PARSER_DESCRIPTION_INDENTATION -# define PARSER_DESCRIPTION_INDENTATION 20 -# endif - -# define PARSER_STDOUT_STREAM std::cout -# define PARSER_STDERR_STREAM std::cerr - -#else -#include - -# define PARSER_STDOUT_STREAM stdout -# define PARSER_STDERR_STREAM stderr -#endif - -#include "tribool.h" -#include "typelist.h" -#include "noninstantiable.h" - - -namespace simppl -{ - -namespace cmdline -{ - -/*TODO move to impl file and declare extern*/ -static const char NoChar = '*'; - -namespace detail -{ - -// forward decls -template -struct LongSwitch; - -template -struct HandlerComposite; - -template -struct HandlerCompositeBase; - - -#ifdef CMDLINE_HAVE_STL_STREAMS -typedef std::ostream stream_type; -#else -typedef FILE* stream_type; -#endif - - -/*TODO move to impl file and declare extern*/ -static bool longOptionSupport = false; ///< FIXME this is a runtime variable which cannot be optimized out at compile-time -static int extraOptionCounter = 0; - -struct NoChar; ///< extra options make this entry into the typelist if they are not mandatory -struct MandatoryNoChar; ///< extra options make this entry into the typelist if they are mandatory -struct MultiNoChar; ///< extra options make this entry into the typelist if they are a multi-type - -/** - * Internal parser state. - */ -struct ParserState -{ - ParserState(int argc, char** argv) - : argc_(argc) - , argv_(argv) - , current_(1) // skip application name - , argument_(0) - { - //::memset(handled_, 0 , sizeof(handled_)); - } - - const char* progname() const - { - // strip off a leading path - char* ptr = argv_[0] + strlen(argv_[0]); - - while(ptr > argv_[0] && *ptr != '/') - --ptr; - - if (*ptr == '/') - ++ptr; - - return ptr; - } - - int argc_; - char** argv_; - - int current_; ///< current position in argv - const char* argument_; ///< current position of argument (_very_ mutable member) - -#ifdef CMDLINE_ENABLE_RUNTIME_CHECK - std::set arguments_; - std::set longArguments_; -#endif -}; - - -/// mandatory extra options after optional ones are not assignable -template -struct CheckMandatoryAfterOptionalExtraOption -{ - enum - { - idx_first_optional = Find::value, - idx_followed_mandatory = idx_first_optional != -1 ? Find::type>::value : -1, - - value = idx_first_optional == -1 || idx_followed_mandatory == -1 || (idx_first_optional != -1 && idx_followed_mandatory == -1) - }; -}; - - -/// multiple optional extra options are forbidden, use the Multi-policy instead -template -struct CheckMultipleOptionalExtraOptions -{ - enum { value = Count::value < 2 }; -}; - - -/// find an extra option in the given list and return the (quite arbitrary) position -template -struct FindExtra -{ - enum - { - idx_mandatory = Find::value, - idx_optional = Find::value, - idx_multi = Find::value, - - value = idx_mandatory + idx_optional + idx_optional + 2 // position is somewhat senseless but we are only interested in if there is one - }; -}; - - -/// check if there are further extra options after a given MultiExtraOption which is currently not parseable -template -struct CheckFurtherExtraOptionAfterMultiExtraOption -{ - enum - { - idx_first_multi = Find::value, - idx_followed_extra = idx_first_multi != -1 ? FindExtra::type>::value : -1, - - value = idx_first_multi == -1 || idx_followed_extra == -1 || (idx_first_multi != -1 && idx_followed_extra == -1) - }; -}; - - -template -struct IsExtraOption -{ - enum { value = std::is_same::value || std::is_same::value || std::is_same::value }; -}; - - -// construct a complete typelist from simple type -template -struct MakeTypeList -{ - typedef TypeList type; -}; - -// do nothing, it is already a typelist -template -struct MakeTypeList > -{ - typedef TypeList type; -}; - - -} // namespace detail - - -// ----------------------------------------------------------------------------------------------------- - - -/// Just ignore unknown (and therefore unhandled) options. -class IgnoreUnknown : NonInstantiable -{ -protected: - - static inline - bool eval(simppl::cmdline::detail::ParserState&) - { - return true; - } -}; - - - - -/// Report unknown (and therefore unhandled) options. Make the parser returning a failure. -class ReportUnknown : NonInstantiable -{ -protected: - - static inline - bool eval(simppl::cmdline::detail::ParserState& state) - { -#ifdef CMDLINE_HAVE_STL_STREAMS - PARSER_STDERR_STREAM << "Unknown or multiple option '" << state.argv_[state.current_] << "' encountered." << std::endl; -#else - fprintf(PARSER_STDERR_STREAM, "Unknown or multiple option '%s' encountered.\n", state.argv_[state.current_]); -#endif - return false; - } -}; - - -// ----------------------------------------------------------------------------------------------------- - - -/// Print the parsers usage string. -class DefaultUsagePrinter -{ - template friend struct LongOptionSupport; - template friend struct NoLongOptionSupport; - -protected: - - inline - void operator()(detail::stream_type&) - { - // NOOP - } - - template - static - void eval(InheriterT* usage, detail::stream_type& os, const ParserT& parser, const char* progname) - { - if (usage) - (*usage)(os); - - simppl::cmdline::detail::extraOptionCounter = 0; - -#ifdef CMDLINE_HAVE_STL_STREAMS - os << std::endl; - os << "Usage: " << progname << ' '; - parser.genCmdline(os); - os << std::endl << std::endl; -#else - fprintf(os, "\nUsage: %s ", progname); - parser.genCmdline(os); - fprintf(os, "\n\n"); -#endif - - simppl::cmdline::detail::extraOptionCounter = 0; - parser.doDoc(os); - } -}; - - -/// Do not print anything about the usage (less memory footprint and code size). -class NoopUsagePrinter -{ - template friend struct LongOptionSupport; - template friend struct NoLongOptionSupport; - -protected: - - inline - void operator()(detail::stream_type&) - { - // NOOP - } - - template - static inline - void eval(InheriterT* usage, detail::stream_type& os, const ParserT&, const char*) - { - if (usage) - (*usage)(os); - } -}; - - -// ----------------------------------------------------------------------------------------------------- - - -/// Enable long options. -template -struct LongOptionSupport : NonInstantiable -{ - enum { longSupport = true }; - - template - static - tribool eval(ParserT& parser, simppl::cmdline::detail::ParserState& state) - { - tribool rc; - - if (state.argv_[state.current_][2] != '\0') - rc = parser.eval(state.argv_[state.current_]+2, state); - - if (indeterminate(rc)) - { - if (!strcmp(state.argv_[state.current_]+2, "help")) - { - UsagePrinterT usage; - UsagePrinterT::eval(&usage, PARSER_STDERR_STREAM, parser, state.progname()); - exit(EXIT_SUCCESS); - } - } - - return rc; - } -}; - - -/// Disable long options, even for those registered as long options. -template -struct NoLongOptionSupport : NonInstantiable -{ - enum { longSupport = false }; - - template - static inline - tribool eval(ParserT&, simppl::cmdline::detail::ParserState&) - { - // never accept long-only arguments in NoLongOptionSupport policy chosen - typedef typename Reverse::type>::type arguments_type; - static_assert(Find, arguments_type>::value < 0, "no_nochar_options_allowed_with_no_long_option_support_policy"); - - return indeterminate; - } -}; - - -// ----------------------------------------------------------------------------------------------------- - - -/** - * The commandline parser generator. - */ -template class LongOptionSupportPolicyT = LongOptionSupport - , typename UsagePrinterT = DefaultUsagePrinter> -struct Parser : protected UnknownPolicyT, protected UsagePrinterT -{ - // TODO could be a ParserT&& argument when -std=c++0x support is enabled - // so the const_cast could be avoided in order to remove the 'const' on all handlers - template - static - bool parse(int argc, char** argv, const ParserT& parser) - { - typedef typename Reverse::type>::type arguments_type; - - // checks on extra options - static_assert(simppl::cmdline::detail::CheckMandatoryAfterOptionalExtraOption::value, "mandatory_after_optional_extraoption_is_nonsense"); - static_assert(simppl::cmdline::detail::CheckMultipleOptionalExtraOptions::value, "multiple_optional_extraoptions_are_nonsense"); - static_assert(simppl::cmdline::detail::CheckFurtherExtraOptionAfterMultiExtraOption::value, "no_extra_option_after_multi_extra_option_allowed"); - - ParserT& _parser = const_cast(parser); - return doParse(argc, argv, _parser); - } - - -private: - - static - bool evaluateReturnValue(tribool rc, simppl::cmdline::detail::ParserState& state) - { - if (indeterminate(rc)) - { - if (!UnknownPolicyT::eval(state)) - return false; - } - else if (!rc) - { -#ifdef CMDLINE_HAVE_STL_STREAMS - PARSER_STDERR_STREAM << "Error in evaluation of option '" << state.argv_[state.current_] << "'." << std::endl; -#else - fprintf(PARSER_STDERR_STREAM, "Error in evaluation of option '%s'.\n", state.argv_[state.current_]); -#endif - return false; - } - - return true; - } - - - template - static - bool doParse(int argc, char** argv, ParserT& parser) - { - typedef typename simppl::cmdline::detail::MakeTypeList::type arguments_type; - simppl::cmdline::detail::longOptionSupport = LongOptionSupportPolicyT::longSupport; - - // don't accept -h - static_assert(Find, arguments_type>::value < 0, "h_is_reserved_for_help"); - - simppl::cmdline::detail::ParserState state(argc, argv); - -#ifdef CMDLINE_ENABLE_RUNTIME_CHECK - if (!parser.plausibilityCheck(state) || state.longArguments_.find("help") != state.longArguments_.end()) - { -# ifdef CMDLINE_HAVE_STL_STREAMS - PARSER_STDOUT_STREAM << "parser grammar error - multiple same switch arguments or 'help' detected." << std::endl; -# else - fprintf(PARSER_STDOUT_STREAM, "parser grammar error - multiple same switch arguments or 'help' detected.\n"); -# endif - ::abort(); - } - else - { - state.arguments_.clear(); - state.longArguments_.clear(); - } -#endif - - tribool rc; - - for (; state.current_ < argc; ++state.current_) - { - if (argv[state.current_][0] == '-') - { - if (argv[state.current_][1] == '-') - { - rc = LongOptionSupportPolicyT::eval(parser, state); - } - else if (argv[state.current_][1] == 'h' && argv[state.current_][2] == '\0') - { - UsagePrinterT usage; - UsagePrinterT::eval(&usage, PARSER_STDOUT_STREAM, parser, state.progname()); - exit(EXIT_SUCCESS); - } - else - { - // enable old-style -xvf like in 'tar', - const char* c = argv[state.current_]; - while(*++c != '\0') - { - rc = parser.eval(*c, state); - if (!evaluateReturnValue(rc, state)) - return false; - } - } - } - else - rc = parser.eval(state); - - if (!evaluateReturnValue(rc, state)) - return false; - } - - if (!parser.ok()) - { -#ifdef CMDLINE_HAVE_STL_STREAMS - PARSER_STDOUT_STREAM << "Missing mandatory options." << std::endl; -#else - fprintf(PARSER_STDOUT_STREAM, "Missing mandatory options.\n"); -#endif - UsagePrinterT::eval((UsagePrinterT*)0, PARSER_STDERR_STREAM, parser, state.progname()); - return false; - } - - return true; - } -}; - - -// ------------------------------------------------------------------------------------ - - -namespace detail -{ - -template -struct DocumentationHelper -{ - static inline - void eval(detail::stream_type& os, const char* longopt, const char* doc) - { -#ifdef CMDLINE_HAVE_STL_STREAMS - os << '-' << Argument << "|--" << std::left << std::setw(PARSER_DESCRIPTION_INDENTATION-4) << longopt << doc << std::endl; -#else - fprintf(os, "-%c|--%-16s %s\n", Argument, longopt, doc); -#endif - } -}; - -template<> -struct DocumentationHelper -{ - static inline - void eval(detail::stream_type& os, const char* longopt, const char* doc) - { -#ifdef CMDLINE_HAVE_STL_STREAMS - os << "--" << std::left << std::setw(PARSER_DESCRIPTION_INDENTATION-1) << longopt << doc << std::endl; -#else - fprintf(os, "--%-19s %s\n", longopt, doc); -#endif - } -}; - - -/// Documentation policy for command line argument. -struct Documentation -{ - inline - Documentation(const char* doc) - : doc_(doc) - { - // NOOP - } - - // switches - template - inline - void doDoc_(detail::stream_type& os) const - { -#ifdef CMDLINE_HAVE_STL_STREAMS - os << '-' << std::left << std::setw(PARSER_DESCRIPTION_INDENTATION) << Argument << doc_ << std::endl; -#else - fprintf(os, "-%-20c %s\n", Argument, doc_); -#endif - } - - /// long option support - template - inline - void doDoc_(detail::stream_type& os, const char* longopt) const - { - detail::DocumentationHelper::eval(os, longopt, doc_); - } - - /// extra option support - inline - void doDoc_(detail::stream_type& os) const - { -#ifdef CMDLINE_HAVE_STL_STREAMS - ++simppl::cmdline::detail::extraOptionCounter; - os << " " << doc_ << std::endl; -#else - fprintf(os, "%-15c %s\n", ++simppl::cmdline::detail::extraOptionCounter, ' ', doc_); -#endif - } - - const char* doc_; -}; - - -/// Documentation policy for command line argument - a NOOP. -struct NoDocumentation -{ - template - inline - void doDoc_(detail::stream_type&) const - { - // NOOP - } - - template - inline - void doDoc_(detail::stream_type&, const char* /*longopt*/) const - { - // NOOP - } - - inline - void doDoc_(detail::stream_type&) const - { - // NOOP - } -}; - -} // end namespace detail - - -// --------------------------------------------------------------------------- - - -/** - * Argument policy. An argument using this policy is optional and must not be - * given at the commandline. - */ -class Optional -{ - template friend struct detail::LongSwitch; - template friend struct detail::HandlerComposite; - -protected: - - inline - bool ok() const - { - return true; - } - - inline - bool ok(bool b) - { - return b; - } - - template - inline - void genCmdline(detail::stream_type& os, char arg) const - { -#ifdef CMDLINE_HAVE_STL_STREAMS - os << "[-" << arg << (HaveArgument?" ] ":"] "); -#else - fprintf(os, "[-%c%s] ", arg, HaveArgument?" ":""); -#endif - } - - template - struct Helper - { - static inline - void eval(detail::stream_type& os, const char* long__) - { -#ifdef CMDLINE_HAVE_STL_STREAMS - os << "[-" << Argument << (HaveArgument?" |--":"|--") << long__ << (HaveArgument?"=] ":"] "); -#else - fprintf(os, "[-%c %s|--%s%s] ", Argument, long__, HaveArgument?" ":"", HaveArgument?"=":""); -#endif - } - }; - - template - struct Helper - { - static inline - void eval(detail::stream_type& os, const char* long__) - { -#ifdef CMDLINE_HAVE_STL_STREAMS - os << "[--" << long__ << (HaveArgument?"=] ":"] "); -#else - fprintf(os, "[--%s%s] ", long__, HaveArgument?"=":""); -#endif - } - }; - - template - inline - void genCmdline(detail::stream_type& os, const char* long__) const - { - Helper::eval(os, long__); - } - - inline - void genCmdline(detail::stream_type& os, const char* ext) const - { -#ifdef CMDLINE_HAVE_STL_STREAMS - os << "[] "; -#else - fprintf(os, "[] ", ext); -#endif - } -}; - - -/** - * Argument Policy. The using argument must be given at the commandline, otherwise the parser - * reports an error. - */ -class Mandatory -{ - template friend struct detail::LongSwitch; - template friend struct detail::HandlerComposite; - -protected: - - inline - Mandatory() - : ok_(false) - { - // NOOP - } - - inline - bool ok() const - { - return ok_; - } - - inline - bool ok(bool b) - { - ok_ |= b; // set it to true one time, dont change later on - return b; - } - - template - inline - void genCmdline(detail::stream_type& os, char arg) const - { -#ifdef CMDLINE_HAVE_STL_STREAMS - os << '-' << arg << (HaveArgument?" ":" "); -#else - fprintf(os, "-%c %s", arg, HaveArgument?" ":""); -#endif - - } - - template - struct Helper - { - static inline - void eval(detail::stream_type& os, const char* long__) - { -#ifdef CMDLINE_HAVE_STL_STREAMS - os << '-' << Argument << (HaveArgument?" |--":"|--") << long__ << (HaveArgument?"= ":" "); -#else - fprintf(os, "-%c %s|--%s=%s", Argument, HaveArgument?"":"", long__, HaveArgument?" ":""); -#endif - } - }; - - template - struct Helper - { - static inline - void eval(detail::stream_type& os, const char* long__) - { -#ifdef CMDLINE_HAVE_STL_STREAMS - os << "--" << long__ << (HaveArgument?"= ":" "); -#else - fprintf(os, "--%s=%s", long__, HaveArgument?" ":""); -#endif - } - }; - - template - inline - void genCmdline(detail::stream_type& os, const char* long__) const - { - Helper::eval(os, long__); - } - - inline - void genCmdline(detail::stream_type& os, const char* ext) const - { -#ifdef CMDLINE_HAVE_STL_STREAMS - os << " "; -#else - fprintf(os, "", ++simppl::cmdline::detail::extraOptionCounter, ext); -#endif - } - - bool ok_; -}; - - -// --------------------------------------------------------------------------- - - -namespace detail -{ - -/// checker for options -template -struct OptionChecker -{ - static - bool eval(ParserState& state) - { - // make sure there is an option - if (state.current_ < state.argc_ && *state.argv_[state.current_] != '-') - { - state.argument_ = state.argv_[state.current_]; - return true; - } - - return false; - } -}; - - -/// checker for switches (trivial) -template<> -struct OptionChecker -{ - static inline - bool eval(ParserState&) - { - return true; - } -}; - - -template -struct EqualityComparator -{ - static inline - bool eval(char c) - { - return Argument == c; - } -}; - -struct InEquality -{ - static inline - bool eval(char) - { - return false; - } -}; - - -static /*TODO move to impl file*/ -bool checkOption(char theChar, char Argument, ParserState& state) -{ - const char* arg = state.argv_[state.current_]; - - // must not be already given - //if (::strchr(state.handled_, theChar) == 0) - //{ - // add the option to the list of handled options to avoid multiple defined options - //::strncat(state.handled_, &theChar, 1); - - // make sure it is the last in a multi commandline arg like e.g. in tar xvzf - return arg[2] == '\0' || arg[strlen(arg)-1] == Argument; - //} - - //return false; -} - - -template -struct LongOptionChecker -{ - static - bool eval(const char* option, const char* current, ParserState& state) - { - int len = strlen(option); - if (!::strncmp(option, current, len) && current[len] == '=') - { - state.argument_ = current + len + 1; - return true; - } - return false; - } -}; - - -template<> -struct LongOptionChecker -{ - static inline - bool eval(const char* option, const char* current, ParserState&) - { - return !::strcmp(option, current); - } -}; - - -struct MultiSupport -{ - inline - bool handled() const - { - return false; - } - - inline - bool isHandled() const - { - return false; - } - - inline - bool setHandled() - { - return true; - } - - inline - const char* cmdlineExtension() const - { - return ", ..."; - } -}; - - -struct NoMultiSupport -{ - inline - NoMultiSupport() - : handled_(false) - { - // NOOP - } - - inline - bool handled() - { - bool rc = handled_; - handled_ = true; - return rc; - } - - inline - bool isHandled() const - { - return handled_; - } - - inline - bool setHandled() - { - handled_ = true; - return handled_; - } - - inline - const char* cmdlineExtension() const - { - return ""; - } - - bool handled_; -}; - - -// template forward declaration -template -struct LongSwitch; - -} // namespace detail - - -/** - * The baseclass for all options and switches. - */ -template -struct Switch : MandatoryT, DocumentationT, MultiSupportT -{ - template friend struct detail::HandlerComposite; - template friend struct detail::HandlerCompositeBase; - template friend struct detail::LongSwitch; - - static_assert(haveArgument == true || std::is_same::value, "mandatory_switches_are_senseless"); - static_assert((Argument >= 48 && Argument <=57) - || (Argument >=65 && Argument <=90) - || (Argument >=97 && Argument <=122) - || Argument == simppl::cmdline::NoChar, - "switch_argument_only_valid_in_0123456789abcdefgijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); - - typedef char_ char_type; - typedef typename if_ >::type equality_check_type; - - enum { LongSupport = false, HaveArgument = haveArgument }; - - -protected: - - inline explicit - Switch(const char* doc) - : MandatoryT() - , MultiSupportT() - , DocumentationT(doc) - { - // NOOP - } - - -public: - - inline - Switch() - : MandatoryT() - , MultiSupportT() - , DocumentationT() - { - // NOOP - } - - inline - Switch - doc(const char* doc) - { - return Switch(doc); - } - - inline - detail::LongSwitch - operator[](const char* long__) - { - return detail::LongSwitch(long__); - } - - -protected: - - bool operator()(char c, detail::ParserState& state) - { - if (!MultiSupportT::isHandled()) - { - return MandatoryT::ok(equality_check_type::eval(c) && (HaveArgument == false ? true : detail::checkOption(c, Argument, state)) && MultiSupportT::setHandled()); - } - else - return false; - } - - inline - void doDoc(detail::stream_type& os) const - { - DocumentationT::template doDoc_(os); - } - - inline - void genCmdline(detail::stream_type& os) const - { - MandatoryT::template genCmdline(os, Argument); - } - - inline - void genCmdline(detail::stream_type& os, const char* long__) const - { - MandatoryT::template genCmdline(os, long__); - } - - inline - bool ok() const - { - return MandatoryT::ok(); - } - -#ifdef CMDLINE_ENABLE_RUNTIME_CHECK - // this check here is mainly interesting only if extension points are part of the grammar - // TODO maybe we can determine whether we need to do that or not before so no code is generated if possible - inline - bool plausibilityCheck(simppl::cmdline::detail::ParserState& state) const - { - if (Argument == simppl::cmdline::NoChar) - { - return true; - } - else - { - bool rc = state.arguments_.find(Argument) == state.arguments_.end(); - state.arguments_.insert(Argument); - return rc; - } - } -#endif -}; - - -/** - * An ordinary commandline option. - */ -template -struct Option : Switch -{ - template friend struct detail::HandlerCompositeBase; - - inline - Option() - : Switch() - { - // NOOP - } -}; - - -/** - * A commandline option that could appear multiple times. - */ -template -struct MultiOption : Option -{ - template friend struct detail::HandlerCompositeBase; - - inline - MultiOption() - : Option() - { - // NOOP - } -}; - - -template -struct ExtraOption : MandatoryT, MultiSupportT, DocumentationT -{ - template friend struct detail::HandlerComposite; - template friend struct detail::HandlerCompositeBase; - template friend struct detail::LongSwitch; - - typedef typename if_::value, - simppl::cmdline::detail::MultiNoChar, - typename if_::value, simppl::cmdline::detail::MandatoryNoChar, simppl::cmdline::detail::NoChar>::type>::type char_type; - - inline - ExtraOption() - : MandatoryT() - , MultiSupportT() - , DocumentationT() - { - // NOOP - } - - inline - ExtraOption - doc(const char* doc) - { - return ExtraOption(doc); - } - - // FIXME why this must be public? - inline explicit - ExtraOption(const char* doc) - : MandatoryT() - , MultiSupportT() - , DocumentationT(doc) - { - // NOOP - } - - -protected: - - inline - tribool operator()(simppl::cmdline::detail::ParserState& state) - { - if (!MultiSupportT::handled()) - { - state.argument_ = state.argv_[state.current_]; - return MandatoryT::ok(true); - } - else - return indeterminate; // just skip it... - } - - inline - void doDoc(detail::stream_type& os) const - { - DocumentationT::doDoc_(os); - } - - inline - void genCmdline(detail::stream_type& os) const - { - MandatoryT::genCmdline(os, MultiSupportT::cmdlineExtension()); - } - -#ifdef CMDLINE_ENABLE_RUNTIME_CHECK - inline - bool plausibilityCheck(simppl::cmdline::detail::ParserState& /*state*/) const - { - return true; - } -#endif -}; - - -template -struct MultiExtraOption : ExtraOption -{ - inline - MultiExtraOption() - : ExtraOption() - { - // NOOP - } -}; - - -// forward declaration -struct ExtensionPoint; - - -namespace detail -{ - -template -struct LongSwitch -{ - typedef char_ char_type; - - enum { LongSupport = true, HaveArgument = haveArgument }; - - inline - LongSwitch(const char* long__) - : switch_() - , long_(long__) - { - // NOOP - } - - inline - LongSwitch(const char* long__, const char* doc) - : switch_(doc) - , long_(long__) - { - // NOOP - } - - inline - LongSwitch - doc(const char* doc) - { - return LongSwitch(long_, doc); - } - - inline - bool operator()(char c, ParserState& state) - { - return switch_(c, state); - } - - //inline - bool operator()(const char* longopt, ParserState& state) - { - if (!switch_.isHandled()) - { - return switch_.MandatoryT::ok(LongOptionChecker::eval(long_, longopt, state)) && switch_.setHandled(); - } - else - return false; - } - - //inline - void doDoc(detail::stream_type& os) const - { - if (simppl::cmdline::detail::longOptionSupport) - { - switch_.template doDoc_(os, long_); - } - else - switch_.template doDoc_(os); - } - - //inline - void genCmdline(detail::stream_type& os) const - { - if (simppl::cmdline::detail::longOptionSupport) - { - switch_.genCmdline(os, long_); - } - else - switch_.genCmdline(os); - } - - inline - bool ok() const - { - return switch_.ok(); - } - -#ifdef CMDLINE_ENABLE_RUNTIME_CHECK - //inline - bool plausibilityCheck(ParserState& state) const - { - bool rc = switch_.plausibilityCheck(state) && state.longArguments_.find(long_) == state.longArguments_.end(); - state.longArguments_.insert(long_); - return rc; - } -#endif - - Switch switch_; - const char* long_; -}; - - -// -------------------------------------------------------------------------------- - - -// NOOP handler for const char* and std::string -template -struct Converter -{ - static inline - typename std::remove_reference::type eval(const char* ptr, bool&) - { - return ptr; - } -}; - - -template<> -struct Converter -{ - static inline - char* eval(const char* ptr, bool&) - { - return const_cast(ptr); - } -}; - - -int convert(const char* ptr, bool& success) -{ - int base = 10; - - if (*ptr == '0' && *(ptr+1) != '\0') - { - base = 8; - - if (*(ptr+1) == 'x') - base = 16; - } - - char* end; - int rc = strtol(ptr, &end, base); - success = (*end == '\0'); - - return rc; -} - - -template -struct IntConverterBase -{ - static inline - T eval(const char* ptr, bool& success) - { - int rc = convert(ptr, success); - success &= (rc >= std::numeric_limits::min() && rc <= std::numeric_limits::max()); - return rc; - } -}; - - -template<> -struct Converter : public IntConverterBase -{ -}; - -template<> -struct Converter : public IntConverterBase -{ -}; - -template<> -struct Converter : public IntConverterBase -{ -}; - -template<> -struct Converter : public IntConverterBase -{ -}; - -template<> -struct Converter : public IntConverterBase -{ -}; - -template<> -struct Converter : public IntConverterBase -{ -}; - -template<> -struct Converter : public IntConverterBase -{ -}; - - -// -------------------------------------------------------------------------------- - - -template -struct FunctionArgumentTypeDeducer -{ - // must be a bound member function... - typedef typename ObjT::arg1_type argument_type; -}; - - -template -struct FunctionArgumentTypeDeducer -{ - // ...or an ordinary free function - typedef ArgumentT argument_type; -}; - - -// ------------------------------------------------------------------------------- - - -// for switches -template -struct ActionCaller -{ - template - static inline - bool eval(ActionT& a, ParserState&) - { - (void)a(); - return true; - } -}; - - -// for switches -template<> -struct ActionCaller -{ - template - static inline - bool eval(ActionT& a, ParserState&) - { - return a(); - } -}; - - -// for options and extraoptions -template -struct ActionCaller -{ - template - static inline - bool eval(ActionT& a, ParserState& state) - { - typedef typename FunctionArgumentTypeDeducer::argument_type action_argument_type; - - bool success = true; - (void)a(Converter::eval(state.argument_, success)); - return success; - } -}; - - -// for options and extraoptions -template<> -struct ActionCaller -{ - template - static inline - bool eval(ActionT& a, ParserState& state) - { - typedef typename FunctionArgumentTypeDeducer::argument_type action_argument_type; - - bool success = true; - return a(Converter::eval(state.argument_, success)) && success; - } -}; - - -// ---------------------------------------------------------------------------------------------- - - -template -struct FunctionReturnTypeDeducer -{ - // must be a bound member function... - typedef typename ObjT::return_type return_type; -}; - - -template -struct FunctionReturnTypeDeducer -{ - // ...or an ordinary free function with no argument (the switch case) - typedef ReturnT return_type; -}; - - -template -struct FunctionReturnTypeDeducer -{ - // ...or an ordinary free function with one argument (the option case) - typedef ReturnT return_type; -}; - - -// ------------------------------------------------------------------------------------------ - - -template -struct Incrementor -{ - inline explicit - Incrementor(int& idx) - : idx_(++idx) - { - // NOOP - } - - inline - bool rollback() - { - --idx_; - return false; - } - - int& idx_; -}; - - -template<> -struct Incrementor -{ - inline explicit - Incrementor(int&) - { - // NOOP - } - - inline - bool rollback() - { - return false; - } -}; - - -// ------------------------------------------------------------------------------------------ - - -template -struct HandlerCompositeBase -{ - static_assert(!std::is_same >::value || AnchorT::LongSupport, "only_long_options_may_support_no_char"); - -private: - - struct LongSupportHelper - { - static inline - bool eval(AnchorT& anchor, const char* longopt, ParserState& state) - { - return anchor(longopt, state); - } - }; - - struct NonLongSupportHelper - { - static inline - bool eval(const AnchorT&, const char*, ParserState& /*state*/) - { - return false; - } - }; - -public: - - explicit inline - HandlerCompositeBase(AnchorT anchor) - : anchor_(anchor) - { - // NOOP - } - - - template - inline - tribool doEval(char theChar, ParserState& state, ActionT& action) - { - typedef typename FunctionReturnTypeDeducer::return_type action_return_type; - typedef Incrementor incrementor_type; - - if (anchor_(theChar, state)) - { - incrementor_type inc(state.current_); - return (OptionChecker::eval(state) && ActionCaller::template eval(action, state)) || inc.rollback(); - } - return indeterminate; - } - - - template - inline - tribool doEval(const char* longopt, ParserState& state, ActionT& action) - { - typedef typename FunctionReturnTypeDeducer::return_type action_return_type; - - if (if_::type::eval(anchor_, longopt, state)) - { - return ActionCaller::template eval(action, state); - } - return indeterminate; - } - - - template - inline - tribool doEval(ParserState&, ActionT& action) - { - return indeterminate; - } - - AnchorT anchor_; -}; - - -template -struct HandlerCompositeBase > -{ - explicit inline - HandlerCompositeBase(ExtraOption anchor) - : anchor_(anchor) - { - // NOOP - } - - - template - inline - tribool doEval(char theChar, ParserState& state, ActionT& action) - { - return indeterminate; - } - - - template - inline - tribool doEval(const char* longopt, ParserState& state, ActionT& action) - { - return indeterminate; - } - - template - inline - tribool doEval(ParserState& state, ActionT& action) - { - if (anchor_(state)) - { - typedef typename FunctionReturnTypeDeducer::return_type action_return_type; - return ActionCaller::template eval(action, state); - } - else - return indeterminate; - } - - ExtraOption anchor_; -}; - - -template -struct HandlerComposite : HandlerCompositeBase -{ -public: - - typedef typename AnchorT::char_type arguments_type; - - inline - HandlerComposite(AnchorT anchor, ActionT action) - : HandlerCompositeBase(anchor) - , action_(action) - { - // NOOP - } - - inline - tribool eval(char theChar, ParserState& state) - { - return HandlerCompositeBase::doEval(theChar, state, action_); - } - - inline - tribool eval(const char* longopt, ParserState& state) - { - return HandlerCompositeBase::doEval(longopt, state, action_); - } - - inline - tribool eval(ParserState& state) - { - return HandlerCompositeBase::doEval(state, action_); - } - - inline - void doDoc(detail::stream_type& os) const - { - HandlerCompositeBase::anchor_.doDoc(os); - } - - inline - void genCmdline(detail::stream_type& os) const - { - HandlerCompositeBase::anchor_.genCmdline(os); - } - - inline - bool ok() const - { - return HandlerCompositeBase::anchor_.ok(); - } - -#ifdef CMDLINE_ENABLE_RUNTIME_CHECK - inline - bool plausibilityCheck(ParserState& state) const - { - return HandlerCompositeBase::anchor_.plausibilityCheck(state); - } -#endif - -private: - ActionT action_; -}; - - -// -------------------------------------------------------------------------------- - - -template -struct ArgumentComposite; - -template -struct CompositeTypeDiscriminator -{ - static_assert(std::is_same::value || IsExtraOption::value || std::is_same >::value || std::is_same::value == 0, "no_same_arguments_allowed"); - typedef TypeList > arguments_type; -}; - -template -struct CompositeTypeDiscriminator, T3> -{ - static_assert(std::is_same::value || IsExtraOption::value || std::is_same >::value || Find::arguments_type>::value == -1, "no_same_arguments_allowed"); - typedef TypeList::arguments_type> arguments_type; -}; - - -template -struct ArgumentComposite -{ - typedef typename CompositeTypeDiscriminator::arguments_type arguments_type; - - inline - ArgumentComposite(HandlerT1 first, HandlerT2 second) - : first_(first) - , second_(second) - { - // NOOP - } - - inline - tribool eval(char theChar, ParserState& state) - { - tribool rc = first_.eval(theChar, state); - if (indeterminate(rc)) - rc = second_.eval(theChar, state); - - return rc; - } - - inline - tribool eval(const char* longopt, ParserState& state) - { - tribool rc = first_.eval(longopt, state); - if (indeterminate(rc)) - rc = second_.eval(longopt, state); - - return rc; - } - - inline - tribool eval(ParserState& state) - { - tribool rc = first_.eval(state); - if (indeterminate(rc)) - rc = second_.eval(state); - - return rc; - } - - inline - void doDoc(detail::stream_type& os) const - { - first_.doDoc(os); - second_.doDoc(os); - } - - inline - void genCmdline(detail::stream_type& os) const - { - first_.genCmdline(os); - second_.genCmdline(os); - } - - // check mandatories - inline - bool ok() const - { - return first_.ok() && second_.ok(); - } - -#ifdef CMDLINE_ENABLE_RUNTIME_CHECK - inline - bool plausibilityCheck(ParserState& state) const - { - return first_.plausibilityCheck(state) && second_.plausibilityCheck(state); - } -#endif - -private: - HandlerT1 first_; - HandlerT2 second_; -}; - - -// -------------------------------------------------------------------------------- - - -/** - * A flagging handler. Takes a bool and flags it 'true' if the option was set. - */ -struct flag -{ - typedef void return_type; - - inline explicit - flag(bool& t) - : t_(t) - { - t_ = false; - } - - inline - void operator()() - { - t_ = true; - } - - bool& t_; -}; - - -/** - * A generic setter for options. - */ -template -struct set -{ - typedef void return_type; - typedef T arg1_type; - - inline explicit - set(T& t) - : t_(t) - { - // NOOP - } - - inline - void operator()(const T& t) - { - t_ = t; - } - - T& t_; -}; - - -/** - * A generic setter for options of type char* and const char*. - */ -template -struct set -{ - typedef void return_type; - typedef T* arg1_type; - - inline explicit - set(T** t) - : t_(t) - { - // NOOP - } - - inline - void operator()(T* t) - { - *t_ = t; - } - - T** t_; -}; - - -/** - * A generic setter for options of type char* (make strcpy). - * FIXME ensure the size of the buffer somehow and use strncpy - */ -template<> -struct set -{ - typedef void return_type; - typedef const char* arg1_type; - - inline explicit - set(char* t) - : t_(t) - { - // NOOP - } - - inline - void operator()(const char* t) - { - ::strcpy(t_, t); - } - - char* t_; -}; - - -template -struct BackInserter -{ - typedef void return_type; - typedef typename T::value_type arg1_type; - - explicit inline - BackInserter(T& t) - : t_(t) - { - // NOOP - } - - inline - void operator()(typename T::const_reference data) - { - t_.push_back(data); - } - - T& t_; -}; - -} // namespace detail - -} // namespace cmdline - -} // namespace simppl - - -template -inline -simppl::cmdline::detail::ArgumentComposite > -operator<= (T1 h1, simppl::cmdline::detail::HandlerComposite h2) -{ - return simppl::cmdline::detail::ArgumentComposite >(h1, h2); -}; - - -// -------------------------------------------------------------------------------- - - -// TODO make sure the handler is not called for any normal variables if no specialized variant is implemented -// that is, we need some static_assert here. -template -inline -simppl::cmdline::detail::HandlerComposite, ActionT> -operator>> (simppl::cmdline::Switch t1, ActionT t2) -{ - return simppl::cmdline::detail::HandlerComposite, ActionT>(t1, t2); -} - - -template -inline -simppl::cmdline::detail::HandlerComposite, ActionT> -operator>> (simppl::cmdline::detail::LongSwitch t1, ActionT t2) -{ - return simppl::cmdline::detail::HandlerComposite, ActionT>(t1, t2); -} - - -template -inline -simppl::cmdline::detail::HandlerComposite, ActionT> -operator>> (simppl::cmdline::Option t1, ActionT t2) -{ - return simppl::cmdline::detail::HandlerComposite, ActionT>(t1, t2); -} - - -template -inline -simppl::cmdline::detail::HandlerComposite, ActionT> -operator>> (simppl::cmdline::ExtraOption t1, ActionT t2) -{ - return simppl::cmdline::detail::HandlerComposite, ActionT>(t1, t2); -} - - -// for bool flagging -template -inline -simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::flag> -operator>> (simppl::cmdline::Switch t1, bool& b) -{ - return simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::flag>(t1, simppl::cmdline::detail::flag(b)); -} - - -// for bool flagging -template -inline -simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::flag> -operator>> (simppl::cmdline::detail::LongSwitch t1, bool& b) -{ - return simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::flag>(t1, simppl::cmdline::detail::flag(b)); -} - - -// ------------------------------------------------------------------------- - - -namespace simppl -{ - -namespace cmdline -{ - -/** - * A value incrementor for multi-options like e.g. -vvvvv (=verbosity level) - */ -struct inc -{ - typedef void return_type; - - inline explicit - inc(int& i) - : i_(i) - { - i = 0; - } - - inline - void operator()() - { - ++i_; - } - - int& i_; -}; - -} // namespace cmdline - -} // namespace simppl - - -// -------------------------------------------------------------------------------- - - -#define PARSER_MAKE_SHIFT_OPERATOR(datatype) \ -template \ -inline \ -simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set > \ -operator>> (simppl::cmdline::Option t1, datatype& t2) \ -{ \ - return simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set >(t1, simppl::cmdline::detail::set(t2)); \ -} \ -\ -\ -template \ -inline \ -simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set > \ -operator>> (simppl::cmdline::detail::LongSwitch t1, datatype& t2) \ -{\ - return simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set >(t1, simppl::cmdline::detail::set(t2)); \ -} \ -\ -\ -template \ -inline \ -simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set > \ -operator>> (simppl::cmdline::ExtraOption t1, datatype& t2) \ -{\ - return simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set >(t1, simppl::cmdline::detail::set(t2)); \ -} - -PARSER_MAKE_SHIFT_OPERATOR(char) -PARSER_MAKE_SHIFT_OPERATOR(signed char) -PARSER_MAKE_SHIFT_OPERATOR(unsigned char) - -PARSER_MAKE_SHIFT_OPERATOR(short) -PARSER_MAKE_SHIFT_OPERATOR(unsigned short) - -PARSER_MAKE_SHIFT_OPERATOR(int) -PARSER_MAKE_SHIFT_OPERATOR(unsigned int) - -#ifdef CMDLINE_HAVE_STD_STRING -PARSER_MAKE_SHIFT_OPERATOR(std::string) -#endif - - -template -inline -simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set > -operator>> (simppl::cmdline::Option t1, T** t2) -{ - return simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set >(t1, simppl::cmdline::detail::set(t2)); -} - - -template -inline -simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set > -operator>> (simppl::cmdline::detail::LongSwitch t1, T** t2) -{ - return simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set >(t1, simppl::cmdline::detail::set(t2)); -} - - -template -inline -simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set > -operator>> (simppl::cmdline::ExtraOption t1, T** t2) -{ - return simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set >(t1, simppl::cmdline::detail::set(t2)); -} - - -template -inline -simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set > -operator>> (simppl::cmdline::Option t1, char t2[]) -{ - return simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set >(t1, simppl::cmdline::detail::set(t2)); -} - - -template -inline -simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set > -operator>> (simppl::cmdline::detail::LongSwitch t1, char t2[]) -{ - return simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set >(t1, simppl::cmdline::detail::set(t2)); -} - - -template -inline -simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set > -operator>> (simppl::cmdline::ExtraOption t1, char t2[]) -{ - return simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::set >(t1, simppl::cmdline::detail::set(t2)); -} - - -#ifdef CMDLINE_HAVE_STD_VECTOR -template -inline -simppl::cmdline::detail::HandlerComposite, simppl::cmdline::detail::BackInserter > > -operator>> (simppl::cmdline::ExtraOption t1, std::vector& t2) -{ - return simppl::cmdline::detail::HandlerComposite, - simppl::cmdline::detail::BackInserter > >(t1, simppl::cmdline::detail::BackInserter >(t2)); -} -#endif - - -#endif // SIMPPL_CMDLINE_H diff --git a/include/simppl/cmdline_extensionpoint.h b/include/simppl/cmdline_extensionpoint.h deleted file mode 100644 index 02f247b..0000000 --- a/include/simppl/cmdline_extensionpoint.h +++ /dev/null @@ -1,249 +0,0 @@ -#ifndef SIMPPL_CMDLINE_EXTENSIONPOINT_H -#define SIMPPL_CMDLINE_EXTENSIONPOINT_H - - -#include "simppl/cmdline.h" -#include "simppl/intrusive_list.h" - -#include - - -namespace simppl -{ - -namespace cmdline -{ - -namespace detail -{ - -struct ExtensionPointHolder : intrusive::ListBaseHook -{ - virtual ~ExtensionPointHolder() - { - // NOOP - } - - virtual tribool eval(char theChar, detail::ParserState& state) = 0; - - virtual tribool eval(const char* longopt, detail::ParserState& state) = 0; - - virtual tribool eval(detail::ParserState& state) = 0; - - virtual void doDoc(stream_type& os) const = 0; - - virtual void genCmdline(stream_type& os) const = 0; - - // check mandatories - virtual bool ok() const = 0; - - // be aware of object size in different compilation modes -> leave virtual function inside here - virtual bool plausibilityCheck(ParserState& state) const = 0; -}; - - -template -struct ExtensionPointHolderImpl : ExtensionPointHolder -{ - explicit inline - ExtensionPointHolderImpl(const ParserT& parser) - : parser_(parser) - { - typedef typename Reverse::type>::type arguments_type; - static_assert(detail::FindExtra::value < 0, "no_extra_options_allowed_in_parser_extension"); - } - - tribool eval(char theChar, detail::ParserState& state) - { - return parser_.eval(theChar, state); - } - - tribool eval(const char* longopt, detail::ParserState& state) - { - return parser_.eval(longopt, state); - } - - tribool eval(detail::ParserState& state) - { - return parser_.eval(state); - } - - void doDoc(stream_type& os) const - { - return parser_.doDoc(os); - } - - void genCmdline(stream_type& os) const - { - return parser_.genCmdline(os); - } - - bool ok() const - { - return parser_.ok(); - } - - bool plausibilityCheck(ParserState& state) const - { -#ifdef CMDLINE_ENABLE_RUNTIME_CHECK - return parser_.plausibilityCheck(state); -#else - return true; -#endif - } - -private: - ParserT parser_; -}; - -} // namespace detail - - -// Extension point for adding further commandline options to the parser grammar. -// Note, that these cannot be validated by the compiler, so using the runtime check is adequate. -struct ExtensionPoint -{ -private: - - // FIXME globally check all public and private typedefs and member functions for accessability - typedef intrusive::List holder_type; - -public: - - typedef ExtensionPoint char_type; - typedef char_type arguments_type; - - inline - ExtensionPoint() - { - // NOOP - } - - template - inline - ExtensionPoint(const ParserT& parser) - { - holder_.push_back(*new detail::ExtensionPointHolderImpl(parser)); - } - - // move semantics once the parser runs - so the extensionpoint cannot be accessed later on. - ExtensionPoint(const ExtensionPoint& rhs) - : holder_(rhs.holder_) /// FIXME??? why this and swap afterwards? - { - holder_.swap(rhs.holder_); - } - - ~ExtensionPoint() - { - holder_.clear(); - } - - template - void operator+=(const ParserT& parser) - { - holder_.push_back(*new detail::ExtensionPointHolderImpl(parser)); - } - -// FIXME from here on private - - tribool eval(char theChar, detail::ParserState& state) - { - tribool rc = indeterminate; - - for(holder_type::iterator iter = holder_.begin(); iter != holder_.end() && indeterminate(rc); ++iter) - { - rc = iter->eval(theChar, state); - } - - return rc; - } - - tribool eval(const char* longopt, detail::ParserState& state) - { - tribool rc = indeterminate; - - for(holder_type::iterator iter = holder_.begin(); iter != holder_.end() && indeterminate(rc); ++iter) - { - rc = iter->eval(longopt, state); - } - - return rc; - } - - tribool eval(detail::ParserState& state) - { - tribool rc = indeterminate; - - for(holder_type::iterator iter = holder_.begin(); iter != holder_.end() && indeterminate(rc); ++iter) - { - rc = iter->eval(state); - } - - return rc; - } - - void doDoc(detail::stream_type& os) const - { - std::for_each(holder_.begin(), holder_.end(), std::bind(&detail::ExtensionPointHolder::doDoc, std::placeholders::_1, std::ref(os))); - } - - void genCmdline(detail::stream_type& os) const - { - std::for_each(holder_.begin(), holder_.end(), std::bind(&detail::ExtensionPointHolder::genCmdline, std::placeholders::_1, std::ref(os))); - } - - bool ok() const - { - bool rc = true; - - for(holder_type::const_iterator iter = holder_.begin(); iter != holder_.end() && rc == true; ++iter) - { - rc = iter->ok(); - } - - return rc; - } - -#ifdef CMDLINE_ENABLE_RUNTIME_CHECK - bool plausibilityCheck(detail::ParserState& state) const - { - bool rc = true; - - for(holder_type::const_iterator iter = holder_.begin(); iter != holder_.end() && rc == true; ++iter) - { - rc = iter->plausibilityCheck(state); - } - - return rc; - } -#endif - - mutable holder_type holder_; // move semantics -}; - -} // namespace cmdline - -} // namespace simppl - - -// --------------------------------------------------------------------------------------------------- - - -template -inline -simppl::cmdline::detail::ArgumentComposite, simppl::cmdline::ExtensionPoint> -operator<= (simppl::cmdline::detail::ArgumentComposite h1, simppl::cmdline::ExtensionPoint h2) -{ - return simppl::cmdline::detail::ArgumentComposite, simppl::cmdline::ExtensionPoint>(h1, h2); -}; - - -inline -simppl::cmdline::detail::ArgumentComposite -operator<= (simppl::cmdline::ExtensionPoint h1, simppl::cmdline::ExtensionPoint h2) -{ - return simppl::cmdline::detail::ArgumentComposite(h1, h2); -}; - - -#endif // SIMPPL_CMDLINE_EXTENSIONPOINT_H diff --git a/include/simppl/connectionstate.h b/include/simppl/connectionstate.h index fcbee4d..61ad65b 100644 --- a/include/simppl/connectionstate.h +++ b/include/simppl/connectionstate.h @@ -5,7 +5,7 @@ namespace simppl { -namespace ipc +namespace dbus { @@ -18,7 +18,7 @@ enum struct ConnectionState }; -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/detail/basicinterface.h b/include/simppl/detail/basicinterface.h index 8845114..ce4ee71 100644 --- a/include/simppl/detail/basicinterface.h +++ b/include/simppl/detail/basicinterface.h @@ -9,7 +9,7 @@ struct DBusConnection; namespace simppl { -namespace ipc +namespace dbus { namespace detail @@ -31,7 +31,7 @@ struct BasicInterface } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/detail/clientresponseholder.h b/include/simppl/detail/clientresponseholder.h index 9bb13f8..0cc7410 100644 --- a/include/simppl/detail/clientresponseholder.h +++ b/include/simppl/detail/clientresponseholder.h @@ -14,7 +14,7 @@ struct DBusPendingCall; namespace simppl { -namespace ipc +namespace dbus { // forward decl @@ -52,7 +52,7 @@ struct ClientResponseHolder } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/detail/is_vector.h b/include/simppl/detail/is_vector.h index 97aaa1c..aaf6b66 100644 --- a/include/simppl/detail/is_vector.h +++ b/include/simppl/detail/is_vector.h @@ -8,7 +8,7 @@ namespace simppl { -namespace ipc +namespace dbus { namespace detail @@ -29,7 +29,7 @@ struct is_vector > } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/detail/parented.h b/include/simppl/detail/parented.h index d4e046e..b19b031 100644 --- a/include/simppl/detail/parented.h +++ b/include/simppl/detail/parented.h @@ -12,7 +12,7 @@ struct Dispatcher; namespace simppl { -namespace ipc +namespace dbus { struct StubBase; @@ -23,8 +23,8 @@ namespace detail struct Parented { - friend struct simppl::ipc::StubBase; - friend struct simppl::ipc::Dispatcher; + friend struct simppl::dbus::StubBase; + friend struct simppl::dbus::Dispatcher; protected: @@ -54,7 +54,7 @@ struct Parented } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/detail/serialization.h b/include/simppl/detail/serialization.h index 9c714fd..5c8a4ec 100644 --- a/include/simppl/detail/serialization.h +++ b/include/simppl/detail/serialization.h @@ -28,7 +28,7 @@ namespace simppl { -namespace ipc +namespace dbus { // forward decls @@ -601,14 +601,14 @@ struct Serializer // : noncopyable } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl #define MAKE_SERIALIZER(type) \ inline \ -simppl::ipc::detail::Serializer& operator<<(simppl::ipc::detail::Serializer& s, type t) \ +simppl::dbus::detail::Serializer& operator<<(simppl::dbus::detail::Serializer& s, type t) \ { \ return s.write(t); \ } @@ -635,12 +635,12 @@ MAKE_SERIALIZER(const std::string&) // forward decl template -simppl::ipc::detail::Serializer& operator<<(simppl::ipc::detail::Serializer&, const simppl::ipc::ServerVectorAttributeUpdate&); +simppl::dbus::detail::Serializer& operator<<(simppl::dbus::detail::Serializer&, const simppl::dbus::ServerVectorAttributeUpdate&); template inline -simppl::ipc::detail::Serializer& operator<<(simppl::ipc::detail::Serializer& s, const std::vector& v) +simppl::dbus::detail::Serializer& operator<<(simppl::dbus::detail::Serializer& s, const std::vector& v) { return s.write(v); } @@ -648,7 +648,7 @@ simppl::ipc::detail::Serializer& operator<<(simppl::ipc::detail::Serializer& s, template inline -simppl::ipc::detail::Serializer& operator<<(simppl::ipc::detail::Serializer& s, const std::map& m) +simppl::dbus::detail::Serializer& operator<<(simppl::dbus::detail::Serializer& s, const std::map& m) { return s.write(m); } @@ -656,7 +656,7 @@ simppl::ipc::detail::Serializer& operator<<(simppl::ipc::detail::Serializer& s, template inline -simppl::ipc::detail::Serializer& operator<<(simppl::ipc::detail::Serializer& s, const StructT& st) +simppl::dbus::detail::Serializer& operator<<(simppl::dbus::detail::Serializer& s, const StructT& st) { return s.write(st); } @@ -664,7 +664,7 @@ simppl::ipc::detail::Serializer& operator<<(simppl::ipc::detail::Serializer& s, template inline -simppl::ipc::detail::Serializer& operator<<(simppl::ipc::detail::Serializer& s, const std::tuple& t) +simppl::dbus::detail::Serializer& operator<<(simppl::dbus::detail::Serializer& s, const std::tuple& t) { return s.write(t); } @@ -673,7 +673,7 @@ simppl::ipc::detail::Serializer& operator<<(simppl::ipc::detail::Serializer& s, template template inline -void simppl::ipc::detail::TupleSerializer::operator()(const T& t) // seems to be already a reference so no copy is done +void simppl::dbus::detail::TupleSerializer::operator()(const T& t) // seems to be already a reference so no copy is done { s_ << t; } @@ -685,7 +685,7 @@ void simppl::ipc::detail::TupleSerializer::operator()(const T& t) namespace simppl { -namespace ipc +namespace dbus { namespace detail @@ -848,14 +848,14 @@ struct Deserializer // : noncopyable } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl #define MAKE_DESERIALIZER(type) \ inline \ -simppl::ipc::detail::Deserializer& operator>>(simppl::ipc::detail::Deserializer& s, type& t) \ +simppl::dbus::detail::Deserializer& operator>>(simppl::dbus::detail::Deserializer& s, type& t) \ { \ return s.read(t); \ } @@ -882,32 +882,32 @@ MAKE_DESERIALIZER(std::string) // forward decl template -simppl::ipc::detail::Deserializer& operator>>(simppl::ipc::detail::Deserializer&, simppl::ipc::ClientVectorAttributeUpdate&); +simppl::dbus::detail::Deserializer& operator>>(simppl::dbus::detail::Deserializer&, simppl::dbus::ClientVectorAttributeUpdate&); template inline -simppl::ipc::detail::Deserializer& operator>>(simppl::ipc::detail::Deserializer& s, std::vector& v) +simppl::dbus::detail::Deserializer& operator>>(simppl::dbus::detail::Deserializer& s, std::vector& v) { return s.read(v); } template inline -simppl::ipc::detail::Deserializer& operator>>(simppl::ipc::detail::Deserializer& s, std::map& m) +simppl::dbus::detail::Deserializer& operator>>(simppl::dbus::detail::Deserializer& s, std::map& m) { return s.read(m); } template inline -simppl::ipc::detail::Deserializer& operator>>(simppl::ipc::detail::Deserializer& s, StructT& st) +simppl::dbus::detail::Deserializer& operator>>(simppl::dbus::detail::Deserializer& s, StructT& st) { return s.read(st); } template inline -simppl::ipc::detail::Deserializer& operator>>(simppl::ipc::detail::Deserializer& s, std::tuple& t) +simppl::dbus::detail::Deserializer& operator>>(simppl::dbus::detail::Deserializer& s, std::tuple& t) { return s.read(t); } @@ -916,7 +916,7 @@ simppl::ipc::detail::Deserializer& operator>>(simppl::ipc::detail::Deserializer& template template inline -void simppl::ipc::detail::TupleDeserializer::operator()(T& t) +void simppl::dbus::detail::TupleDeserializer::operator()(T& t) { s_ >> t; } @@ -928,7 +928,7 @@ void simppl::ipc::detail::TupleDeserializer::operator()(T& t) namespace simppl { -namespace ipc +namespace dbus { namespace detail @@ -1037,7 +1037,7 @@ struct DeserializeAndCall : simppl::NonInstantiable template static inline - void evalResponse(Deserializer& d, FunctorT& f, const simppl::ipc::CallState& cs) + void evalResponse(Deserializer& d, FunctorT& f, const simppl::dbus::CallState& cs) { std::tuple tuple; @@ -1060,7 +1060,7 @@ struct DeserializeAndCall0 : simppl::NonInstantiable template static inline - void evalResponse(Deserializer& /*d*/, FunctorT& f, const simppl::ipc::CallState& cs) + void evalResponse(Deserializer& /*d*/, FunctorT& f, const simppl::dbus::CallState& cs) { f(cs); } @@ -1075,7 +1075,7 @@ struct GetCaller : simppl::NonInstantiable } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/detail/serverholder.h b/include/simppl/detail/serverholder.h index 062b021..440293c 100644 --- a/include/simppl/detail/serverholder.h +++ b/include/simppl/detail/serverholder.h @@ -5,7 +5,7 @@ namespace simppl { -namespace ipc +namespace dbus { namespace detxxail @@ -62,7 +62,7 @@ struct ServerHolder : ServerHolderBase } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/detail/serverrequestbasesetter.h b/include/simppl/detail/serverrequestbasesetter.h index 933329c..778259a 100644 --- a/include/simppl/detail/serverrequestbasesetter.h +++ b/include/simppl/detail/serverrequestbasesetter.h @@ -5,7 +5,7 @@ namespace simppl { -namespace ipc +namespace dbus { namespace detail @@ -25,7 +25,7 @@ struct ServerRequestBaseSetter } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/detail/serverresponseholder.h b/include/simppl/detail/serverresponseholder.h index 651c6ba..691edf3 100644 --- a/include/simppl/detail/serverresponseholder.h +++ b/include/simppl/detail/serverresponseholder.h @@ -15,7 +15,7 @@ struct DBusMessage; namespace simppl { -namespace ipc +namespace dbus { // forward decl @@ -46,7 +46,7 @@ struct ServerResponseHolder } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/detail/util.h b/include/simppl/detail/util.h index d53eaaa..aa65329 100644 --- a/include/simppl/detail/util.h +++ b/include/simppl/detail/util.h @@ -8,7 +8,7 @@ namespace simppl { -namespace ipc +namespace dbus { namespace detail @@ -30,7 +30,7 @@ char* extract_interface(const char* mangled_iface); } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/detail/validation.h b/include/simppl/detail/validation.h index 5fa176f..e51c328 100644 --- a/include/simppl/detail/validation.h +++ b/include/simppl/detail/validation.h @@ -10,7 +10,7 @@ namespace simppl { -namespace ipc +namespace dbus { namespace detail @@ -82,7 +82,7 @@ namespace boost_adapter template struct isValidType { - typedef typename boost::mpl::if_c::value, boost::mpl::true_, boost::mpl::false_>::type type; + typedef typename boost::mpl::if_c::value, boost::mpl::true_, boost::mpl::false_>::type type; }; } // namespace boost_adapter @@ -218,7 +218,7 @@ struct isValidType } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/dispatcher.h b/include/simppl/dispatcher.h index 06c9183..fc24d92 100644 --- a/include/simppl/dispatcher.h +++ b/include/simppl/dispatcher.h @@ -29,7 +29,7 @@ struct inotify_event; namespace simppl { -namespace ipc +namespace dbus { extern DBusObjectPathVTable stub_v_table; @@ -139,7 +139,7 @@ struct Dispatcher }; -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/error.h b/include/simppl/error.h index e5f0e40..5ee5ebe 100644 --- a/include/simppl/error.h +++ b/include/simppl/error.h @@ -11,7 +11,7 @@ namespace simppl { -namespace ipc +namespace dbus { /// Base class for all IPC related exceptions. @@ -115,7 +115,7 @@ struct TransportError : Error } // namespace simppl -} // namespace ipc +} // namespace dbus #endif // SIMPPL_ERROR_H diff --git a/include/simppl/function_traits.h b/include/simppl/function_traits.h deleted file mode 100644 index 28a056c..0000000 --- a/include/simppl/function_traits.h +++ /dev/null @@ -1,311 +0,0 @@ -#ifndef SIMPPL_FUNCTION_TRAITS_H -#define SIMPPL_FUNCTION_TRAITS_H - - -#include "simppl/typelist.h" - - -namespace simppl -{ - -// template forward declaration -template -struct FunctionTraits; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef NilType object_type; - typedef TypeList param_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef NilType object_type; - typedef TypeList param_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef NilType object_type; - typedef TypeList > param_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef NilType object_type; - typedef TypeList > > param_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef NilType object_type; - typedef TypeList > > > param_type; -}; - -// --------------------------------------------------------------------------------------- - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef NilType object_type; - typedef TypeList param_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef NilType object_type; - typedef TypeList param_type; - - typedef T1 arg1_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef NilType object_type; - typedef TypeList > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef NilType object_type; - typedef TypeList > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; - typedef T3 arg3_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef NilType object_type; - typedef TypeList > > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; - typedef T3 arg3_type; - typedef T4 arg4_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef NilType object_type; - typedef TypeList > > > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; - typedef T3 arg3_type; - typedef T4 arg4_type; - typedef T5 arg5_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef NilType object_type; - typedef TypeList > > > > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; - typedef T3 arg3_type; - typedef T4 arg4_type; - typedef T5 arg5_type; - typedef T6 arg6_type; -}; - -// --------------------------------------------------------------------------------------- - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef ObjT object_type; - typedef TypeList param_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef const ObjT object_type; - typedef TypeList param_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef ObjT object_type; - typedef TypeList > param_type; - - typedef T1 arg1_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef const ObjT object_type; - typedef TypeList > param_type; - - typedef T1 arg1_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef ObjT object_type; - typedef TypeList > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef const ObjT object_type; - typedef TypeList > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef ObjT object_type; - typedef TypeList > > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; - typedef T3 arg3_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef const ObjT object_type; - typedef TypeList > > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; - typedef T3 arg3_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef ObjT object_type; - typedef TypeList > > > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; - typedef T3 arg3_type; - typedef T4 arg4_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef const ObjT object_type; - typedef TypeList > > > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; - typedef T3 arg3_type; - typedef T4 arg4_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef ObjT object_type; - typedef TypeList > > > > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; - typedef T3 arg3_type; - typedef T4 arg4_type; - typedef T5 arg5_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef const ObjT object_type; - typedef TypeList > > > > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; - typedef T3 arg3_type; - typedef T4 arg4_type; - typedef T5 arg5_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef ObjT object_type; - typedef TypeList > > > > > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; - typedef T3 arg3_type; - typedef T4 arg4_type; - typedef T5 arg5_type; - typedef T6 arg6_type; -}; - -template -struct FunctionTraits -{ - typedef ReturnT return_type; - typedef const ObjT object_type; - typedef TypeList > > > > > > param_type; - - typedef T1 arg1_type; - typedef T2 arg2_type; - typedef T3 arg3_type; - typedef T4 arg4_type; - typedef T5 arg5_type; - typedef T6 arg6_type; -}; - -} // namespace simppl - - -#endif // SIMPPL_FUNCTION_TRAITS_H \ No newline at end of file diff --git a/include/simppl/inifile.h b/include/simppl/inifile.h deleted file mode 100644 index f167ec3..0000000 --- a/include/simppl/inifile.h +++ /dev/null @@ -1,778 +0,0 @@ -#ifndef SIMPPL_INIFILE_H -#define SIMPPL_INIFILE_H - -#include -#include -#include -#include - -#define INIFILE_HAVE_STL_STREAMS 1 -#define INIFILE_HAVE_STD_VECTOR 1 - -#define INIFILE_RVALUE_REF && - -#ifdef INIFILE_HAVE_STL_STREAMS -# include -# include -#else -# include -#endif - -#ifdef INIFILE_HAVE_STD_VECTOR -# include -#endif - -#include "simppl/if.h" -#include "simppl/tribool.h" -#include "simppl/noninstantiable.h" - -#define INIFILE_FRIEND_PARSER template friend struct Parser; - - -namespace simppl -{ - -namespace inifile -{ - -// forward decls -template -struct Key; - -namespace detail -{ - -/// 'first' marks the section -/// 'second' the key -typedef std::pair section_key_pair_type; - -template -struct ParserChainSection; - -template -struct KeyHandlerComposite; - -template -struct DuplicateKeyEncountered; - -template -struct HandlerComposite; - -} // namespace detail - -// end forward decls - - -/** - * Argument policy. An argument using this policy is optional and must not be - * given at the commandline. - */ -struct Optional -{ - template - friend struct detail::KeyHandlerComposite; - -protected: - - inline - Optional() - { - // NOOP - } - - inline - bool ok() const - { - return true; - } - - inline - bool ok(bool b) - { - return b; - } -}; - - -/** - * Argument Policy. The using argument must be given at the commandline, otherwise the parser - * reports an error. - */ -struct Mandatory -{ - template - friend struct detail::KeyHandlerComposite; - -protected: - - inline - Mandatory() - : ok_(false) - { - // NOOP - } - - inline - bool ok() const - { - return ok_; - } - - inline - bool ok(bool b) - { - ok_ |= b; // set it to true one time, dont change later on - return b; - } - - bool ok_; -}; - - -/// key of key-value pair -template -struct Key : MandatoryT -{ - template - friend struct detail::KeyHandlerComposite; - - template - friend struct detail::DuplicateKeyEncountered; - - template - friend struct detail::HandlerComposite; - - explicit - Key(const char* INIFILE_RVALUE_REF key) - : key_(key) - { - assert(key); - assert(strlen(key) > 0); - } - -private: - - inline - bool operator()(const char* key) - { - return MandatoryT::ok(!::strcmp(key_, key)); - } - - const char* key_; -}; - - -enum Error -{ - Error_OK = 0, ///< no error occurred during processing - - Error_FILE_NOT_FOUND, - - Error_INVALID_FILE_HEADER, - Error_INVALID_SECTION_HEADER, - Error_INVALID_KEYVALUE_PAIR, ///< general parse error due to wrong grammar - - Error_UNKNOWN_SECTION, - Error_UNKNOWN_KEY, - - Error_MISSING_MANDATORY, ///< missing mandatory key-value pair - Error_ANY, ///< any other unknown error - - Error_MAX ///< no error, just for static check purposes -}; - - -// ----------------------------------------------------------------------------- - - -/// result object of a parse operation -struct Result -{ - const char* toString() const - { - static const char* msg[] = { - "ok", - "file not found", - "invalid header", - "invalid section", - "invalid key-value pair", - "unknown section", - "unknown key", - "missing mandatory key", - "unknown error" - }; - static_assert(Error_MAX == sizeof(msg)/sizeof(msg[0]), "enum_and_string_array_do_not_match"); - - return msg[errno_]; - } - - inline - Result(Error err, int line = -1) - : errno_(err) - , line_no_(line) - { - // NOOP - } - - /// boolean comparison operator - inline - operator const void*() const - { - return errno_ == Error_OK ? this : 0; - } - - inline - Error error() const - { - return errno_; - } - - inline - int line() const - { - return line_no_; - } - -private: - - Error errno_; ///< type of error that occurred - int line_no_; ///< where did the error occur -}; - - -// ----------------------------------------------------------------------------- - - -/// inifile section as in [sectionname] -struct Section -{ - friend struct File; - - INIFILE_FRIEND_PARSER - - explicit - Section(const char* INIFILE_RVALUE_REF name) - : name_(name) - { - assert(name); - } - - Section() - : name_("[default]") - { - // NOOP - } - - template - inline - detail::ParserChainSection operator[](ParserT parser); - - virtual tribool eval(char* line) - { - return indeterminate; - } - - inline - bool ok(detail::section_key_pair_type& p) const - { - return true; - } - - inline - const char* name() const - { - return name_; - } - -private: - - const char* name_; -}; - - -// ---------------------------------------------------------------------------- - - -} // namespace inifile - -} // namespace simppl - -#include "detail/inifile.h" - -namespace simppl -{ - -namespace inifile -{ - - -template -inline -simppl::inifile::detail::ParserChainSection Section::operator[](ParserT parser) -{ - return simppl::inifile::detail::ParserChainSection(*this, parser); -} - - -// ---------------------------------------------------------------------------- - - -/// Ini-File with key-value pairs grouped into sections -struct File -{ - friend struct ReportMandatoryKeys; - friend struct CheckMandatoryKeys; - INIFILE_FRIEND_PARSER - - /// Both arguments are supposed to survive the lifetime of the object, the second one should be - /// a compiled-in value - explicit inline - File(const char* /*user specific*/fname, const char* INIFILE_RVALUE_REF /*system wide*/defaultname = 0) - : fname_(fname) - , defaultname_(defaultname) - { - assert(fname); - } - - /// return section name -> default: no name - inline - const char* name() const - { - return 0; - } - - inline - Section* find(const char*) const - { - return 0; - } - - inline - const char* filename() const - { - return fname_; - } - - inline - const char* defaultFilename() const - { - return defaultname_; - } - - template - inline - detail::SectionatedIniFile, File> operator[](const ParserT& parser) - { - return detail::SectionatedIniFile, File>( - detail::ParserChainSection(parser), *this); - } - - // only for easier stopping of the algorithm -> better would be to never call this from the parser composite - inline - bool ok(detail::section_key_pair_type& p) const - { - return true; - } - -private: - - const char* fname_; - const char* defaultname_; -}; - - -// ---------------------------------------------------------------------------- - - -class IgnoreUnknownSection : NonInstantiable -{ - INIFILE_FRIEND_PARSER - - static inline - bool eval(const char* sectionName) - { - return true; - } -}; - - -class ReportUnknownSection : NonInstantiable -{ - INIFILE_FRIEND_PARSER - - static inline - bool eval(const char* sectionName) - { -#ifdef INIFILE_HAVE_STL_STREAMS - std::cout << "Skipping unknown section '" << sectionName << "'." << std::endl; -#else - fprintf(stdout, "Skipping unknown section '%s'.\n", sectionName); -#endif - return true; - } -}; - - -class FailOnUnknownSection : NonInstantiable -{ - INIFILE_FRIEND_PARSER - - static inline - bool eval(const char* sectionName) - { -#ifdef INIFILE_HAVE_STL_STREAMS - std::cerr << "Unknown section '" << sectionName << "' detected." << std::endl; -#else - fprintf(stderr, "Unknown section '%s' detected.\n", sectionName); -#endif - return false; - } -}; - - -// ---------------------------------------------------------------------------- - - -class IgnoreUnknownKey : NonInstantiable -{ - INIFILE_FRIEND_PARSER - - static inline - bool eval(const char* line) - { - return true; - } -}; - - -class ReportUnknownKey : NonInstantiable -{ - INIFILE_FRIEND_PARSER - - static inline - bool eval(const char* line) - { -#ifdef INIFILE_HAVE_STL_STREAMS - std::cout << "Skipping unknown key '" << line << "'." << std::endl; -#else - fprintf(stdout, "Skipping unknown key '%s'.\n", line); -#endif - return true; - } -}; - - -class FailOnUnknownKey : NonInstantiable -{ - INIFILE_FRIEND_PARSER - - static inline - bool eval(const char* line) - { -#ifdef INIFILE_HAVE_STL_STREAMS - std::cerr << "Unknown key-value pair '" << line << "' detected." << std::endl; -#else - fprintf(stderr, "Unknown key-value pair '%s' detected.\n", line); -#endif - return false; - } -}; - - -// --------------------------------------------------------------------------------------------- - - -class IgnoreMandatoryKeys : NonInstantiable -{ - INIFILE_FRIEND_PARSER - - template - static inline - Result eval(const FileGrammarT& /*inifile*/) - { - return Error_OK; - } -}; - - -class ReportMandatoryKeys : NonInstantiable -{ - INIFILE_FRIEND_PARSER - - template - static inline - Result eval(const FileGrammarT& inifile) - { - detail::section_key_pair_type p; - - if (!inifile.ok(p)) - { -#ifdef INIFILE_HAVE_STL_STREAMS - std::cerr << "Missing mandatory key '" << p.second << "' in section '" << p.first << "'." << std::endl; -#else - fprintf(stderr, "Missing mandatory key '%s' in section '%s'.\n", p.second, p.first); -#endif - return Error_MISSING_MANDATORY; - } - else - return Error_OK; - } -}; - - -class CheckMandatoryKeys : NonInstantiable -{ - INIFILE_FRIEND_PARSER - - template - static inline - Result eval(const FileGrammarT& inifile) - { - detail::section_key_pair_type p; - return inifile.ok(p) ? Error_OK : Error_MISSING_MANDATORY; - } -}; - - -// --------------------------------------------------------------------------- - - -template -struct Parser : NonInstantiable -{ - template - static - Result parse(const FileGrammarT& inifile__) - { - FileGrammarT& inifile = const_cast(inifile__); - int line = 0; - - stream_type ifs(inifile.filename()); - - if (!ifs.is_open()) - ifs.open(inifile.defaultFilename()); - - if (ifs.is_open()) - { - if (!detail::HeaderlineEvaluator::eval(ifs, line)) - return Error_INVALID_FILE_HEADER; - - char buf[2048]; - Section* current = &inifile.defaultSection(); - - bool skipUntilNextSection = false; - - while(ifs) - { - ifs.getline(buf, sizeof(buf)); - ++line; - - if (ifs.gcount() > 0 && ifs.gcount() < (int)sizeof(buf) - 1) - { - char* ptr = buf; - - // skip blanks - while(*ptr && ::isblank(*ptr)) - ++ptr; - - // skip comment lines - if (*ptr == '#') - - continue; - - // skip empty lines - if (*ptr == 0) - continue; - - // section start - if (*ptr == '[') - { - skipUntilNextSection = false; - - detail::SectionNameParser p(ptr); - if (p.parse().good()) - { - // section exists in parser grammar? - Section* found = inifile.find(p.name()); - - if (found) - { - current = found; - continue; - } - else - { - if (!UnknownSectionT::eval(p.name())) - return Result(Error_UNKNOWN_SECTION, line); - - skipUntilNextSection = true; - continue; - } - } - - return Result(Error_INVALID_SECTION_HEADER, line); - } - else - { - if (!skipUntilNextSection) - { - // must be a key/value pair or line based section entry - tribool ret = current->eval(ptr); - - if (!ret) - { - return Result(Error_INVALID_KEYVALUE_PAIR, line); - } - else if (indeterminate(ret) && !UnknownKeyT::eval(ptr)) - return Result(Error_UNKNOWN_KEY, line); - } - } - } - else - break; - } - - if (ifs.bad()) - { - return Error_ANY; - } - else - return CheckMandatoryT::eval(inifile); - } - - return Mandatory ? Error_FILE_NOT_FOUND : Error_OK; - } -}; - -} // namespace inifile - -} // namespace simppl - - -// ------------------------------------------------------------------------------------------ - - -#ifdef INIFILE_HAVE_STD_VECTOR - -template -inline -simppl::inifile::detail::KeyHandlerComposite > > -operator>>(const simppl::inifile::Key& key, std::vector& v) -{ - return simppl::inifile::detail::KeyHandlerComposite > >( - key, simppl::inifile::detail::BackInserterContainerHandler >(v)); -} - - -template -inline -simppl::inifile::detail::FullHandledSection > > -operator>>(const simppl::inifile::Section& section, std::vector& v) -{ - return simppl::inifile::detail::FullHandledSection > >( - section, simppl::inifile::detail::BackInserterContainerHandler >(v)); -} - -#endif // INIFILE_HAVE_STD_VECTOR - - -template -inline -simppl::inifile::detail::KeyHandlerComposite -operator>>(const simppl::inifile::Key& key, HandlerT handler) -{ - return simppl::inifile::detail::KeyHandlerComposite(key, handler); -} - - -#define INIFILE_DECLARE_STREAM_OPERATOR(type) \ -template \ -inline \ -simppl::inifile::detail::KeyHandlerComposite > \ -operator>>(const simppl::inifile::Key& key, type& b) \ -{ \ - return simppl::inifile::detail::KeyHandlerComposite >(key, simppl::inifile::detail::set(b)); \ -} \ - -INIFILE_DECLARE_STREAM_OPERATOR(bool) - -INIFILE_DECLARE_STREAM_OPERATOR(char) -INIFILE_DECLARE_STREAM_OPERATOR(signed char) -INIFILE_DECLARE_STREAM_OPERATOR(unsigned char) - -INIFILE_DECLARE_STREAM_OPERATOR(signed short) -INIFILE_DECLARE_STREAM_OPERATOR(unsigned short) - -INIFILE_DECLARE_STREAM_OPERATOR(signed int) -INIFILE_DECLARE_STREAM_OPERATOR(unsigned int) - -INIFILE_DECLARE_STREAM_OPERATOR(std::string) - - -template -inline -simppl::inifile::detail::KeyHandlerComposite > -operator>>(const simppl::inifile::Key& key, char b[]) -{ - return simppl::inifile::detail::KeyHandlerComposite >(key, simppl::inifile::detail::set(b)); -} - - -template -inline -simppl::inifile::detail::HandlerComposite -operator||(const CompositeT& lhs, const simppl::inifile::detail::KeyHandlerComposite& rhs) -{ - // assert for duplicate keys - return simppl::inifile::detail::HandlerComposite(rhs, lhs); -} - - -// ------------------------------------------------------------------------------------------ - - -/// function objects handler -template -inline -simppl::inifile::detail::FullHandledSection operator>>(const simppl::inifile::Section& section, const HandlerT& handler) -{ - return simppl::inifile::detail::FullHandledSection(section, handler); -} - - -/// normal functions handler -template -inline -simppl::inifile::detail::FullHandledSection operator>>(const simppl::inifile::Section& section, ReturnT(*handler)(ArgumentT)) -{ - return simppl::inifile::detail::FullHandledSection(section, handler); -} - - -// ------------------------------------------------------------------------------------------ - - -template -inline -simppl::inifile::detail::SectionatedIniFile > -operator<=(const simppl::inifile::detail::SectionatedIniFile& left, const RightT& right) -{ - return simppl::inifile::detail::SectionatedIniFile >(right, left); -} - - -template -inline -simppl::inifile::detail::SectionatedIniFile > -operator<=(const simppl::inifile::File& f, const RightT& right) -{ - return simppl::inifile::detail::SectionatedIniFile >( - right, simppl::inifile::detail::SectionatedIniFile(simppl::inifile::detail::NoopDefaultSection(), f)); -} - - -#endif // SIMPPL_INIFILE_H diff --git a/include/simppl/inifile_extensionpoint.h b/include/simppl/inifile_extensionpoint.h deleted file mode 100644 index 9ecd148..0000000 --- a/include/simppl/inifile_extensionpoint.h +++ /dev/null @@ -1,178 +0,0 @@ -#ifndef SIMPPL_INIFILE_EXTENSIONPOINT_H -#define SIMPPL_INIFILE_EXTENSIONPOINT_H - -#include "intrusive_list.h" - - -namespace simppl -{ - -namespace inifile -{ - -namespace detail -{ - -struct ExtensionPointHolder : intrusive::ListBaseHook -{ - virtual ~ExtensionPointHolder() { /* NOOP */ } - - virtual Section* find(const char* name) = 0; - - virtual bool ok(detail::section_key_pair_type& p) const = 0; -}; - - -// FIXME holder must always hold a composite -> makes it much easier -template -struct ExtensionPointHolderImpl : ExtensionPointHolder -{ - ExtensionPointHolderImpl(const GrammarT& grammar) - : grammar_(grammar) - { - // NOOP - } - - Section* find(const char* name) - { - return 0; // FIXME must do something senseful... - } - - bool ok(detail::section_key_pair_type& p) const - { - return true; // FIXME do something senseful - } - - GrammarT grammar_; -}; - -} // namespace detail - - -struct ExtensionPoint -{ - typedef intrusive::List holder_type; - - inline - ExtensionPoint() - { - // NOOP - } - - template - inline - ExtensionPoint(const GrammarT& grammar) - { - holder_.push_back(*new detail::ExtensionPointHolderImpl(grammar)); - } - - // move semantics once the parser runs - so the extensionpoint cannot be accessed later on. - ExtensionPoint(const ExtensionPoint& rhs) - : holder_(rhs.holder_) // FIXME ??? why this and swap afterwards? - { - holder_.swap(rhs.holder_); - } - - ~ExtensionPoint() - { - holder_.clear(); - } - - - template - void operator+=(const GrammarT& grammar) - { - holder_.push_back(*new detail::ExtensionPointHolderImpl(grammar)); - } - - Section* find(const char* name) - { - Section* rc = 0; - - for(holder_type::iterator iter = holder_.begin(); iter != holder_.end() && indeterminate(rc); ++iter) - { - if ((rc = iter->find(name))) - break; - } - - return rc; - } - - inline - bool ok(detail::section_key_pair_type& p) const - { - bool rc = true; - - for(holder_type::iterator iter = holder_.begin(); iter != holder_.end() && indeterminate(rc); ++iter) - { - if (!(rc = iter->ok(p))) - break; - } - - return rc; - } - -private: - - mutable holder_type holder_; // FIXME mutable necessary because of 'swap' -}; - - -namespace detail -{ - -/// extension point specialization -template -struct SectionatedIniFile -{ - SectionatedIniFile(const ExtensionPoint& ep, const IncludedSectionT& included) - : ep_(ep) - , included_(included) - { - //assert(included_.find(section_.name()) == 0); - // FIXME iterate over sections of extensionpoint and check for occurance of name in included - } - - Section* find(const char* name) - { - Section* rc = ep_.find(name); - return rc ? rc : included_.find(name); - } - - inline - Section& defaultSection() - { - return included_.defaultSection(); - } - - inline - const char* filename() const - { - return included_.filename(); - } - - inline - const char* defaultFilename() const - { - return included_.defaultFilename(); - } - - inline - bool ok(detail::section_key_pair_type& p) const - { - return ep_.ok(p) && included_.ok(p); - } - - ExtensionPoint ep_; - IncludedSectionT included_; -}; - - -} // end namespace detail - -} // end namespace inifile - -} // end namespace simppl - - -#endif // SIMPPL_INIFILE_EXTENSIONPOINT_H diff --git a/include/simppl/interface.h b/include/simppl/interface.h index f4a7523..27b6145 100644 --- a/include/simppl/interface.h +++ b/include/simppl/interface.h @@ -14,7 +14,7 @@ namespace simppl { -namespace ipc +namespace dbus { // forward decls @@ -51,7 +51,7 @@ struct InterfaceBase : detail::BasicInterface std::map attributes_; }; -} // namespace ipc +} // namespace dbus } // namespace simppl @@ -61,8 +61,8 @@ struct InterfaceBase : detail::BasicInterface template class Request, \ template class Response, \ template class Signal, \ - template class Attribute> \ - struct iface : public simppl::ipc::InterfaceBase + template class Attribute> \ + struct iface : public simppl::dbus::InterfaceBase #define INIT_REQUEST(request) \ request(# request, this) @@ -80,7 +80,7 @@ struct InterfaceBase : detail::BasicInterface template inline -void operator>> (simppl::ipc::ClientRequest& request, simppl::ipc::ClientResponse& response) +void operator>> (simppl::dbus::ClientRequest& request, simppl::dbus::ClientResponse& response) { assert(!request.handler_); request.handler_ = &response; @@ -89,11 +89,11 @@ void operator>> (simppl::ipc::ClientRequest& request, simppl::ipc::ClientR template inline -void operator>> (simppl::ipc::ServerRequest& request, simppl::ipc::ServerResponse& response) +void operator>> (simppl::dbus::ServerRequest& request, simppl::dbus::ServerResponse& response) { assert(!request.hasResponse()); - simppl::ipc::detail::ServerRequestBaseSetter::setHasResponse(request); + simppl::dbus::detail::ServerRequestBaseSetter::setHasResponse(request); response.allowedRequests_.insert(&request); } diff --git a/include/simppl/serialization.h b/include/simppl/serialization.h index cf4109b..dd2d07f 100644 --- a/include/simppl/serialization.h +++ b/include/simppl/serialization.h @@ -8,7 +8,7 @@ namespace simppl { -namespace ipc +namespace dbus { template @@ -18,7 +18,7 @@ struct make_serializer typedef typename detail::make_serializer_imp::type type; }; -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/serverrequestdescriptor.h b/include/simppl/serverrequestdescriptor.h index e68c4c2..f84fcef 100644 --- a/include/simppl/serverrequestdescriptor.h +++ b/include/simppl/serverrequestdescriptor.h @@ -12,7 +12,7 @@ struct DBusMessage; namespace simppl { -namespace ipc +namespace dbus { // forward decl @@ -40,7 +40,7 @@ struct ServerRequestDescriptor DBusMessage* msg_; }; -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/serverside.h b/include/simppl/serverside.h index 6874113..050733a 100644 --- a/include/simppl/serverside.h +++ b/include/simppl/serverside.h @@ -29,7 +29,7 @@ namespace simppl { -namespace ipc +namespace dbus { // forward decl @@ -187,7 +187,7 @@ struct ServerResponse : ServerResponseBase inline detail::ServerResponseHolder __impl(tTrueType, typename CallTraits::param_type... t) { - std::function f(std::bind(&simppl::ipc::detail::serialize::param_type...>, std::placeholders::_1, t...)); + std::function f(std::bind(&simppl::dbus::detail::serialize::param_type...>, std::placeholders::_1, t...)); return detail::ServerResponseHolder(*this, f); } @@ -312,14 +312,14 @@ struct ServerAttribute : CommitMixin> } }; -} // namespace ipc +} // namespace dbus } // namespace simppl template inline -void operator>>(simppl::ipc::ServerRequest& r, const FunctorT& f) +void operator>>(simppl::dbus::ServerRequest& r, const FunctorT& f) { r.handledBy(f); } diff --git a/include/simppl/skeleton.h b/include/simppl/skeleton.h index a550b75..29b3931 100644 --- a/include/simppl/skeleton.h +++ b/include/simppl/skeleton.h @@ -13,7 +13,7 @@ namespace simppl { -namespace ipc +namespace dbus { template class, @@ -39,7 +39,7 @@ struct Skeleton : SkeletonBase, IfaceT inline -void operator>> (std::function& func, const CallableT& callable) +void operator>> (std::function& func, const CallableT& callable) { func = callable; } diff --git a/include/simppl/stubbase.h b/include/simppl/stubbase.h index ccc72a7..fd224c0 100644 --- a/include/simppl/stubbase.h +++ b/include/simppl/stubbase.h @@ -18,7 +18,7 @@ namespace simppl { -namespace ipc +namespace dbus { // forward decls @@ -122,7 +122,7 @@ struct StubBase std::map signals_; }; -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/include/simppl/timeout.h b/include/simppl/timeout.h index 9fcaf05..8eb8c62 100644 --- a/include/simppl/timeout.h +++ b/include/simppl/timeout.h @@ -8,7 +8,7 @@ namespace simppl { -namespace ipc +namespace dbus { struct request_specific_timeout_helper @@ -36,7 +36,7 @@ extern __thread std::chrono::milliseconds request_specific_timeout; } // namespace simppl -} // namespace ipc +} // namespace dbus #endif // SIMPPL_DETAIL_TIMEOUT_H diff --git a/include/simppl/tribool.h b/include/simppl/tribool.h deleted file mode 100644 index a6ad076..0000000 --- a/include/simppl/tribool.h +++ /dev/null @@ -1,108 +0,0 @@ -#ifndef SIMPPL_TRIBOOL_H -#define SIMPPL_TRIBOOL_H - - -namespace simppl -{ - -struct tribool; -typedef bool (*tIndeterminateFunc)(tribool); - - -struct tribool -{ -private: - - struct safe_bool_struct - { - void safe() { /*NOOP*/ } - }; - -public: - - typedef void(safe_bool_struct::*safe_bool)(); - - enum State { False = -1, Indeterminate = 0, True = 1 }; - - inline - tribool() - : value_(Indeterminate) - { - // NOOP - } - - inline - tribool(const tribool& rvalue) - : value_(rvalue.value_) - { - // NOOP - } - - inline - tribool(bool b) - : value_(b ? True : False) - { - // NOOP - } - - inline - tribool(tIndeterminateFunc /*value*/) - : value_(Indeterminate) - { - // NOOP - } - - inline - tribool& operator=(tribool rvalue) - { - if (&rvalue != this) - { - value_ = rvalue.value_; - } - return *this; - } - - inline - tribool& operator=(tIndeterminateFunc /*value*/) - { - value_ = Indeterminate; - return *this; - } - - inline - tribool& operator=(bool b) - { - value_ = b ? True : False; - return *this; - } - - inline - operator safe_bool() const - { - return value_ == True ? &safe_bool_struct::safe : 0; - } - - inline - safe_bool operator!() const - { - return value_ == False ? &safe_bool_struct::safe : 0; - } - - State value_; -}; - - -#ifndef INDETERMINATE_STATE -# define INDETERMINATE_STATE indeterminate -#endif - -inline -bool INDETERMINATE_STATE(tribool b) -{ - return b.value_ == tribool::Indeterminate; -} - -} // namespace simppl - - -#endif // SIMPPL_TRIBOOL_H diff --git a/src/clientresponseholder.cpp b/src/clientresponseholder.cpp index 7dbf6cc..3cdd312 100644 --- a/src/clientresponseholder.cpp +++ b/src/clientresponseholder.cpp @@ -2,7 +2,7 @@ #include "simppl/dispatcher.h" -simppl::ipc::detail::ClientResponseHolder::operator bool() +simppl::dbus::detail::ClientResponseHolder::operator bool() { dbus_pending_call_block(pending_); return true; diff --git a/src/dispatcher.cpp b/src/dispatcher.cpp index 3b3ed73..be8fac9 100644 --- a/src/dispatcher.cpp +++ b/src/dispatcher.cpp @@ -34,7 +34,7 @@ get_lookup_duetime() struct BlockingResponseHandler0 { inline - BlockingResponseHandler0(simppl::ipc::Dispatcher& disp, simppl::ipc::ClientResponse<>& r) + BlockingResponseHandler0(simppl::dbus::Dispatcher& disp, simppl::dbus::ClientResponse<>& r) : disp_(disp) , r_(r) { @@ -42,7 +42,7 @@ struct BlockingResponseHandler0 } inline - void operator()(const simppl::ipc::CallState& state) + void operator()(const simppl::dbus::CallState& state) { disp_.stop(); r_.handledBy(std::nullptr_t()); @@ -51,14 +51,14 @@ struct BlockingResponseHandler0 disp_.propagate(state); } - simppl::ipc::Dispatcher& disp_; - simppl::ipc::ClientResponse<>& r_; + simppl::dbus::Dispatcher& disp_; + simppl::dbus::ClientResponse<>& r_; }; DBusHandlerResult signal_filter(DBusConnection* /*connection*/, DBusMessage* msg, void *user_data) { - simppl::ipc::Dispatcher* disp = (simppl::ipc::Dispatcher*)user_data; + simppl::dbus::Dispatcher* disp = (simppl::dbus::Dispatcher*)user_data; return disp->try_handle_signal(msg); } @@ -102,7 +102,7 @@ int make_dbus_flags(short events) namespace simppl { -namespace ipc +namespace dbus { struct Dispatcher::Private @@ -110,37 +110,37 @@ struct Dispatcher::Private static dbus_bool_t add_watch(DBusWatch *watch, void *data) { - return ((simppl::ipc::Dispatcher::Private*)data)->add_watch(watch); + return ((simppl::dbus::Dispatcher::Private*)data)->add_watch(watch); } static void remove_watch(DBusWatch *watch, void *data) { - ((simppl::ipc::Dispatcher::Private*)data)->remove_watch(watch); + ((simppl::dbus::Dispatcher::Private*)data)->remove_watch(watch); } static void toggle_watch(DBusWatch *watch, void *data) { - ((simppl::ipc::Dispatcher::Private*)data)->toggle_watch(watch); + ((simppl::dbus::Dispatcher::Private*)data)->toggle_watch(watch); } static dbus_bool_t add_timeout(DBusTimeout *timeout, void *data) { - return ((simppl::ipc::Dispatcher::Private*)data)->add_timeout(timeout); + return ((simppl::dbus::Dispatcher::Private*)data)->add_timeout(timeout); } static void remove_timeout(DBusTimeout *timeout, void *data) { - ((simppl::ipc::Dispatcher::Private*)data)->remove_timeout(timeout); + ((simppl::dbus::Dispatcher::Private*)data)->remove_timeout(timeout); } static void toggle_timeout(DBusTimeout *timeout, void *data) { - ((simppl::ipc::Dispatcher::Private*)data)->toggle_timeout(timeout); + ((simppl::dbus::Dispatcher::Private*)data)->toggle_timeout(timeout); } @@ -704,6 +704,6 @@ int Dispatcher::run() } } -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/src/error.cpp b/src/error.cpp index 32ac38f..d379880 100644 --- a/src/error.cpp +++ b/src/error.cpp @@ -8,7 +8,7 @@ namespace simppl { -namespace ipc +namespace dbus { RuntimeError::RuntimeError(int error) @@ -85,6 +85,6 @@ const char* TransportError::what() const throw() return buf_; } -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/src/serialization.cpp b/src/serialization.cpp index 251e09c..b77923d 100644 --- a/src/serialization.cpp +++ b/src/serialization.cpp @@ -4,7 +4,7 @@ namespace simppl { -namespace ipc +namespace dbus { detail::Serializer::Serializer(DBusMessage* msg) @@ -88,6 +88,6 @@ detail::Deserializer& detail::Deserializer::read(std::string& str) return *this; } -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/src/serverrequestdescriptor.cpp b/src/serverrequestdescriptor.cpp index d1269ba..0e17717 100644 --- a/src/serverrequestdescriptor.cpp +++ b/src/serverrequestdescriptor.cpp @@ -8,7 +8,7 @@ namespace simppl { -namespace ipc +namespace dbus { @@ -82,7 +82,7 @@ ServerRequestDescriptor::operator const void*() const } -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/src/serverresponseholder.cpp b/src/serverresponseholder.cpp index 99b3398..63d500b 100644 --- a/src/serverresponseholder.cpp +++ b/src/serverresponseholder.cpp @@ -6,7 +6,7 @@ namespace simppl { -namespace ipc +namespace dbus { namespace detail @@ -50,6 +50,6 @@ ServerResponseHolder& ServerResponseHolder::operator=(ServerResponseHolder&& rhs } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/src/serverside.cpp b/src/serverside.cpp index 42c1b68..361f420 100644 --- a/src/serverside.cpp +++ b/src/serverside.cpp @@ -9,7 +9,7 @@ namespace simppl { -namespace ipc +namespace dbus { @@ -28,6 +28,6 @@ ServerAttributeBase::ServerAttributeBase(const char* name, detail::BasicInterfac } -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/src/skeletonbase.cpp b/src/skeletonbase.cpp index 1a8fafd..4f01f87 100644 --- a/src/skeletonbase.cpp +++ b/src/skeletonbase.cpp @@ -13,7 +13,7 @@ namespace simppl { -namespace ipc +namespace dbus { @@ -261,6 +261,6 @@ std::tuple SkeletonBase::clientAttached() return std::tuple(nullptr, nullptr); // the default does not create any session data } */ -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/src/stubbase.cpp b/src/stubbase.cpp index 81b3ad5..07de908 100644 --- a/src/stubbase.cpp +++ b/src/stubbase.cpp @@ -16,7 +16,7 @@ using namespace std::literals::chrono_literals; namespace simppl { -namespace ipc +namespace dbus { StubBase::StubBase(const char* iface, const char* role) @@ -204,7 +204,7 @@ void StubBase::try_handle_signal(DBusMessage* msg) } -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/src/timeout.cpp b/src/timeout.cpp index 9ca46c5..610009f 100644 --- a/src/timeout.cpp +++ b/src/timeout.cpp @@ -4,7 +4,7 @@ namespace simppl { -namespace ipc +namespace dbus { __thread request_specific_timeout_helper timeout = {}; @@ -19,4 +19,4 @@ __thread std::chrono::milliseconds request_specific_timeout = std::chrono::milli } // namespace simppl -} // namespace ipc +} // namespace dbus diff --git a/src/util.cpp b/src/util.cpp index f88179f..e122dcf 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -7,7 +7,7 @@ namespace simppl { -namespace ipc +namespace dbus { namespace detail @@ -66,6 +66,6 @@ char* extract_interface(const char* mangled_iface) } // namespace detail -} // namespace ipc +} // namespace dbus } // namespace simppl diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 54f79c1..381ca3e 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -11,11 +11,11 @@ include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR}) add_executable(unittests - ipc2_timeout.cpp - ipc2_simple.cpp - ipc2_errors.cpp - ipc2_async_server.cpp - ipc2_attributes.cpp + timeout.cpp + simple.cpp + errors.cpp + async_server.cpp + attributes.cpp ) target_link_libraries(unittests gtest gtest_main simppl rt dbus-1) diff --git a/tests/ipc2_async_server.cpp b/tests/async_server.cpp similarity index 70% rename from tests/ipc2_async_server.cpp rename to tests/async_server.cpp index f5807f9..c818484 100644 --- a/tests/ipc2_async_server.cpp +++ b/tests/async_server.cpp @@ -44,10 +44,10 @@ using namespace test; namespace { -struct Client : simppl::ipc::Stub +struct Client : simppl::dbus::Stub { Client() - : simppl::ipc::Stub("s", "unix:AServerTest") + : simppl::dbus::Stub("s", "unix:AServerTest") { connected >> std::bind(&Client::handleConnected, this, _1); result >> std::bind(&Client::handleResult, this, _1, _2); @@ -55,22 +55,22 @@ struct Client : simppl::ipc::Stub } - void handleConnected(simppl::ipc::ConnectionState s) + void handleConnected(simppl::dbus::ConnectionState s) { - EXPECT_EQ(simppl::ipc::ConnectionState::Connected, s); + EXPECT_EQ(simppl::dbus::ConnectionState::Connected, s); add(42, 777); echo(42, 3.1415); } - void handleResult(const simppl::ipc::CallState& s, double d) + void handleResult(const simppl::dbus::CallState& s, double d) { EXPECT_TRUE((bool)s); oneway(42); } - void handleEcho(const simppl::ipc::CallState& s, int i, double d) + void handleEcho(const simppl::dbus::CallState& s, int i, double d) { EXPECT_TRUE((bool)s); haveEcho_ = true; @@ -80,32 +80,32 @@ struct Client : simppl::ipc::Stub }; -struct ShutdownClient : simppl::ipc::Stub +struct ShutdownClient : simppl::dbus::Stub { ShutdownClient() - : simppl::ipc::Stub("s", "unix:AServerTest") + : simppl::dbus::Stub("s", "unix:AServerTest") { connected >> std::bind(&ShutdownClient::handleConnected, this, _1); result >> std::bind(&ShutdownClient::handleResult, this, _1, _2); } - void handleConnected(simppl::ipc::ConnectionState s) + void handleConnected(simppl::dbus::ConnectionState s) { EXPECT_EQ(expected_, s); - if (s == simppl::ipc::ConnectionState::Connected) + if (s == simppl::dbus::ConnectionState::Connected) { add(42, 777); oneway(42); } - expected_ = simppl::ipc::ConnectionState::Disconnected; + expected_ = simppl::dbus::ConnectionState::Disconnected; ++count_; } - void handleResult(const simppl::ipc::CallState& s, double d) + void handleResult(const simppl::dbus::CallState& s, double d) { EXPECT_FALSE((bool)s); EXPECT_TRUE(s.isTransportError()); @@ -113,15 +113,15 @@ struct ShutdownClient : simppl::ipc::Stub disp().stop(); } - simppl::ipc::ConnectionState expected_ = simppl::ipc::ConnectionState::Connected; + simppl::dbus::ConnectionState expected_ = simppl::dbus::ConnectionState::Connected; int count_ = 0; }; -struct Server : simppl::ipc::Skeleton +struct Server : simppl::dbus::Skeleton { Server(const char* rolename) - : simppl::ipc::Skeleton(rolename) + : simppl::dbus::Skeleton(rolename) { oneway >> std::bind(&Server::handleOneway, this, _1); add >> std::bind(&Server::handleAdd, this, _1, _2); @@ -144,7 +144,7 @@ struct Server : simppl::ipc::Skeleton respondOn(req_, result(d)); } - simppl::ipc::ServerRequestDescriptor req_; + simppl::dbus::ServerRequestDescriptor req_; }; @@ -154,7 +154,7 @@ struct Server : simppl::ipc::Skeleton /// one response can overtake another TEST(AServer, trivial) { - simppl::ipc::Dispatcher d("dbus:session"); + simppl::dbus::Dispatcher d("dbus:session"); Client c; Server s("s"); @@ -171,8 +171,8 @@ TEST(AServer, trivial) /// with a transport error TEST(AServer, outstanding) { - std::unique_ptr sd(new simppl::ipc::Dispatcher("dbus:session")); - simppl::ipc::Dispatcher cd; + std::unique_ptr sd(new simppl::dbus::Dispatcher("dbus:session")); + simppl::dbus::Dispatcher cd; ShutdownClient c; std::unique_ptr s(new Server("s")); diff --git a/tests/ipc2_attributes.cpp b/tests/attributes.cpp similarity index 86% rename from tests/ipc2_attributes.cpp rename to tests/attributes.cpp index 38c2d46..dc48a70 100644 --- a/tests/ipc2_attributes.cpp +++ b/tests/attributes.cpp @@ -51,18 +51,18 @@ using namespace test; namespace { -struct Client : simppl::ipc::Stub +struct Client : simppl::dbus::Stub { Client() - : simppl::ipc::Stub("s") + : simppl::dbus::Stub("s") { connected >> std::bind(&Client::handleConnected, this, _1); } - void handleConnected(simppl::ipc::ConnectionState s) + void handleConnected(simppl::dbus::ConnectionState s) { - EXPECT_EQ(simppl::ipc::ConnectionState::Connected, s); + EXPECT_EQ(simppl::dbus::ConnectionState::Connected, s); props.attach() >> std::bind(&Client::handleProps, this, _1); set(Four, "Four"); @@ -111,19 +111,19 @@ struct Client : simppl::ipc::Stub }; -struct MultiClient : simppl::ipc::Stub +struct MultiClient : simppl::dbus::Stub { MultiClient(bool attach) - : simppl::ipc::Stub("s") + : simppl::dbus::Stub("s") , attach_(attach) { connected >> std::bind(&MultiClient::handleConnected, this, _1); } - void handleConnected(simppl::ipc::ConnectionState s) + void handleConnected(simppl::dbus::ConnectionState s) { - EXPECT_EQ(simppl::ipc::ConnectionState::Connected, s); + EXPECT_EQ(simppl::dbus::ConnectionState::Connected, s); if (attach_) { @@ -160,10 +160,10 @@ struct MultiClient : simppl::ipc::Stub }; -struct Server : simppl::ipc::Skeleton +struct Server : simppl::dbus::Skeleton { Server(const char* rolename) - : simppl::ipc::Skeleton(rolename) + : simppl::dbus::Skeleton(rolename) { shutdown >> std::bind(&Server::handleShutdown, this); set >> std::bind(&Server::handleSet, this, _1, _2); @@ -201,7 +201,7 @@ struct Server : simppl::ipc::Skeleton TEST(Attributes, attr) { - simppl::ipc::Dispatcher d("dbus:session"); + simppl::dbus::Dispatcher d("dbus:session"); Client c; Server s("s"); @@ -217,7 +217,7 @@ TEST(Attributes, attr) TEST(Attributes, multiple_attach) { - simppl::ipc::Dispatcher d("dbus:session"); + simppl::dbus::Dispatcher d("dbus:session"); MultiClient c1(true); MultiClient c2(false); Server s("s"); diff --git a/tests/ipc2_errors.cpp b/tests/errors.cpp similarity index 73% rename from tests/ipc2_errors.cpp rename to tests/errors.cpp index befc821..481fa85 100644 --- a/tests/ipc2_errors.cpp +++ b/tests/errors.cpp @@ -43,10 +43,10 @@ using namespace test; namespace { -struct Client : simppl::ipc::Stub +struct Client : simppl::dbus::Stub { Client() - : simppl::ipc::Stub("s", "unix:ErrorsTest") + : simppl::dbus::Stub("s", "unix:ErrorsTest") { connected >> std::bind(&Client::handleConnected, this, _1); @@ -55,14 +55,14 @@ struct Client : simppl::ipc::Stub } - void handleConnected(simppl::ipc::ConnectionState s) + void handleConnected(simppl::dbus::ConnectionState s) { - EXPECT_EQ(simppl::ipc::ConnectionState::Connected, s); + EXPECT_EQ(simppl::dbus::ConnectionState::Connected, s); hello(); } - void handleWorld(const simppl::ipc::CallState& state) + void handleWorld(const simppl::dbus::CallState& state) { EXPECT_FALSE((bool)state); EXPECT_FALSE(state.isTransportError()); @@ -73,7 +73,7 @@ struct Client : simppl::ipc::Stub } - void handleWorld1(const simppl::ipc::CallState& state, int) + void handleWorld1(const simppl::dbus::CallState& state, int) { EXPECT_FALSE((bool)state); EXPECT_FALSE(state.isTransportError()); @@ -85,10 +85,10 @@ struct Client : simppl::ipc::Stub }; -struct Server : simppl::ipc::Skeleton +struct Server : simppl::dbus::Skeleton { Server(const char* rolename) - : simppl::ipc::Skeleton(rolename) + : simppl::dbus::Skeleton(rolename) { hello >> std::bind(&Server::handleHello, this); hello1 >> std::bind(&Server::handleHello1, this, _1); @@ -96,12 +96,12 @@ struct Server : simppl::ipc::Skeleton void handleHello() { - respondWith(simppl::ipc::RuntimeError(-1, "Shit happens")); + respondWith(simppl::dbus::RuntimeError(-1, "Shit happens")); } void handleHello1(int i) { - respondWith(simppl::ipc::RuntimeError(-2, "Also shit")); + respondWith(simppl::dbus::RuntimeError(-2, "Also shit")); } }; @@ -111,7 +111,7 @@ struct Server : simppl::ipc::Skeleton TEST(Errors, methods) { - simppl::ipc::Dispatcher d("dbus:session"); + simppl::dbus::Dispatcher d("dbus:session"); Client c; Server s("s"); @@ -124,12 +124,12 @@ TEST(Errors, methods) TEST(Errors, blocking) { - simppl::ipc::Dispatcher d("dbus:session"); + simppl::dbus::Dispatcher d("dbus:session"); Server s("s"); d.addServer(s); - simppl::ipc::Stub stub("s", "unix:ErrorsTest"); + simppl::dbus::Stub stub("s", "unix:ErrorsTest"); d.addClient(stub); stub.connect(); @@ -141,7 +141,7 @@ TEST(Errors, blocking) // never reach ASSERT_FALSE(true); } - catch(const simppl::ipc::RuntimeError& e) + catch(const simppl::dbus::RuntimeError& e) { EXPECT_EQ(0, strcmp(e.what(), "Shit happens")); } @@ -158,7 +158,7 @@ TEST(Errors, blocking) // never reach ASSERT_FALSE(true); } - catch(const simppl::ipc::RuntimeError& e) + catch(const simppl::dbus::RuntimeError& e) { EXPECT_EQ(0, strcmp(e.what(), "Also shit")); } diff --git a/tests/ipc2_simple.cpp b/tests/simple.cpp similarity index 76% rename from tests/ipc2_simple.cpp rename to tests/simple.cpp index dab1dd8..58f7961 100644 --- a/tests/ipc2_simple.cpp +++ b/tests/simple.cpp @@ -56,24 +56,24 @@ using namespace test; namespace { -struct Client : simppl::ipc::Stub +struct Client : simppl::dbus::Stub { Client() - : simppl::ipc::Stub("s", "unix:SimpleTest") + : simppl::dbus::Stub("s", "unix:SimpleTest") { connected >> std::bind(&Client::handleConnected, this, _1); world >> std::bind(&Client::handleWorld, this, _1); } - void handleConnected(simppl::ipc::ConnectionState s) + void handleConnected(simppl::dbus::ConnectionState s) { - EXPECT_EQ(simppl::ipc::ConnectionState::Connected, s); + EXPECT_EQ(simppl::dbus::ConnectionState::Connected, s); hello(); } - void handleWorld(const simppl::ipc::CallState& state) + void handleWorld(const simppl::dbus::CallState& state) { EXPECT_TRUE((bool)state); EXPECT_FALSE(state.isTransportError()); @@ -87,45 +87,45 @@ struct Client : simppl::ipc::Stub }; -struct DisconnectClient : simppl::ipc::Stub +struct DisconnectClient : simppl::dbus::Stub { DisconnectClient() - : simppl::ipc::Stub("s", "unix:SimpleTest") + : simppl::dbus::Stub("s", "unix:SimpleTest") { connected >> std::bind(&DisconnectClient::handleConnected, this, _1); } - void handleConnected(simppl::ipc::ConnectionState s) + void handleConnected(simppl::dbus::ConnectionState s) { EXPECT_EQ(expected_, s); - if (s == simppl::ipc::ConnectionState::Connected) + if (s == simppl::dbus::ConnectionState::Connected) { oneway(7777); } else disp().stop(); - expected_ = simppl::ipc::ConnectionState::Disconnected; + expected_ = simppl::dbus::ConnectionState::Disconnected; } - simppl::ipc::ConnectionState expected_ = simppl::ipc::ConnectionState::Connected; + simppl::dbus::ConnectionState expected_ = simppl::dbus::ConnectionState::Connected; }; -struct AttributeClient : simppl::ipc::Stub +struct AttributeClient : simppl::dbus::Stub { AttributeClient() - : simppl::ipc::Stub("sa", "unix:SimpleTest") + : simppl::dbus::Stub("sa", "unix:SimpleTest") { connected >> std::bind(&AttributeClient::handleConnected, this, _1); } - void handleConnected(simppl::ipc::ConnectionState s) + void handleConnected(simppl::dbus::ConnectionState s) { - EXPECT_EQ(simppl::ipc::ConnectionState::Connected, s); + EXPECT_EQ(simppl::dbus::ConnectionState::Connected, s); // like for signals, attributes must be attached when the client is connected data.attach() >> std::bind(&AttributeClient::attributeChanged, this, _1); @@ -158,18 +158,18 @@ struct AttributeClient : simppl::ipc::Stub }; -struct SignalClient : simppl::ipc::Stub +struct SignalClient : simppl::dbus::Stub { SignalClient() - : simppl::ipc::Stub("ss", "unix:SimpleTest") + : simppl::dbus::Stub("ss", "unix:SimpleTest") { connected >> std::bind(&SignalClient::handleConnected, this, _1); } - void handleConnected(simppl::ipc::ConnectionState s) + void handleConnected(simppl::dbus::ConnectionState s) { - EXPECT_EQ(simppl::ipc::ConnectionState::Connected, s); + EXPECT_EQ(simppl::dbus::ConnectionState::Connected, s); // like for attributes, attributes must be attached when the client is connected sig.attach() >> std::bind(&SignalClient::handleSignal, this, _1); @@ -196,10 +196,10 @@ struct SignalClient : simppl::ipc::Stub }; -struct Server : simppl::ipc::Skeleton +struct Server : simppl::dbus::Skeleton { Server(const char* rolename) - : simppl::ipc::Skeleton(rolename) + : simppl::dbus::Skeleton(rolename) { hello >> std::bind(&Server::handleHello, this); oneway >> std::bind(&Server::handleOneway, this, _1); @@ -251,7 +251,7 @@ struct Server : simppl::ipc::Skeleton TEST(Simple, methods) { - simppl::ipc::Dispatcher d("dbus:session"); + simppl::dbus::Dispatcher d("dbus:session"); Client c; Server s("s"); @@ -264,7 +264,7 @@ TEST(Simple, methods) TEST(Simple, signal) { - simppl::ipc::Dispatcher d("dbus:session"); + simppl::dbus::Dispatcher d("dbus:session"); SignalClient c; Server s("ss"); @@ -279,7 +279,7 @@ TEST(Simple, signal) TEST(Simple, attribute) { - simppl::ipc::Dispatcher d("dbus:session"); + simppl::dbus::Dispatcher d("dbus:session"); AttributeClient c; Server s("sa"); @@ -292,12 +292,12 @@ TEST(Simple, attribute) TEST(Simple, blocking) { - simppl::ipc::Dispatcher d("dbus:session"); + simppl::dbus::Dispatcher d("dbus:session"); Server s("sb"); d.addServer(s); - simppl::ipc::Stub stub("sb", "dbus:session"); + simppl::dbus::Stub stub("sb", "dbus:session"); d.addClient(stub); stub.connect(); @@ -333,13 +333,13 @@ TEST(Simple, blocking) TEST(Simple, disconnect) { - simppl::ipc::Dispatcher clientd; + simppl::dbus::Dispatcher clientd; DisconnectClient c; clientd.addClient(c); { - simppl::ipc::Dispatcher* serverd = new simppl::ipc::Dispatcher("dbus:session"); + simppl::dbus::Dispatcher* serverd = new simppl::dbus::Dispatcher("dbus:session"); Server* s = new Server("s"); serverd->addServer(*s); diff --git a/tests/ipc2_timeout.cpp b/tests/timeout.cpp similarity index 65% rename from tests/ipc2_timeout.cpp rename to tests/timeout.cpp index a1a9bb1..926ad26 100644 --- a/tests/ipc2_timeout.cpp +++ b/tests/timeout.cpp @@ -40,40 +40,40 @@ using namespace test; namespace { -simppl::ipc::Dispatcher* gbl_disp = nullptr; +simppl::dbus::Dispatcher* gbl_disp = nullptr; -struct Client : simppl::ipc::Stub +struct Client : simppl::dbus::Stub { Client() - : simppl::ipc::Stub("tm", "unix:TimeoutTest") + : simppl::dbus::Stub("tm", "unix:TimeoutTest") { connected >> std::bind(&Client::handleConnected, this, _1); rEval >> std::bind(&Client::handleEval, this, _1, _2); } - void handleConnected(simppl::ipc::ConnectionState s) + void handleConnected(simppl::dbus::ConnectionState s) { EXPECT_EQ(expect_, s); - if (s == simppl::ipc::ConnectionState::Connected) + if (s == simppl::dbus::ConnectionState::Connected) { start_ = std::chrono::steady_clock::now(); eval(42); } - expect_ = simppl::ipc::ConnectionState::Disconnected; + expect_ = simppl::dbus::ConnectionState::Disconnected; } - void handleEval(const simppl::ipc::CallState& state, double) + void handleEval(const simppl::dbus::CallState& state, double) { EXPECT_FALSE((bool)state); EXPECT_TRUE(state.isTransportError()); EXPECT_FALSE(state.isRuntimeError()); - EXPECT_EQ(EIO, static_cast(state.exception()).getErrno()); + EXPECT_EQ(EIO, static_cast(state.exception()).getErrno()); int millis = std::chrono::duration_cast(std::chrono::steady_clock::now() - start_).count(); EXPECT_GE(millis, 500); @@ -85,95 +85,95 @@ struct Client : simppl::ipc::Stub std::chrono::steady_clock::time_point start_; - simppl::ipc::ConnectionState expect_ = simppl::ipc::ConnectionState::Connected; + simppl::dbus::ConnectionState expect_ = simppl::dbus::ConnectionState::Connected; }; -struct DisconnectClient : simppl::ipc::Stub +struct DisconnectClient : simppl::dbus::Stub { DisconnectClient() - : simppl::ipc::Stub("tm", "unix:TimeoutTest") + : simppl::dbus::Stub("tm", "unix:TimeoutTest") { connected >> std::bind(&DisconnectClient::handleConnected, this, _1); rEval >> std::bind(&DisconnectClient::handleEval, this, _1, _2); } - void handleConnected(simppl::ipc::ConnectionState s) + void handleConnected(simppl::dbus::ConnectionState s) { EXPECT_EQ(expect_, s); - if (s == simppl::ipc::ConnectionState::Connected) + if (s == simppl::dbus::ConnectionState::Connected) eval(777); - expect_ = simppl::ipc::ConnectionState::Disconnected; + expect_ = simppl::dbus::ConnectionState::Disconnected; } - void handleEval(const simppl::ipc::CallState& state, double) + void handleEval(const simppl::dbus::CallState& state, double) { EXPECT_FALSE((bool)state); EXPECT_TRUE(state.isTransportError()); - EXPECT_EQ(ECONNABORTED, static_cast(state.exception()).getErrno()); + EXPECT_EQ(ECONNABORTED, static_cast(state.exception()).getErrno()); EXPECT_FALSE(state.isRuntimeError()); disp().stop(); } - simppl::ipc::ConnectionState expect_ = simppl::ipc::ConnectionState::Connected; + simppl::dbus::ConnectionState expect_ = simppl::dbus::ConnectionState::Connected; }; -struct OnewayClient : simppl::ipc::Stub +struct OnewayClient : simppl::dbus::Stub { OnewayClient() - : simppl::ipc::Stub("tm", "unix:TimeoutTest") + : simppl::dbus::Stub("tm", "unix:TimeoutTest") { connected >> std::bind(&OnewayClient::handleConnected, this, _1); } - void handleConnected(simppl::ipc::ConnectionState s) + void handleConnected(simppl::dbus::ConnectionState s) { EXPECT_EQ(expect_, s); - if (s == simppl::ipc::ConnectionState::Connected) + if (s == simppl::dbus::ConnectionState::Connected) { gbl_disp = &disp(); oneway(42); } - expect_ = simppl::ipc::ConnectionState::Disconnected; + expect_ = simppl::dbus::ConnectionState::Disconnected; } - simppl::ipc::ConnectionState expect_ = simppl::ipc::ConnectionState::Connected; + simppl::dbus::ConnectionState expect_ = simppl::dbus::ConnectionState::Connected; }; -struct NeverConnectedClient : simppl::ipc::Stub +struct NeverConnectedClient : simppl::dbus::Stub { - NeverConnectedClient(simppl::ipc::ConnectionState expected = simppl::ipc::ConnectionState::Timeout) - : simppl::ipc::Stub("tm", "unix:TimeoutTest") + NeverConnectedClient(simppl::dbus::ConnectionState expected = simppl::dbus::ConnectionState::Timeout) + : simppl::dbus::Stub("tm", "unix:TimeoutTest") , expected_(expected) { connected >> std::bind(&NeverConnectedClient::handleConnected, this, _1); } - void handleConnected(simppl::ipc::ConnectionState s) + void handleConnected(simppl::dbus::ConnectionState s) { EXPECT_EQ(expected_, s); disp().stop(); } - simppl::ipc::ConnectionState expected_; + simppl::dbus::ConnectionState expected_; }; -struct Server : simppl::ipc::Skeleton +struct Server : simppl::dbus::Skeleton { Server() - : simppl::ipc::Skeleton("tm") + : simppl::dbus::Skeleton("tm") { eval >> std::bind(&Server::handleEval, this, _1); oneway >> std::bind(&Server::handleOneway, this, _1); @@ -207,7 +207,7 @@ struct Server : simppl::ipc::Skeleton void runServer() { - simppl::ipc::Dispatcher d("dbus:session"); + simppl::dbus::Dispatcher d("dbus:session"); gbl_disp = &d; try{ @@ -225,7 +225,7 @@ catch(...) void runClient() { - simppl::ipc::Dispatcher d; + simppl::dbus::Dispatcher d; DisconnectClient c; d.addClient(c); @@ -239,7 +239,7 @@ TEST(Timeout, method) { std::thread serverthread(&runServer); - simppl::ipc::Dispatcher d; + simppl::dbus::Dispatcher d; Client c; d.setRequestTimeout(500ms); @@ -255,7 +255,7 @@ TEST(Timeout, oneway) { std::thread serverthread(&runServer); - simppl::ipc::Dispatcher d; + simppl::dbus::Dispatcher d; OnewayClient c; d.setRequestTimeout(500ms); @@ -284,8 +284,8 @@ TEST(Timeout, request_specific) { std::thread serverthread(&runServer); - simppl::ipc::Dispatcher d("dbus:session"); - simppl::ipc::Stub stub("tm", "unix:TimeoutTest"); + simppl::dbus::Dispatcher d("dbus:session"); + simppl::dbus::Stub stub("tm", "unix:TimeoutTest"); // default timeout d.setRequestTimeout(500ms); @@ -300,12 +300,12 @@ TEST(Timeout, request_specific) double rc; // request specific timeout -> overrides default - stub.eval[simppl::ipc::timeout = 700ms](42) >> rc; + stub.eval[simppl::dbus::timeout = 700ms](42) >> rc; // never arrive here! EXPECT_FALSE(true); } - catch(simppl::ipc::TransportError& err) + catch(simppl::dbus::TransportError& err) { EXPECT_EQ(EIO, err.getErrno()); } @@ -322,8 +322,8 @@ TEST(Timeout, request_specific) TEST(Timeout, blocking_connect) { - simppl::ipc::Dispatcher d; - simppl::ipc::Stub stub("tm", "unix:TimeoutTest"); + simppl::dbus::Dispatcher d; + simppl::dbus::Stub stub("tm", "unix:TimeoutTest"); d.setRequestTimeout(500ms); d.addClient(stub); @@ -335,7 +335,7 @@ TEST(Timeout, blocking_connect) // never arrive here! EXPECT_FALSE(true); } - catch(const simppl::ipc::TransportError& err) + catch(const simppl::dbus::TransportError& err) { EXPECT_EQ(ETIMEDOUT, err.getErrno()); } @@ -346,8 +346,8 @@ TEST(Timeout, blocking_api) { std::thread serverthread(&runServer); - simppl::ipc::Dispatcher d; - simppl::ipc::Stub stub("tm", "unix:TimeoutTest"); + simppl::dbus::Dispatcher d; + simppl::dbus::Stub stub("tm", "unix:TimeoutTest"); d.setRequestTimeout(500ms); d.addClient(stub); @@ -362,7 +362,7 @@ TEST(Timeout, blocking_api) // never arrive here! EXPECT_FALSE(true); } - catch(const simppl::ipc::TransportError& err) + catch(const simppl::dbus::TransportError& err) { EXPECT_EQ(EIO, err.getErrno()); }