Unverified Commit 1de110dd authored by Noir's avatar Noir Committed by GitHub

Merge branch 'master' into issue/1195

parents 39cb34c8 c089c764
......@@ -22,6 +22,8 @@ is based on [Keep a Changelog](https://keepachangelog.com).
trying to parse the input of `x` if it contains a string. The function
`get_or` already existed for `settings`, but we have added new overloads for
generalizing the function to `config_value` as well.
- The `typed_response_promise` received additional member functions to mirror
the interface of the untyped `response_promise`.
### Deprecated
......@@ -84,6 +86,8 @@ is based on [Keep a Changelog](https://keepachangelog.com).
- Skipping high-priority messages resulted in CAF lowering the priority to
normal. This unintentional demotion has been fixed (#1171).
- Fix undefined behavior in the experimental datagram brokers (#1174).
- Response promises no longer send empty messages in response to asynchronous
messages.
- `CAF_ADD_TYPE_ID` now works with types that live in namespaces that also exist
as nested namespace in CAF such as `detail` or `io` (#1195).
......
cmake_minimum_required(VERSION 3.5...3.18 FATAL_ERROR)
project(CAF CXX)
cmake_policy(PUSH)
cmake_policy(VERSION 3.5...3.18)
# -- includes ------------------------------------------------------------------
include(CMakeDependentOption)
......@@ -49,11 +46,8 @@ cmake_dependent_option(CAF_ENABLE_OPENSSL_MODULE "Build OpenSSL module" ON
set(CAF_LOG_LEVEL "QUIET" CACHE STRING "Set log verbosity of CAF components")
set(CAF_SANITIZERS "" CACHE STRING
"Comma separated sanitizers, e.g., 'address,undefined'")
set(CAF_INSTALL_CMAKEDIR
"${CMAKE_INSTALL_FULL_LIBDIR}/cmake/CAF" CACHE PATH
"Path for installing CMake files, enables 'find_package(CAF)'")
set(CAF_BUILD_INFO_FILE_PATH "" CACHE FILEPATH
"Optional path for writing CMake and compiler version information")
set(CAF_BUILD_INFO_FILE_PATH "" CACHE FILEPATH
"Optional path for writing CMake and compiler version information")
# -- macOS-specific options ----------------------------------------------------
......@@ -450,7 +444,7 @@ endif()
export(EXPORT CAFTargets FILE CAFTargets.cmake NAMESPACE CAF::)
install(EXPORT CAFTargets
DESTINATION "${CAF_INSTALL_CMAKEDIR}"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/CAF"
NAMESPACE CAF::)
write_basic_package_version_file(
......@@ -461,15 +455,14 @@ write_basic_package_version_file(
configure_package_config_file(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/CAFConfig.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/CAFConfig.cmake"
INSTALL_DESTINATION "${CAF_INSTALL_CMAKEDIR}")
INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/CAF")
install(
FILES
"${CMAKE_CURRENT_BINARY_DIR}/CAFConfig.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/CAFConfigVersion.cmake"
DESTINATION
"${CAF_INSTALL_CMAKEDIR}")
"${CMAKE_INSTALL_LIBDIR}/cmake/CAF")
# -- extra file output (primarily for CAF CI) ----------------------------------
......@@ -478,5 +471,3 @@ if(CAF_BUILD_INFO_FILE_PATH)
"${CAF_BUILD_INFO_FILE_PATH}"
@ONLY)
endif()
cmake_policy(POP)
......@@ -45,7 +45,7 @@ add_core_example(custom_type custom_types_3)
# testing DSL
add_example(testing ping_pong)
target_link_libraries(ping_pong PRIVATE CAF::internal CAF::core CAF::test)
add_test(NAME "examples.ping-pong" COMMAND ping_pong -r300 -n -v5)
# -- examples for CAF::io ------------------------------------------------------
......
#include <random>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <random>
#include "caf/all.hpp"
#include "caf/actor_ostream.hpp"
#include "caf/actor_system.hpp"
#include "caf/caf_main.hpp"
#include "caf/event_based_actor.hpp"
using namespace caf;
using std::endl;
void caf_main(actor_system& system) {
for (int i = 1; i <= 50; ++i) {
system.spawn([i](blocking_actor* self) {
aout(self) << "Hi there! This is actor nr. "
<< i << "!" << endl;
std::random_device rd;
std::default_random_engine re(rd());
std::chrono::milliseconds tout{re() % 10};
self->delayed_send(self, tout, 42);
self->receive(
[i, self](int) {
aout(self) << "Actor nr. "
<< i << " says goodbye!" << endl;
}
);
});
}
behavior printer(event_based_actor* self, int32_t num, int32_t delay) {
aout(self) << "Hi there! This is actor nr. " << num << "!" << std::endl;
std::chrono::milliseconds timeout{delay};
self->delayed_send(self, timeout, timeout_atom_v);
return {
[=](timeout_atom) {
aout(self) << "Actor nr. " << num << " says goodbye after waiting for "
<< delay << "ms!" << std::endl;
},
};
}
void caf_main(actor_system& sys) {
std::random_device rd;
std::minstd_rand re(rd());
std::uniform_int_distribution<int32_t> dis{1, 99};
for (int32_t i = 1; i <= 50; ++i)
sys.spawn(printer, i, dis(re));
}
CAF_MAIN()
......@@ -7,8 +7,6 @@
* - simple_broker -c localhost 4242 *
\******************************************************************************/
// Manual refs: 42-47 (Actors.tex)
#include "caf/config.hpp"
#ifdef CAF_WINDOWS
......@@ -38,12 +36,14 @@ using namespace caf::io;
namespace {
// --(rst-attach-begin)--
// Utility function to print an exit message with custom name.
void print_on_exit(const actor& hdl, const std::string& name) {
hdl->attach_functor([=](const error& reason) {
cout << name << " exited: " << to_string(reason) << endl;
});
}
// --(rst-attach-end)--
enum class op : uint8_t {
ping,
......
// Showcases how to add custom POD message types.
// Manual refs: 24-27, 30-34, 75-78, 81-84 (ConfiguringActorApplications)
// 23-33 (TypeInspection)
#include <cassert>
#include <iostream>
#include <string>
......
#include <string>
#include <iostream>
#include "caf/all.hpp"
using std::endl;
using std::string;
#include "caf/actor_ostream.hpp"
#include "caf/actor_system.hpp"
#include "caf/caf_main.hpp"
#include "caf/event_based_actor.hpp"
using namespace caf;
......@@ -13,32 +13,32 @@ behavior mirror(event_based_actor* self) {
return {
// a handler for messages containing a single string
// that replies with a string
[=](const string& what) -> string {
[=](const std::string& what) -> std::string {
// prints "Hello World!" via aout (thread-safe cout wrapper)
aout(self) << what << endl;
aout(self) << what << std::endl;
// reply "!dlroW olleH"
return string(what.rbegin(), what.rend());
}
return std::string{what.rbegin(), what.rend()};
},
};
}
void hello_world(event_based_actor* self, const actor& buddy) {
// send "Hello World!" to our buddy ...
self->request(buddy, std::chrono::seconds(10), "Hello World!").then(
// ... wait up to 10s for a response ...
[=](const string& what) {
// ... and print it
aout(self) << what << endl;
}
);
self->request(buddy, std::chrono::seconds(10), "Hello World!")
.then(
// ... wait up to 10s for a response ...
[=](const std::string& what) {
// ... and print it
aout(self) << what << std::endl;
});
}
void caf_main(actor_system& system) {
void caf_main(actor_system& sys) {
// create a new actor that calls 'mirror()'
auto mirror_actor = system.spawn(mirror);
auto mirror_actor = sys.spawn(mirror);
// create another actor that calls 'hello_world(mirror_actor)';
system.spawn(hello_world, mirror_actor);
// system will wait until both actors are destroyed before leaving main
sys.spawn(hello_world, mirror_actor);
// the system will wait until both actors are done before exiting the program
}
// creates a main function for us that calls our caf_main
......
......@@ -3,8 +3,6 @@
* for both the blocking and the event-based API. *
\******************************************************************************/
// Manual refs: lines 17-18, 21-26, 28-56, 58-92, 123-128 (Actor)
#include <iostream>
#include "caf/all.hpp"
......@@ -14,18 +12,22 @@ using namespace caf;
namespace {
// --(rst-calculator-actor-begin)--
using calculator_actor
= typed_actor<result<int32_t>(add_atom, int32_t, int32_t),
result<int32_t>(sub_atom, int32_t, int32_t)>;
// --(rst-calculator-actor-end)--
// prototypes and forward declarations
// --(rst-prototypes-begin)--
behavior calculator_fun(event_based_actor* self);
void blocking_calculator_fun(blocking_actor* self);
calculator_actor::behavior_type typed_calculator_fun();
class calculator;
class blocking_calculator;
class typed_calculator;
// --(rst-prototypes-end)--
// --(rst-function-based-begin)--
// function-based, dynamically typed, event-based API
behavior calculator_fun(event_based_actor*) {
return {
......@@ -55,7 +57,9 @@ calculator_actor::behavior_type typed_calculator_fun() {
[](sub_atom, int32_t a, int32_t b) { return a - b; },
};
}
// --(rst-function-based-end)--
// --(rst-class-based-begin)--
// class-based, dynamically typed, event-based API
class calculator : public event_based_actor {
public:
......@@ -91,6 +95,7 @@ public:
return typed_calculator_fun();
}
};
// --(rst-class-based-end)--
void tester(scoped_actor&) {
// end of recursion
......@@ -120,14 +125,16 @@ void tester(scoped_actor& self, const Handle& hdl, int32_t x, int32_t y,
tester(self, std::forward<Ts>(xs)...);
}
void caf_main(actor_system& system) {
auto a1 = system.spawn(blocking_calculator_fun);
auto a2 = system.spawn(calculator_fun);
auto a3 = system.spawn(typed_calculator_fun);
auto a4 = system.spawn<blocking_calculator>();
auto a5 = system.spawn<calculator>();
auto a6 = system.spawn<typed_calculator>();
scoped_actor self{system};
void caf_main(actor_system& sys) {
// --(rst-spawn-begin)--
auto a1 = sys.spawn(blocking_calculator_fun);
auto a2 = sys.spawn(calculator_fun);
auto a3 = sys.spawn(typed_calculator_fun);
auto a4 = sys.spawn<blocking_calculator>();
auto a5 = sys.spawn<calculator>();
auto a6 = sys.spawn<typed_calculator>();
// --(rst-spawn-end)--
scoped_actor self{sys};
tester(self, a1, 1, 2, a2, 3, 4, a3, 5, 6, a4, 7, 8, a5, 9, 10, a6, 11, 12);
self->send_exit(a1, exit_reason::user_shutdown);
self->send_exit(a4, exit_reason::user_shutdown);
......
......@@ -40,7 +40,7 @@ behavior unchecked_cell(stateful_actor<cell_state>* self) {
// --(rst-cell-end)--
void caf_main(actor_system& system) {
// --(rst-spawn-cell-end)--
// --(rst-spawn-cell-begin)--
// Create one cell for each implementation.
auto cell1 = system.spawn(type_checked_cell);
auto cell2 = system.spawn(unchecked_cell);
......@@ -50,7 +50,7 @@ void caf_main(actor_system& system) {
f(put_atom_v, 20);
cout << "cell value (after setting to 20): " << f(get_atom_v) << endl;
// Get an unchecked cell and send it some garbage. Triggers an "unexpected
// message" error.
// message" error (and terminates cell2!).
anon_send(cell2, "hello there!");
}
......
......@@ -55,24 +55,28 @@ void draw_kirby(const animation_step& animation) {
cout.flush();
}
// --(rst-delayed-send-begin)--
// uses a message-based loop to iterate over all animation steps
void dancing_kirby(event_based_actor* self) {
behavior dancing_kirby(event_based_actor* self) {
using namespace std::literals::chrono_literals;
// let's get it started
self->send(self, update_atom_v, size_t{0});
self->become([=](update_atom, size_t step) {
if (step == sizeof(animation_step)) {
// we've printed all animation steps (done)
cout << endl;
self->quit();
return;
}
// print given step
draw_kirby(animation_steps[step]);
// animate next step in 150ms
self->delayed_send(self, std::chrono::milliseconds(150), update_atom_v,
step + 1);
});
return {
[=](update_atom, size_t step) {
if (step == sizeof(animation_step)) {
// we've printed all animation steps (done)
cout << endl;
self->quit();
return;
}
// print given step
draw_kirby(animation_steps[step]);
// schedule next animation step
self->delayed_send(self, 150ms, update_atom_v, step + 1);
},
};
}
// --(rst-delayed-send-end)--
void caf_main(actor_system& system) {
system.spawn(dancing_kirby);
......
#include <iostream>
#include "caf/all.hpp"
// This file is partially included in the manual, do not modify
// without updating the references in the *.tex files!
// Manual references: lines 15-36 (MessagePassing.tex)
using namespace caf;
// using add_atom = atom_constant<atom("add")>; (defined in atom.hpp)
using calc = typed_actor<result<int32_t>(add_atom, int32_t, int32_t)>;
// --(rst-delegate-begin)--
using adder_actor = typed_actor<result<int32_t>(add_atom, int32_t, int32_t)>;
void actor_a(event_based_actor* self, const calc& worker) {
self->request(worker, std::chrono::seconds(10), add_atom_v, 1, 2)
.then([=](int32_t result) { //
aout(self) << "1 + 2 = " << result << std::endl;
});
adder_actor::behavior_type worker_impl() {
return {
[](add_atom, int32_t x, int32_t y) { return x + y; },
};
}
calc::behavior_type actor_b(calc::pointer self, const calc& worker) {
adder_actor::behavior_type server_impl(adder_actor::pointer self,
adder_actor worker) {
return {
[=](add_atom add, int32_t x, int32_t y) {
return self->delegate(worker, add, x, y);
......@@ -27,14 +19,19 @@ calc::behavior_type actor_b(calc::pointer self, const calc& worker) {
};
}
calc::behavior_type actor_c() {
return {
[](add_atom, int32_t x, int32_t y) { return x + y; },
};
void client_impl(event_based_actor* self, adder_actor adder, int32_t x,
int32_t y) {
using namespace std::literals::chrono_literals;
self->request(adder, 10s, add_atom_v, x, y).then([=](int32_t result) {
aout(self) << x << " + " << y << " = " << result << std::endl;
});
}
void caf_main(actor_system& system) {
system.spawn(actor_a, system.spawn(actor_b, system.spawn(actor_c)));
void caf_main(actor_system& sys) {
auto worker = sys.spawn(worker_impl);
auto server = sys.spawn(server_impl, sys.spawn(worker_impl));
sys.spawn(client_impl, server, 1, 2);
}
// --(rst-delegate-end)--
CAF_MAIN()
......@@ -2,18 +2,11 @@
* A very basic, interactive divider. *
\******************************************************************************/
// Manual refs: 17-19, 49-59, 70-76 (MessagePassing);
// 17-47 (Error)
#include <iostream>
#include "caf/all.hpp"
using std::cout;
using std::endl;
using std::flush;
using namespace caf;
// --(rst-math-error-begin)--
enum class math_error : uint8_t {
division_by_zero = 1,
};
......@@ -27,6 +20,29 @@ std::string to_string(math_error x) {
}
}
bool from_string(caf::string_view in, math_error& out) {
if (in == "division_by_zero") {
out = math_error::division_by_zero;
return true;
} else {
return false;
}
}
bool from_integer(uint8_t in, math_error& out) {
if (in == 1) {
out = math_error::division_by_zero;
return true;
} else {
return false;
}
}
template <class Inspector>
bool inspect(Inspector& f, math_error& x) {
return caf::default_enum_inspect(f, x);
}
CAF_BEGIN_TYPE_ID_BLOCK(divider, first_custom_type_id)
CAF_ADD_TYPE_ID(divider, (math_error))
......@@ -34,7 +50,15 @@ CAF_BEGIN_TYPE_ID_BLOCK(divider, first_custom_type_id)
CAF_END_TYPE_ID_BLOCK(divider)
CAF_ERROR_CODE_ENUM(math_error)
// --(rst-math-error-end)--
using std::cout;
using std::endl;
using std::flush;
using namespace caf;
// --(rst-divider-begin)--
using divider = typed_actor<result<double>(div_atom, double, double)>;
divider::behavior_type divider_impl() {
......@@ -46,6 +70,7 @@ divider::behavior_type divider_impl() {
},
};
}
// --(rst-divider-end)--
void caf_main(actor_system& system) {
double x;
......@@ -54,6 +79,7 @@ void caf_main(actor_system& system) {
std::cin >> x;
cout << "y: " << flush;
std::cin >> y;
// --(rst-request-begin)--
auto div = system.spawn(divider_impl);
scoped_actor self{system};
self->request(div, std::chrono::seconds(10), div_atom_v, x, y)
......@@ -63,6 +89,7 @@ void caf_main(actor_system& system) {
aout(self) << "*** cannot compute " << x << " / " << y << " => "
<< to_string(err) << endl;
});
// --(rst-request-end)--
}
CAF_MAIN(id_block::divider)
// This file is partially included in the manual, do not modify
// without updating the references in the *.tex files!
// Manual references: lines 86-98 (MessagePassing.tex)
#include <cassert>
#include <chrono>
#include <iomanip>
......@@ -101,6 +97,7 @@ matrix::behavior_type matrix_actor(matrix::stateful_pointer<matrix_state> self,
[=](error& err) mutable { rp.deliver(std::move(err)); });
return rp;
},
// --(rst-fan-out-begin)--
[=](get_atom get, average_atom, column_atom, int column) {
assert(column < columns);
std::vector<cell> columns;
......@@ -118,6 +115,7 @@ matrix::behavior_type matrix_actor(matrix::stateful_pointer<matrix_state> self,
[=](error& err) mutable { rp.deliver(std::move(err)); });
return rp;
},
// --(rst-fan-out-end)--
};
}
......
......@@ -19,6 +19,43 @@ CAF_END_TYPE_ID_BLOCK(fixed_stack)
CAF_ERROR_CODE_ENUM(fixed_stack_errc)
std::string to_string(fixed_stack_errc x) {
switch (x) {
case fixed_stack_errc::push_to_full:
return "push_to_full";
case fixed_stack_errc::pop_from_empty:
return "pop_from_empty";
default:
return "-unknown-error-";
}
}
bool from_string(caf::string_view in, fixed_stack_errc& out) {
if (in == "push_to_full") {
out = fixed_stack_errc::push_to_full;
return true;
} else if (in == "pop_from_empty") {
out = fixed_stack_errc::pop_from_empty;
return true;
} else {
return false;
}
}
bool from_integer(uint8_t in, fixed_stack_errc& out) {
if (in > 0 && in < 1) {
out = static_cast<fixed_stack_errc>(in);
return true;
} else {
return false;
}
}
template <class Inspector>
bool inspect(Inspector& f, fixed_stack_errc& x) {
return caf::default_enum_inspect(f, x);
}
using std::endl;
using namespace caf;
......
/******************************************************************************\
* Illustrates response promises. *
\******************************************************************************/
// This file is partially included in the manual, do not modify
// without updating the references in the *.tex files!
// Manual references: lines 18-43 (MessagePassing.tex)
#include <iostream>
#include "caf/all.hpp"
using std::cout;
using std::endl;
using namespace caf;
using adder = typed_actor<result<int32_t>(add_atom, int32_t, int32_t)>;
// --(rst-promise-begin)--
using adder_actor = typed_actor<result<int32_t>(add_atom, int32_t, int32_t)>;
// function-based, statically typed, event-based API
adder::behavior_type worker() {
adder_actor::behavior_type worker_impl() {
return {
[](add_atom, int32_t a, int32_t b) { return a + b; },
[](add_atom, int32_t x, int32_t y) { return x + y; },
};
}
// function-based, statically typed, event-based API
adder::behavior_type calculator_master(adder::pointer self) {
auto w = self->spawn(worker);
adder_actor::behavior_type server_impl(adder_actor::pointer self,
adder_actor worker) {
return {
[=](add_atom x, int32_t y, int32_t z) -> result<int32_t> {
[=](add_atom, int32_t y, int32_t z) {
auto rp = self->make_response_promise<int32_t>();
self->request(w, infinite, x, y, z).then([=](int32_t result) mutable {
rp.deliver(result);
});
self->request(worker, infinite, add_atom_v, y, z)
.then([rp](int32_t result) mutable { rp.deliver(result); });
return rp;
},
};
}
void caf_main(actor_system& system) {
auto f = make_function_view(system.spawn(calculator_master));
cout << "12 + 13 = " << f(add_atom_v, 12, 13) << endl;
void client_impl(event_based_actor* self, adder_actor adder, int32_t x,
int32_t y) {
using namespace std::literals::chrono_literals;
self->request(adder, 10s, add_atom_v, x, y).then([=](int32_t result) {
aout(self) << x << " + " << y << " = " << result << std::endl;
});
}
void caf_main(actor_system& sys) {
auto worker = sys.spawn(worker_impl);
auto server = sys.spawn(server_impl, sys.spawn(worker_impl));
sys.spawn(client_impl, server, 1, 2);
}
// --(rst-promise-end)--
CAF_MAIN()
......@@ -2,10 +2,6 @@
* Illustrates semantics of request().{then|await|receive}. *
\******************************************************************************/
// This file is partially included in the manual, do not modify
// without updating the references in the *.tex files!
// Manual references: lines 20-37, 39-51, 53-64, 67-69 (MessagePassing.tex)
#include <chrono>
#include <cstdint>
#include <iostream>
......@@ -18,22 +14,38 @@ using std::vector;
using std::chrono::seconds;
using namespace caf;
// --(rst-cell-begin)--
using cell
= typed_actor<result<void>(put_atom, int32_t), result<int32_t>(get_atom)>;
= typed_actor<result<void>(put_atom, int32_t), // 'put' writes to the cell
result<int32_t>(get_atom)>; // 'get 'reads from the cell
struct cell_state {
int32_t value = 0;
static constexpr inline const char* name = "cell";
cell::pointer self;
int32_t value;
cell_state(cell::pointer ptr, int32_t val) : self(ptr), value(val) {
// nop
}
cell_state(const cell_state&) = delete;
cell_state& operator=(const cell_state&) = delete;
cell::behavior_type make_behavior() {
return {
[=](put_atom, int32_t val) { value = val; },
[=](get_atom) { return value; },
};
}
};
cell::behavior_type cell_impl(cell::stateful_pointer<cell_state> self,
int32_t x0) {
self->state.value = x0;
return {
[=](put_atom, int32_t val) { self->state.value = val; },
[=](get_atom) { return self->state.value; },
};
}
using cell_impl = cell::stateful_impl<cell_state>;
// --(rst-cell-end)--
// --(rst-testees-begin)--
void waiting_testee(event_based_actor* self, vector<cell> cells) {
for (auto& x : cells)
self->request(x, seconds(1), get_atom_v).await([=](int32_t y) {
......@@ -59,11 +71,13 @@ void blocking_testee(blocking_actor* self, vector<cell> cells) {
aout(self) << "cell #" << x.id() << " -> " << to_string(err) << endl;
});
}
// --(rst-testees-end)--
// --(rst-main-begin)--
void caf_main(actor_system& system) {
vector<cell> cells;
for (auto i = 0; i < 5; ++i)
cells.emplace_back(system.spawn(cell_impl, i * i));
for (int32_t i = 0; i < 5; ++i)
cells.emplace_back(system.spawn<cell_impl>(i * i));
scoped_actor self{system};
aout(self) << "waiting_testee" << endl;
auto x1 = self->spawn(waiting_testee, cells);
......@@ -74,5 +88,6 @@ void caf_main(actor_system& system) {
aout(self) << "blocking_testee" << endl;
system.spawn(blocking_testee, cells);
}
// --(rst-main-end)--
CAF_MAIN()
......@@ -203,6 +203,7 @@ optional<int> toint(const string& str) {
return none;
}
// --(rst-config-begin)--
class config : public actor_system_config {
public:
uint16_t port = 0;
......@@ -216,6 +217,7 @@ public:
.add(server_mode, "server-mode,s", "enable server mode");
}
};
// --(rst-config-end)--
void client_repl(actor_system& system, const config& cfg) {
// keeps track of requests and tries to reconnect on server failures
......
// Manual refs: lines 12-60 (Testing)
#define CAF_SUITE ping_pong
#include "caf/test/dsl.hpp"
......@@ -9,6 +7,7 @@
using namespace caf;
// --(rst-ping-pong-begin)--
namespace {
behavior ping(event_based_actor* self, actor pong_actor, int n) {
......@@ -58,3 +57,4 @@ CAF_TEST(three pings) {
}
CAF_TEST_FIXTURE_SCOPE_END()
// --(rst-ping-pong-end)--
......@@ -308,6 +308,7 @@ caf_add_component(
policy.select_all
policy.select_any
request_timeout
response_promise
result
save_inspector
selective_streaming
......
......@@ -32,6 +32,7 @@
#include "caf/blocking_actor.hpp"
#include "caf/byte_buffer.hpp"
#include "caf/byte_span.hpp"
#include "caf/caf_main.hpp"
#include "caf/config_option.hpp"
#include "caf/config_option_adder.hpp"
#include "caf/config_value.hpp"
......
......@@ -5,8 +5,6 @@
#include <cstdint>
#include <type_traits>
#include "caf/detail/type_traits.hpp"
#pragma once
namespace caf {
......@@ -15,31 +13,31 @@ namespace caf {
enum class byte : uint8_t {};
template <class IntegerType,
class = detail::enable_if_tt<std::is_integral<IntegerType>>>
class = std::enable_if_t<std::is_integral<IntegerType>::value>>
constexpr IntegerType to_integer(byte x) noexcept {
return static_cast<IntegerType>(x);
}
template <class IntegerType,
class E = detail::enable_if_tt<std::is_integral<IntegerType>>>
class E = std::enable_if_t<std::is_integral<IntegerType>::value>>
constexpr byte& operator<<=(byte& x, IntegerType shift) noexcept {
return x = static_cast<byte>(to_integer<uint8_t>(x) << shift);
}
template <class IntegerType,
class E = detail::enable_if_tt<std::is_integral<IntegerType>>>
class E = std::enable_if_t<std::is_integral<IntegerType>::value>>
constexpr byte operator<<(byte x, IntegerType shift) noexcept {
return static_cast<byte>(to_integer<uint8_t>(x) << shift);
}
template <class IntegerType,
class E = detail::enable_if_tt<std::is_integral<IntegerType>>>
class E = std::enable_if_t<std::is_integral<IntegerType>::value>>
constexpr byte& operator>>=(byte& x, IntegerType shift) noexcept {
return x = static_cast<byte>(to_integer<uint8_t>(x) >> shift);
}
template <class IntegerType,
class E = detail::enable_if_tt<std::is_integral<IntegerType>>>
class E = std::enable_if_t<std::is_integral<IntegerType>::value>>
constexpr byte operator>>(byte x, IntegerType shift) noexcept {
return static_cast<byte>(static_cast<unsigned char>(x) >> shift);
}
......
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
// For historic reasons, CAF_MAIN is implemented in exec_main.hpp. Eventually
// the implementation of the macro should move here.
#include "caf/exec_main.hpp"
......@@ -64,7 +64,7 @@ CAF_ADD_CONFIG_VALUE_TYPE(dictionary<config_value>);
template <class T>
constexpr bool is_config_value_type_v = is_config_value_type<T>::value;
}; // namespace caf::detail
} // namespace caf::detail
namespace caf {
......
......@@ -6,6 +6,7 @@
#include <atomic>
#include <cstdlib>
#include <new>
#include "caf/byte.hpp"
#include "caf/config.hpp"
......@@ -46,6 +47,8 @@ public:
message_data* copy() const;
static intrusive_ptr<message_data> make_uninitialized(type_id_list types);
// -- reference counting -----------------------------------------------------
/// Increases reference count by one.
......@@ -110,9 +113,53 @@ public:
init_impl(storage(), std::forward<Ts>(xs)...);
}
byte* stepwise_init(byte* pos) {
return pos;
}
template <class T, class... Ts>
byte* stepwise_init(byte* pos, T&& x, Ts&&... xs) {
using type = strip_and_convert_t<T>;
new (pos) type(std::forward<T>(x));
++constructed_elements_;
return stepwise_init(pos + padded_size_v<type>, std::forward<Ts>(xs)...);
}
byte* stepwise_init_from(byte* pos, const message& msg);
byte* stepwise_init_from(byte* pos, const message_data* other);
template <class Tuple, size_t... Is>
byte* stepwise_init_from(byte* pos, Tuple&& tup, std::index_sequence<Is...>) {
return stepwise_init(pos, std::get<Is>(std::forward<Tuple>(tup))...);
}
template <class... Ts>
byte* stepwise_init_from(byte* pos, std::tuple<Ts...>&& tup) {
return stepwise_init_from(pos, std::move(tup),
std::make_index_sequence<sizeof...(Ts)>{});
}
template <class... Ts>
byte* stepwise_init_from(byte* pos, std::tuple<Ts...>& tup) {
return stepwise_init_from(pos, tup,
std::make_index_sequence<sizeof...(Ts)>{});
}
template <class... Ts>
byte* stepwise_init_from(byte* pos, const std::tuple<Ts...>& tup) {
return stepwise_init_from(pos, tup,
std::make_index_sequence<sizeof...(Ts)>{});
}
template <class... Ts>
void init_from(Ts&&... xs) {
init_from_impl(storage(), std::forward<Ts>(xs)...);
}
private:
void init_impl(byte*) {
// nop
// End of recursion.
}
template <class T, class... Ts>
......@@ -123,6 +170,16 @@ private:
init_impl(storage + padded_size_v<type>, std::forward<Ts>(xs)...);
}
void init_from_impl(byte*) {
// End of recursion.
}
template <class T, class... Ts>
void init_from_impl(byte* pos, T&& x, Ts&&... xs) {
init_from_impl(stepwise_init_from(pos, std::forward<T>(x)),
std::forward<Ts>(xs)...);
}
mutable std::atomic<size_t> rc_;
type_id_list types_;
size_t constructed_elements_;
......
......@@ -12,8 +12,6 @@
#include "caf/detail/type_pair.hpp"
#include "caf/fwd.hpp"
#include "caf/none.hpp"
#include "caf/type_id.hpp"
#include "caf/type_id_list.hpp"
#include "caf/unit.hpp"
namespace caf::detail {
......@@ -36,21 +34,6 @@ struct strip_param<param<T>> {
using type = T;
};
template <class List>
struct to_type_id_list_helper;
template <class... Ts>
struct to_type_id_list_helper<type_list<Ts...>> {
static constexpr type_id_list get() {
return make_type_id_list<typename strip_param<Ts>::type...>();
}
};
template <class List>
constexpr type_id_list to_type_id_list() {
return to_type_id_list_helper<List>::get();
}
/// Denotes the empty list.
using empty_type_list = type_list<>;
......
......@@ -19,6 +19,7 @@
namespace caf {
// --(rst-exit-reason-begin)--
/// This error category represents fail conditions for actors.
enum class exit_reason : uint8_t {
/// Indicates that an actor finished execution without error.
......@@ -40,6 +41,7 @@ enum class exit_reason : uint8_t {
/// Indicates that an actor was killed because it became unreachable.
unreachable
};
// --(rst-exit-reason-end)--
/// @relates exit_reason
CAF_CORE_EXPORT std::string to_string(exit_reason);
......
......@@ -130,7 +130,6 @@ class string_view;
class tracing_data;
class tracing_data_factory;
class type_id_list;
class type_id_list_builder;
class uri;
class uri_builder;
class uuid;
......
......@@ -43,6 +43,17 @@ public:
message& operator=(const message&) noexcept = default;
// -- concatenation ----------------------------------------------------------
template <class... Ts>
static message concat(Ts&&... xs) {
static_assert(sizeof...(Ts) >= 2);
auto types = type_id_list::concat(types_of(xs)...);
auto ptr = detail::message_data::make_uninitialized(types);
ptr->init_from(std::forward<Ts>(xs)...);
return message{data_ptr{ptr.release(), false}};
}
// -- properties -------------------------------------------------------------
auto types() const noexcept {
......
......@@ -53,27 +53,31 @@ public:
"mixing expected<T> with regular values is not supported");
if constexpr (sizeof...(Ts) == 0
&& std::is_same<message, std::decay_t<T>>::value)
return deliver_impl(std::forward<T>(x));
deliver_impl(std::forward<T>(x));
else
return deliver_impl(
make_message(std::forward<T>(x), std::forward<Ts>(xs)...));
deliver_impl(make_message(std::forward<T>(x), std::forward<Ts>(xs)...));
}
/// Satisfies the promise by sending either an error or a non-error response
/// message.
template <class T>
void deliver(expected<T> x) {
if (x)
return deliver(std::move(*x));
return deliver(std::move(x.error()));
if (x) {
if constexpr (std::is_same<T, void>::value)
deliver();
else
deliver(std::move(*x));
} else {
deliver(std::move(x.error()));
}
}
/// Satisfies the promise by delegating to another actor.
template <message_priority P = message_priority::normal, class Handle = actor,
class... Ts>
typename response_type<typename Handle::signatures,
detail::implicit_conversions_t<
typename std::decay<Ts>::type>...>::delegated_type
delegated_response_type_t<
typename Handle::signatures,
detail::implicit_conversions_t<typename std::decay<Ts>::type>...>
delegate(const Handle& dest, Ts&&... xs) {
static_assert(sizeof...(Ts) > 0, "nothing to delegate");
using token = detail::type_list<typename detail::implicit_conversions<
......@@ -96,7 +100,13 @@ public:
/// Satisfies the promise by sending an empty message if this promise has a
/// valid message ID, i.e., `async() == false`.
void deliver(unit_t x);
void deliver();
/// Satisfies the promise by sending an empty message if this promise has a
/// valid message ID, i.e., `async() == false`.
void deliver(unit_t) {
deliver();
}
/// Returns whether this response promise replies to an asynchronous message.
bool async() const;
......
......@@ -58,11 +58,18 @@ struct response_type<detail::type_list<Out(In...), Fs...>, In...> {
using delegated_type = delegated<Out>;
};
/// Computes the response message for input `In...` from the list of message
/// passing interfaces `Fs`.
/// Computes the response message type for input `In...` from the list of
/// message passing interfaces `Fs`.
template <class Fs, class... In>
using response_type_t = typename response_type<Fs, In...>::type;
/// Computes the response message type for input `In...` from the list of
/// message passing interfaces `Fs` and returns the corresponding
/// `delegated<T>`.
template <class Fs, class... In>
using delegated_response_type_t =
typename response_type<Fs, In...>::delegated_type;
/// Unboxes `Xs` and calls `response_type`.
template <class Ts, class Xs>
struct response_type_unbox;
......
......@@ -19,6 +19,7 @@
namespace caf {
// --(rst-sec-begin)--
/// SEC stands for "System Error Code". This enum contains error codes for
/// ::actor_system and its modules.
enum class sec : uint8_t {
......@@ -159,6 +160,7 @@ enum class sec : uint8_t {
/// A key lookup failed.
no_such_key = 65,
};
// --(rst-sec-end)--
/// @relates sec
CAF_CORE_EXPORT std::string to_string(sec);
......@@ -170,8 +172,8 @@ CAF_CORE_EXPORT bool from_string(string_view, sec&);
CAF_CORE_EXPORT bool from_integer(std::underlying_type_t<sec>, sec&);
/// @relates sec
template <class Inssector>
bool inspect(Inssector& f, sec& x) {
template <class Inspector>
bool inspect(Inspector& f, sec& x) {
return default_enum_inspect(f, x);
}
......
......@@ -27,16 +27,15 @@ struct is_string_like {
template <class U>
static bool sfinae(
const U* x,
// check if `(*x)[0]` returns `const char&`
typename std::enable_if<
std::is_same<const char&, decltype((*x)[0])>::value>::type* = nullptr,
// check if `x->data()` returns const char*
std::enable_if_t<
std::is_same<const char*, decltype(x->data())>::value>* = nullptr,
// check if `x->size()` returns an integer
typename std::enable_if<
std::is_integral<decltype(x->size())>::value>::type* = nullptr,
std::enable_if_t<std::is_integral<decltype(x->size())>::value>* = nullptr,
// check if `x->find('?', 0)` is well-formed and returns an integer
// (distinguishes vectors from strings)
typename std::enable_if<
std::is_integral<decltype(x->find('?', 0))>::value>::type* = nullptr);
std::enable_if_t<
std::is_integral<decltype(x->find('?', 0))>::value>* = nullptr);
// SFINAE fallback.
static void sfinae(void*);
......@@ -105,15 +104,9 @@ public:
template <class T, class = typename std::enable_if<
detail::is_string_like<T>::value>::type>
string_view(const T& str) noexcept {
auto len = str.size();
if (len == 0) {
data_ = nullptr;
size_ = 0;
} else {
data_ = &(str[0]);
size_ = str.size();
}
constexpr string_view(const T& str) noexcept
: data_(str.data()), size_(str.size()) {
// nop
}
string_view& operator=(const string_view&) noexcept = default;
......
......@@ -11,6 +11,8 @@
#include "caf/detail/comparable.hpp"
#include "caf/detail/core_export.hpp"
#include "caf/detail/implicit_conversions.hpp"
#include "caf/span.hpp"
#include "caf/type_id.hpp"
namespace caf {
......@@ -78,6 +80,17 @@ public:
/// type-erased tuple for the element types stored in this list.
size_t data_size() const noexcept;
/// Concatenates all `lists` into a single type ID list.
static type_id_list concat(span<type_id_list> lists);
/// Concatenates all `lists` into a single type ID list.
template <class... Ts>
static type_id_list
concat(type_id_list list1, type_id_list list2, Ts... lists) {
type_id_list arr[] = {list1, list2, lists...};
return concat(arr);
}
private:
pointer data_;
};
......@@ -99,6 +112,14 @@ constexpr type_id_list make_type_id_list() {
/// @relates type_id_list
CAF_CORE_EXPORT std::string to_string(type_id_list xs);
/// @relates type_id_list
CAF_CORE_EXPORT type_id_list types_of(const message& msg);
template <class... Ts>
type_id_list types_of(const std::tuple<Ts...>&) {
return make_type_id_list<detail::strip_and_convert_t<Ts>...>();
}
} // namespace caf
namespace caf::detail {
......@@ -118,4 +139,19 @@ type_id_list make_argument_type_id_list() {
return argument_type_id_list_factory<F>::make();
}
template <class List>
struct to_type_id_list_helper;
template <class... Ts>
struct to_type_id_list_helper<type_list<Ts...>> {
static constexpr type_id_list get() {
return make_type_id_list<typename strip_param<Ts>::type...>();
}
};
template <class List>
constexpr type_id_list to_type_id_list() {
return to_type_id_list_helper<List>::get();
}
} // namespace caf::detail
......@@ -54,6 +54,9 @@ public:
// tell actor_cast which semantic this type uses
static constexpr bool has_weak_ptr_semantics = false;
/// Stores the template parameter pack.
using signatures = detail::type_list<Sigs...>;
/// Creates a new `typed_actor` type by extending this one with `Es...`.
template <class... Es>
using extend = typed_actor<Sigs..., Es...>;
......@@ -68,15 +71,31 @@ public:
/// for their behavior stack.
using behavior_type = typed_behavior<Sigs...>;
/// The default, event-based type for implementing this messaging interface.
using impl = typed_event_based_actor<Sigs...>;
/// Identifies pointers to instances of this kind of actor.
using pointer = typed_event_based_actor<Sigs...>*;
using pointer = impl*;
/// Allows a view to an actor implementing this messaging interface without
/// knowledge of the actual type..
/// A view to an actor that implements this messaging interface without
/// knowledge of the actual type.
using pointer_view = typed_actor_pointer<Sigs...>;
/// Identifies the base class for this kind of actor.
using base = typed_event_based_actor<Sigs...>;
/// A class type suitable as base type class-based implementations.
using base = impl;
/// The default, event-based type for implementing this messaging interface as
/// a stateful actor.
template <class State>
using stateful_impl = stateful_actor<State, impl>;
template <class State>
using stateful_base [[deprecated("use stateful_impl instead")]]
= stateful_actor<State, base>;
/// Convenience alias for `stateful_impl<State>*`.
template <class State>
using stateful_pointer = stateful_impl<State>*;
/// Identifies pointers to brokers implementing this interface.
using broker_pointer = io::typed_broker<Sigs...>*;
......@@ -84,17 +103,6 @@ public:
/// Identifies the base class of brokers implementing this interface.
using broker_base = io::typed_broker<Sigs...>;
/// Stores the template parameter pack.
using signatures = detail::type_list<Sigs...>;
/// Identifies the base class for this kind of actor with actor.
template <class State>
using stateful_base = stateful_actor<State, base>;
/// Identifies the base class for this kind of actor with actor.
template <class State>
using stateful_pointer = stateful_actor<State, base>*;
/// Identifies the broker_base class for this kind of actor with actor.
template <class State>
using stateful_broker_base = stateful_actor<State, broker_base>;
......
......@@ -4,9 +4,11 @@
#pragma once
#include "caf/response_promise.hpp"
#include <type_traits>
#include "caf/detail/type_list.hpp"
#include "caf/make_message.hpp"
#include "caf/response_promise.hpp"
namespace caf {
......@@ -48,42 +50,38 @@ public:
}
/// Satisfies the promise by sending a non-error response message.
template <class U, class... Us>
typename std::enable_if<(sizeof...(Us) > 0)
|| !std::is_convertible<U, error>::value,
typed_response_promise>::type
deliver(U&& x, Us&&... xs) {
static_assert(
std::is_same<detail::type_list<Ts...>,
detail::type_list<typename std::decay<U>::type,
typename std::decay<Us>::type...>>::value,
"typed_response_promise: message type mismatched");
promise_.deliver(std::forward<U>(x), std::forward<Us>(xs)...);
return *this;
template <class... Us>
std::enable_if_t<(std::is_constructible<Ts, Us>::value && ...)>
deliver(Us... xs) {
promise_.deliver(make_message(Ts{std::forward<Us>(xs)}...));
}
/// Satisfies the promise by sending an empty response message.
template <class L = detail::type_list<Ts...>>
std::enable_if_t<std::is_same<L, detail::type_list<void>>::value> deliver() {
promise_.deliver();
}
/// Satisfies the promise by sending an error response message.
/// For non-requests, nothing is done.
void deliver(error x) {
promise_.deliver(std::move(x));
}
/// Satisfies the promise by sending either an error or a non-error response
/// message.
template <class T>
void deliver(expected<T> x) {
if (x)
return deliver(std::move(*x));
return deliver(std::move(x.error()));
std::enable_if_t<
std::is_same<detail::type_list<T>, detail::type_list<Ts...>>::value>
deliver(expected<T> x) {
promise_.deliver(std::move(x));
}
/// Satisfies the promise by delegating to another actor.
template <message_priority P = message_priority::normal, class Handle = actor,
class... Us>
typed_response_promise delegate(const Handle& dest, Us&&... xs) {
promise_.template delegate<P>(dest, std::forward<Us>(xs)...);
return *this;
}
/// Satisfies the promise by sending an error response message.
/// For non-requests, nothing is done.
typed_response_promise deliver(error x) {
promise_.deliver(std::move(x));
return *this;
auto delegate(const Handle& dest, Us&&... xs) {
return promise_.template delegate<P>(dest, std::forward<Us>(xs)...);
}
/// Returns whether this response promise replies to an asynchronous message.
......
......@@ -220,7 +220,7 @@ expected<bool> config_value::to_boolean() const {
using result_type = expected<bool>;
auto f = detail::make_overload(
no_conversions<bool, none_t, integer, real, timespan, uri,
config_value::list, config_value::dictionary>(),
config_value::list>(),
[](boolean x) { return result_type{x}; },
[](const std::string& x) {
if (x == "true") {
......@@ -233,6 +233,31 @@ expected<bool> config_value::to_boolean() const {
msg += " to a boolean";
return result_type{make_error(sec::conversion_failed, std::move(msg))};
}
},
[](const dictionary& x) {
if (auto i = x.find("@type");
i != x.end() && holds_alternative<std::string>(i->second)) {
const auto& tn = get<std::string>(i->second);
if (tn == type_name_v<bool>) {
if (auto j = x.find("value"); j != x.end()) {
return j->second.to_boolean();
} else {
std::string msg = "missing value for object of type ";
msg += tn;
return result_type{
make_error(sec::conversion_failed, std::move(msg))};
}
} else {
std::string msg = "cannot convert ";
msg += tn;
msg += " to a boolean";
return result_type{
make_error(sec::conversion_failed, std::move(msg))};
}
} else {
std::string msg = "cannot convert a dictionary to a boolean";
return result_type{make_error(sec::conversion_failed, std::move(msg))};
}
});
return visit(f, data_);
}
......@@ -240,8 +265,7 @@ expected<bool> config_value::to_boolean() const {
expected<config_value::integer> config_value::to_integer() const {
using result_type = expected<integer>;
auto f = detail::make_overload(
no_conversions<integer, none_t, bool, timespan, uri, config_value::list,
config_value::dictionary>(),
no_conversions<integer, none_t, bool, timespan, uri, config_value::list>(),
[](integer x) { return result_type{x}; },
[](real x) {
using limits = std::numeric_limits<config_value::integer>;
......@@ -269,6 +293,37 @@ expected<config_value::integer> config_value::to_integer() const {
detail::print_escaped(msg, x);
msg += " to an integer";
return result_type{make_error(sec::conversion_failed, std::move(msg))};
},
[](const dictionary& x) {
if (auto i = x.find("@type");
i != x.end() && holds_alternative<std::string>(i->second)) {
const auto& tn = get<std::string>(i->second);
string_view valid_types[]
= {type_name_v<int16_t>, type_name_v<int32_t>,
type_name_v<int64_t>, type_name_v<int8_t>,
type_name_v<uint16_t>, type_name_v<uint32_t>,
type_name_v<uint64_t>, type_name_v<uint8_t>};
auto eq = [&tn](string_view x) { return x == tn; };
if (std::any_of(std::begin(valid_types), std::end(valid_types), eq)) {
if (auto j = x.find("value"); j != x.end()) {
return j->second.to_integer();
} else {
std::string msg = "missing value for object of type ";
msg += tn;
return result_type{
make_error(sec::conversion_failed, std::move(msg))};
}
} else {
std::string msg = "cannot convert ";
msg += tn;
msg += " to an integer";
return result_type{
make_error(sec::conversion_failed, std::move(msg))};
}
} else {
std::string msg = "cannot convert a dictionary to an integer";
return result_type{make_error(sec::conversion_failed, std::move(msg))};
}
});
return visit(f, data_);
}
......@@ -276,8 +331,7 @@ expected<config_value::integer> config_value::to_integer() const {
expected<config_value::real> config_value::to_real() const {
using result_type = expected<real>;
auto f = detail::make_overload(
no_conversions<real, none_t, bool, timespan, uri, config_value::list,
config_value::dictionary>(),
no_conversions<real, none_t, bool, timespan, uri, config_value::list>(),
[](integer x) {
// This cast may lose precision on the value. We could try and check that,
// but refusing to convert on loss of precision could also be unexpected
......@@ -293,6 +347,35 @@ expected<config_value::real> config_value::to_real() const {
detail::print_escaped(msg, x);
msg += " to a floating point number";
return result_type{make_error(sec::conversion_failed, std::move(msg))};
},
[](const dictionary& x) {
if (auto i = x.find("@type");
i != x.end() && holds_alternative<std::string>(i->second)) {
const auto& tn = get<std::string>(i->second);
string_view valid_types[] = {type_name_v<float>, type_name_v<double>,
type_name_v<long double>};
auto eq = [&tn](string_view x) { return x == tn; };
if (std::any_of(std::begin(valid_types), std::end(valid_types), eq)) {
if (auto j = x.find("value"); j != x.end()) {
return j->second.to_real();
} else {
std::string msg = "missing value for object of type ";
msg += tn;
return result_type{
make_error(sec::conversion_failed, std::move(msg))};
}
} else {
std::string msg = "cannot convert ";
msg += tn;
msg += " to a floating point number";
return result_type{
make_error(sec::conversion_failed, std::move(msg))};
}
} else {
std::string msg
= "cannot convert a dictionary to a floating point number";
return result_type{make_error(sec::conversion_failed, std::move(msg))};
}
});
return visit(f, data_);
}
......
......@@ -381,7 +381,7 @@ bool config_value_reader::begin_associative_array(size_t& size) {
st_.top() = associative_array{dict->begin(), dict->end()};
return true;
}
std::string msg = "expected a dictionary, got a ";
std::string msg = "begin_associative_array: expected a dictionary, got a ";
msg += top->type_name();
emplace_error(sec::conversion_failed, std::move(msg));
return false;
......@@ -419,13 +419,10 @@ bool pull(config_value_reader& reader, T& x) {
reader.pop();
return true;
} else {
std::string msg = "expected a dictionary, got a ";
msg += to_string(type_name_v<T>);
reader.emplace_error(sec::conversion_failed, std::move(msg));
reader.set_error(std::move(val.error()));
return false;
}
}
if (holds_alternative<config_value_reader::sequence>(top)) {
} else if (holds_alternative<config_value_reader::sequence>(top)) {
auto& seq = get<config_value_reader::sequence>(top);
if (seq.at_end()) {
reader.emplace_error(sec::runtime_error, "value: sequence out of bounds");
......@@ -437,13 +434,10 @@ bool pull(config_value_reader& reader, T& x) {
seq.advance();
return true;
} else {
std::string msg = "expected a dictionary, got a ";
msg += to_string(type_name_v<T>);
reader.emplace_error(sec::conversion_failed, std::move(msg));
reader.set_error(std::move(val.error()));
return false;
}
}
if (holds_alternative<config_value_reader::key_ptr>(top)) {
} else if (holds_alternative<config_value_reader::key_ptr>(top)) {
auto ptr = get<config_value_reader::key_ptr>(top);
if constexpr (std::is_same<std::string, T>::value) {
x = *ptr;
......@@ -453,8 +447,9 @@ bool pull(config_value_reader& reader, T& x) {
if (auto err = detail::parse(*ptr, x)) {
reader.set_error(std::move(err));
return false;
} else {
return true;
}
return true;
}
}
reader.emplace_error(sec::conversion_failed,
......
......@@ -10,6 +10,7 @@
#include "caf/detail/meta_object.hpp"
#include "caf/error.hpp"
#include "caf/error_code.hpp"
#include "caf/message.hpp"
#include "caf/raise_error.hpp"
#include "caf/sec.hpp"
#include "caf/span.hpp"
......@@ -48,18 +49,30 @@ message_data* message_data::copy() const {
auto vptr = malloc(total_size);
if (vptr == nullptr)
CAF_RAISE_ERROR(std::bad_alloc, "bad_alloc");
auto ptr = new (vptr) message_data(types_);
intrusive_ptr<message_data> ptr{new (vptr) message_data(types_), false};
auto src = storage();
auto dst = ptr->storage();
for (auto id : types_) {
auto& meta = gmos[id];
// TODO: exception handling.
meta.copy_construct(dst, src);
++ptr->constructed_elements_;
src += meta.padded_size;
dst += meta.padded_size;
}
return ptr;
return ptr.release();
}
intrusive_ptr<message_data>
message_data::make_uninitialized(type_id_list types) {
auto gmos = global_meta_objects();
size_t storage_size = 0;
for (auto id : types)
storage_size += gmos[id].padded_size;
auto total_size = sizeof(message_data) + storage_size;
auto vptr = malloc(total_size);
if (vptr == nullptr)
CAF_RAISE_ERROR(std::bad_alloc, "bad_alloc");
return {new (vptr) message_data(types), false};
}
byte* message_data::at(size_t index) noexcept {
......@@ -82,4 +95,23 @@ const byte* message_data::at(size_t index) const noexcept {
return ptr;
}
byte* message_data::stepwise_init_from(byte* pos, const message& msg) {
return stepwise_init_from(pos, msg.cptr());
}
byte* message_data::stepwise_init_from(byte* pos, const message_data* other) {
CAF_ASSERT(other != nullptr);
CAF_ASSERT(other != this);
auto gmos = global_meta_objects();
auto src = other->storage();
for (auto id : other->types()) {
auto& meta = gmos[id];
meta.copy_construct(pos, src);
++constructed_elements_;
src += meta.padded_size;
pos += meta.padded_size;
}
return pos;
}
} // namespace caf::detail
......@@ -46,7 +46,7 @@ void response_promise::deliver(error x) {
deliver_impl(make_message(std::move(x)));
}
void response_promise::deliver(unit_t) {
void response_promise::deliver() {
deliver_impl(make_message());
}
......@@ -75,6 +75,11 @@ void response_promise::deliver_impl(message msg) {
CAF_LOG_DEBUG("drop response: invalid promise");
return;
}
if (msg.empty() && id_.is_async()) {
CAF_LOG_DEBUG("drop response: empty response to asynchronous input");
self_.reset();
return;
}
auto dptr = self_dptr();
if (!stages_.empty()) {
auto next = std::move(stages_.back());
......
......@@ -5,6 +5,8 @@
#include "caf/type_id_list.hpp"
#include "caf/detail/meta_object.hpp"
#include "caf/detail/type_id_list_builder.hpp"
#include "caf/message.hpp"
namespace caf {
......@@ -35,4 +37,20 @@ std::string to_string(type_id_list xs) {
return result;
}
type_id_list type_id_list::concat(span<type_id_list> lists) {
auto total_size = size_t{0};
for (auto ls : lists)
total_size += ls.size();
detail::type_id_list_builder builder;
builder.reserve(total_size);
for (auto ls : lists)
for (auto id : ls)
builder.push_back(id);
return builder.move_to_list();
}
type_id_list types_of(const message& msg) {
return msg.types();
}
} // namespace caf
......@@ -97,6 +97,16 @@ SCENARIO("get_as can convert config values to boolean") {
}
}
}
GIVEN("a config value with type annotation 'bool' and the value \"true\"") {
config_value x;
x.as_dictionary().emplace("@type", "bool");
x.as_dictionary().emplace("value", "true");
WHEN("using get_as with bool") {
THEN("conversion succeeds") {
CHECK_EQ(get_as<bool>(x), true);
}
}
}
GIVEN("non-boolean config_values") {
WHEN("using get_as with bool") {
THEN("conversion fails") {
......@@ -161,6 +171,23 @@ SCENARIO("get_as can convert config values to integers") {
}
}
}
GIVEN("a config value x with type annotation 'int32_t' and the value 50") {
config_value x;
x.as_dictionary().emplace("@type", "int32_t");
x.as_dictionary().emplace("value", 50);
WHEN("using get_as with integer types") {
THEN("CAF parses the integer and performs a bound check") {
CHECK_EQ(get_as<uint64_t>(x), 50u);
CHECK_EQ(get_as<int64_t>(x), 50);
CHECK_EQ(get_as<uint32_t>(x), 50u);
CHECK_EQ(get_as<int32_t>(x), 50);
CHECK_EQ(get_as<uint16_t>(x), 50u);
CHECK_EQ(get_as<int16_t>(x), 50);
CHECK_EQ(get_as<uint8_t>(x), 50u);
CHECK_EQ(get_as<int8_t>(x), 50);
}
}
}
GIVEN("a config value x with value 50.0") {
auto x = config_value{50.0};
WHEN("using get_as with integer types") {
......@@ -278,6 +305,18 @@ SCENARIO("get_as can convert config values to floating point numbers") {
}
}
}
GIVEN("a config value x with type annotation 'float' and the value 50") {
config_value x;
x.as_dictionary().emplace("@type", "float");
x.as_dictionary().emplace("value", 123.0);
WHEN("using get_as with floating point types") {
THEN("CAF parses the value and performs a bound check") {
CHECK_EQ(get_as<long double>(x), 123.0);
CHECK_EQ(get_as<double>(x), 123.0);
CHECK_EQ(get_as<float>(x), 123.f);
}
}
}
GIVEN("config_values of null, URI, boolean, list or dictionary") {
WHEN("using get_as with integer types") {
THEN("conversion fails") {
......
......@@ -121,3 +121,15 @@ CAF_TEST(match_elements exposes element types) {
CAF_CHECK((msg.match_element<int64_t>(2)));
CAF_CHECK((msg.match_elements<put_atom, string, int64_t>()));
}
CAF_TEST(messages are concatenable) {
using std::make_tuple;
CHECK(message::concat(make_tuple(int16_t{1}), make_tuple(uint8_t{2}))
.matches(int16_t{1}, uint8_t{2}));
CHECK(message::concat(make_message(int16_t{1}), make_message(uint8_t{2}))
.matches(int16_t{1}, uint8_t{2}));
CHECK(message::concat(make_message(int16_t{1}), make_tuple(uint8_t{2}))
.matches(int16_t{1}, uint8_t{2}));
CHECK(message::concat(make_tuple(int16_t{1}), make_message(uint8_t{2}))
.matches(int16_t{1}, uint8_t{2}));
}
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#define CAF_SUITE response_promise
#include "caf/response_promise.hpp"
#include "core-test.hpp"
using namespace caf;
namespace {
behavior adder() {
return {
[](int x, int y) { return x + y; },
[](ok_atom) {},
};
}
behavior delegator(event_based_actor* self, actor worker) {
return {
[=](int x, int y) {
auto promise = self->make_response_promise();
return promise.delegate(worker, x, y);
},
[=](ok_atom) {
auto promise = self->make_response_promise();
return promise.delegate(worker, ok_atom_v);
},
};
}
behavior requester_v1(event_based_actor* self, actor worker) {
return {
[=](int x, int y) {
auto rp = self->make_response_promise();
self->request(worker, infinite, x, y)
.then(
[rp](int result) mutable {
CHECK(rp.pending());
rp.deliver(result);
},
[rp](error err) mutable {
CHECK(rp.pending());
rp.deliver(std::move(err));
});
return rp;
},
[=](ok_atom) {
auto rp = self->make_response_promise();
self->request(worker, infinite, ok_atom_v)
.then(
[rp]() mutable {
CHECK(rp.pending());
rp.deliver();
},
[rp](error err) mutable {
CHECK(rp.pending());
rp.deliver(std::move(err));
});
return rp;
},
};
}
behavior requester_v2(event_based_actor* self, actor worker) {
return {
[=](int x, int y) {
auto rp = self->make_response_promise();
auto deliver = [rp](expected<int> x) mutable {
CHECK(rp.pending());
rp.deliver(std::move(x));
};
self->request(worker, infinite, x, y)
.then([deliver](int result) mutable { deliver(result); },
[deliver](error err) mutable { deliver(std::move(err)); });
return rp;
},
[=](ok_atom) {
auto rp = self->make_response_promise();
auto deliver = [rp](expected<void> x) mutable {
CHECK(rp.pending());
rp.deliver(std::move(x));
};
self->request(worker, infinite, ok_atom_v)
.then([deliver]() mutable { deliver({}); },
[deliver](error err) mutable { deliver(std::move(err)); });
return rp;
},
};
}
} // namespace
CAF_TEST_FIXTURE_SCOPE(response_promise_tests, test_coordinator_fixture<>)
SCENARIO("response promises allow delaying of response messages") {
auto adder_hdl = sys.spawn(adder);
std::map<std::string, actor> impls;
impls["with a value or an error"] = sys.spawn(requester_v1, adder_hdl);
impls["with an expected<T>"] = sys.spawn(requester_v2, adder_hdl);
for (auto& [desc, hdl] : impls) {
GIVEN("a dispatcher that calls deliver " << desc << " on its promise") {
WHEN("sending a request with two integers to the dispatcher") {
inject((int, int), from(self).to(hdl).with(3, 4));
THEN("clients receive the response from the dispatcher") {
expect((int, int), from(hdl).to(adder_hdl).with(3, 4));
expect((int), from(adder_hdl).to(hdl).with(7));
expect((int), from(hdl).to(self).with(7));
}
}
WHEN("sending ok_atom to the dispatcher synchronously") {
auto res = self->request(hdl, infinite, ok_atom_v);
auto fetch_result = [&] {
message result;
res.receive([] {}, // void result
[&](const error& reason) {
result = make_message(reason);
});
return result;
};
THEN("clients receive an empty response from the dispatcher") {
expect((ok_atom), from(self).to(hdl));
expect((ok_atom), from(hdl).to(adder_hdl));
expect((void), from(adder_hdl).to(hdl));
CHECK(fetch_result().empty());
}
}
WHEN("sending ok_atom to the dispatcher asynchronously") {
THEN("clients receive no response from the dispatcher") {
inject((ok_atom), from(self).to(hdl).with(ok_atom_v));
expect((ok_atom), from(hdl).to(adder_hdl));
expect((void), from(adder_hdl).to(hdl));
CHECK(self->mailbox().empty());
}
}
}
}
}
SCENARIO("response promises allow delegation") {
GIVEN("a dispatcher that calls delegate on its promise") {
auto adder_hdl = sys.spawn(adder);
auto hdl = sys.spawn(delegator, adder_hdl);
WHEN("sending a request to the dispatcher") {
inject((int, int), from(self).to(hdl).with(3, 4));
THEN("clients receive the response from the adder") {
expect((int, int), from(self).to(adder_hdl).with(3, 4));
expect((int), from(adder_hdl).to(self).with(7));
}
}
}
}
CAF_TEST_FIXTURE_SCOPE_END()
......@@ -83,3 +83,35 @@ CAF_TEST(type ID lists are convertible to strings) {
auto xs = make_type_id_list<uint16_t, bool, float, long double>();
CAF_CHECK_EQUAL(to_string(xs), "[uint16_t, bool, float, ldouble]");
}
CAF_TEST(type ID lists are concatenable) {
// 1 + 0
CHECK_EQ((make_type_id_list<int8_t>()),
type_id_list::concat(make_type_id_list<int8_t>(),
make_type_id_list<>()));
CHECK_EQ((make_type_id_list<int8_t>()),
type_id_list::concat(make_type_id_list<>(),
make_type_id_list<int8_t>()));
// 1 + 1
CHECK_EQ((make_type_id_list<int8_t, int16_t>()),
type_id_list::concat(make_type_id_list<int8_t>(),
make_type_id_list<int16_t>()));
// 2 + 0
CHECK_EQ((make_type_id_list<int8_t, int16_t>()),
type_id_list::concat(make_type_id_list<int8_t, int16_t>(),
make_type_id_list<>()));
CHECK_EQ((make_type_id_list<int8_t, int16_t>()),
type_id_list::concat(make_type_id_list<>(),
make_type_id_list<int8_t, int16_t>()));
// 2 + 1
CHECK_EQ((make_type_id_list<int8_t, int16_t, int32_t>()),
type_id_list::concat(make_type_id_list<int8_t, int16_t>(),
make_type_id_list<int32_t>()));
CHECK_EQ((make_type_id_list<int8_t, int16_t, int32_t>()),
type_id_list::concat(make_type_id_list<int8_t>(),
make_type_id_list<int16_t, int32_t>()));
// 2 + 2
CHECK_EQ((make_type_id_list<int8_t, int16_t, int32_t, int64_t>()),
type_id_list::concat(make_type_id_list<int8_t, int16_t>(),
make_type_id_list<int32_t, int64_t>()));
}
This diff is collapsed.
......@@ -69,8 +69,8 @@ CAF_IO_EXPORT bool from_string(string_view, message_type&);
CAF_IO_EXPORT bool from_integer(std::underlying_type_t<message_type>,
message_type&);
template <class Inssector>
bool inspect(Inssector& f, message_type& x) {
template <class Inspector>
bool inspect(Inspector& f, message_type& x) {
return default_enum_inspect(f, x);
}
......
......@@ -391,7 +391,7 @@ strong_actor_ptr middleman::remote_lookup(std::string name,
make_message(registry_lookup_atom_v, std::move(name)));
self->receive(
[&](strong_actor_ptr& addr) { result = std::move(addr); },
others >> [](message& msg) -> skippable_result {
others >> []([[maybe_unused]] message& msg) -> skippable_result {
CAF_LOG_ERROR(
"middleman received unexpected remote_lookup result:" << msg);
return message{};
......
......@@ -250,14 +250,15 @@ messaging interface for a simple calculator.
.. literalinclude:: /examples/message_passing/calculator.cpp
:language: C++
:lines: 17-18
:start-after: --(rst-calculator-actor-begin)--
:end-before: --(rst-calculator-actor-end)--
It is not required to create a type alias such as ``calculator_actor``,
but it makes dealing with statically typed actors much easier. Also, a central
alias definition eases refactoring later on.
Interfaces have set semantics. This means the following two type aliases
``i1`` and ``i2`` are equal:
``i1`` and ``i2`` are considered equal by CAF:
.. code-block:: C++
......@@ -300,13 +301,15 @@ parameter. For example, the following functions and classes represent actors.
.. literalinclude:: /examples/message_passing/calculator.cpp
:language: C++
:lines: 21-26
:start-after: --(rst-prototypes-begin)--
:end-before: --(rst-prototypes-end)--
Spawning an actor for each implementation is illustrated below.
.. literalinclude:: /examples/message_passing/calculator.cpp
:language: C++
:lines: 123-128
:start-after: --(rst-spawn-begin)--
:end-before: --(rst-spawn-end)--
Additional arguments to ``spawn`` are passed to the constructor of a
class or used as additional function arguments, respectively. In the example
......@@ -344,7 +347,8 @@ dynamically typed).
.. literalinclude:: /examples/message_passing/calculator.cpp
:language: C++
:lines: 28-56
:start-after: --(rst-function-based-begin)--
:end-before: --(rst-function-based-end)--
.. _class-based:
......@@ -365,6 +369,14 @@ simple management of state via member variables. However, composing states via
inheritance can get quite tedious. For dynamically typed actors, composing
states is particularly hard, because the compiler cannot provide much help.
The following three classes implement the prototypes shown in spawn_ by
delegating to the function-based implementations we have seen before:
.. literalinclude:: /examples/message_passing/calculator.cpp
:language: C++
:start-after: --(rst-class-based-begin)--
:end-before: --(rst-class-based-end)--
.. _stateful-actor:
Stateful Actors
......@@ -405,7 +417,8 @@ printing a custom string on exit.
.. literalinclude:: /examples/broker/simple_broker.cpp
:language: C++
:lines: 42-47
:start-after: --(rst-attach-begin)--
:end-before: --(rst-attach-end)--
It is possible to attach code to remote actors. However, the cleanup code will
run on the local machine.
......@@ -461,7 +474,7 @@ before the optional timeout, as shown in the example below.
[&](const exit_msg& x) {
// ...
},
others >> [](message_view& x) -> result<message> {
others >> [](message& x) -> skippable_result {
// report unexpected message back to client
return sec::unexpected_message;
}
......
......@@ -135,7 +135,8 @@ adds three options to the ``global`` category.
.. literalinclude:: /examples/remoting/distributed_calculator.cpp
:language: C++
:lines: 206-218
:begin-after: --(rst-config-begin)--
:end-before: --(rst-config-end)--
We create a new ``global`` category in ``custom_options_``. Each following call
to ``add`` then appends individual options to the category. The first argument
......
......@@ -5,9 +5,7 @@ Errors
Errors in CAF have a code and a category, similar to ``std::error_code`` and
``std::error_condition``. Unlike its counterparts from the C++ standard library,
``error`` is plattform-neutral and serializable. Instead of using category
singletons, CAF stores categories as atoms (see :ref:`atom`). Errors can also
include a message to provide additional context information.
``error`` is plattform-neutral and serializable.
Class Interface
---------------
......@@ -15,19 +13,17 @@ Class Interface
+-----------------------------------------+--------------------------------------------------------------------+
| **Constructors** | |
+-----------------------------------------+--------------------------------------------------------------------+
| ``(Enum x)`` | Construct error by calling ``make_error(x)`` |
| ``(Enum code)`` | Constructs an error with given error code. |
+-----------------------------------------+--------------------------------------------------------------------+
| ``(uint8_t x, atom_value y)`` | Construct error with code ``x`` and category ``y`` |
+-----------------------------------------+--------------------------------------------------------------------+
| ``(uint8_t x, atom_value y, message z)``| Construct error with code ``x``, category ``y``, and context ``z`` |
| ``(Enum code, messag context)`` | Constructs an error with given error code and additional context. |
+-----------------------------------------+--------------------------------------------------------------------+
| | |
+-----------------------------------------+--------------------------------------------------------------------+
| **Observers** | |
+-----------------------------------------+--------------------------------------------------------------------+
| ``uint8_t code()`` | Returns the error code |
| ``uint8_t code()`` | Returns the error code as 8-bit integer. |
+-----------------------------------------+--------------------------------------------------------------------+
| ``atom_value category()`` | Returns the error category |
| ``type_id_t category()`` | Returns the type ID of the Enum type used to construct this error. |
+-----------------------------------------+--------------------------------------------------------------------+
| ``message context()`` | Returns additional context information |
+-----------------------------------------+--------------------------------------------------------------------+
......@@ -39,43 +35,52 @@ Class Interface
Add Custom Error Categories
---------------------------
Adding custom error categories requires three steps: (1) declare an enum class
of type ``uint8_t`` with the first value starting at 1, (2) specialize
``error_category`` to give your type a custom ID (value 0-99 are
reserved by CAF), and (3) add your error category to the actor system config.
The following example adds custom error codes for math errors.
Adding custom error categories requires these steps:
* Declare an enum class of type ``uint8_t`` with error codes starting at 1. CAF
always interprets the value 0 as *no error*.
* Assign a type ID to your enum type.
* Specialize ``caf::is_error_code_enum`` for your enum type. For this step, CAF
offers the macro ``CAF_ERROR_CODE_ENUM`` to generate the boilerplate code
necessary.
The following example illustrates all these steps for a custom error code enum
called ``math_error``.
.. literalinclude:: /examples/message_passing/divider.cpp
:language: C++
:lines: 17-47
:start-after: --(rst-math-error-begin)--
:end-before: --(rst-math-error-end)--
.. _sec:
System Error Codes
------------------
Default Error Codes
-------------------
System Error Codes (SECs) use the error category ``"system"``. They
represent errors in the actor system or one of its modules and are defined as
follows.
The enum type ``sec`` (for System Error Code) provides many error codes for
common failures in actor systems:
.. literalinclude:: /libcaf_core/caf/sec.hpp
:language: C++
:lines: 32-117
:start-after: --(rst-sec-begin)--
:end-before: --(rst-sec-end)--
.. _exit-reason:
Default Exit Reasons
--------------------
CAF uses the error category ``"exit"`` for default exit reasons. These errors
are usually fail states set by the actor system itself. The two exceptions are
A special kind of error codes are exit reasons of actors. These errors are
usually fail states set by the actor system itself. The two exceptions are
``exit_reason::user_shutdown`` and ``exit_reason::kill``. The former is used in
CAF to signalize orderly, user-requested shutdown and can be used by programmers
in the same way. The latter terminates an actor unconditionally when used in
``send_exit``, even if the default handler for exit messages (see
:ref:`exit-message`) is overridden.
``send_exit``, even for actors that override the default handler (see
:ref:`exit-message`).
.. literalinclude:: /libcaf_core/caf/exit_reason.hpp
:language: C++
:lines: 29-49
:start-after: --(rst-exit-reason-begin)--
:end-before: --(rst-exit-reason-end)--
......@@ -36,19 +36,5 @@ generation, CAF also offers ``message_builder``:
What Debugging Tools Exist?
---------------------------
The ``scripts/`` and ``tools/`` directories contain some useful tools to aid in
development and debugging.
``scripts/atom.py`` converts integer atom values back into strings.
``scripts/demystify.py`` replaces cryptic ``typed_mpi<...>``
templates with ``replies_to<...>::with<...>`` and
``atom_constant<...>`` with a human-readable representation of the
actual atom.
``scripts/caf-prof`` is an R script that generates plots from CAF
profiler output.
``caf-vec`` is a (highly) experimental tool that annotates CAF logs
with vector timestamps. It gives you happens-before relations and a nice
visualization via `ShiViz <https://bestchai.bitbucket.io/shiviz/>`_.
The ``scripts/`` directory contains some useful tools to aid in analyzing CAF
log output.
......@@ -10,10 +10,8 @@ name, joining, and leaving.
.. code-block:: C++
std::string module = "local";
std::string id = "foo";
auto expected_grp = system.groups().get(module, id);
if (! expected_grp) {
auto expected_grp = system.groups().get("local", "foo");
if (!expected_grp) {
std::cerr << "*** cannot load group: " << to_string(expected_grp.error())
<< std::endl;
return;
......
......@@ -85,10 +85,9 @@ This policy models split/join or scatter/gather work flows, where a work item
is split into as many tasks as workers are available and then the individuals
results are joined together before sending the full result back to the client.
The join function is responsible for ``glueing'' all result messages together
to create a single result. The function is called with the result object
(initialed using ``init``) and the current result messages from a
worker.
The join function is responsible for "glueing" all result messages together to
create a single result. The function is called with the result object (initialed
using ``init``) and the current result messages from a worker.
The first argument of a split function is a mapping from actors (workers) to
tasks (messages). The second argument is the input message. The default split
......
......@@ -17,9 +17,9 @@ change its behavior when not receiving message after a certain amount of time.
.. code-block:: C++
message_handler x1{
[](int i) { /*...*/ },
[](int32_t i) { /*...*/ },
[](double db) { /*...*/ },
[](int a, int b, int c) { /*...*/ }
[](int32_t a, int32_t b, int32_t c) { /*...*/ }
};
In our first example, ``x1`` models a behavior accepting messages that consist
......@@ -70,48 +70,33 @@ introduced an approach to use non-numerical constants, so-called
*atoms*, which have an unambiguous, special-purpose type and do not have
the runtime overhead of string constants.
Atoms in CAF are mapped to integer values at compile time. This mapping is
guaranteed to be collision-free and invertible, but limits atom literals to ten
characters and prohibits special characters. Legal characters are
``_0-9A-Za-z`` and the whitespace character. Atoms are created using
the ``constexpr`` function ``atom``, as the following example
illustrates.
Atoms in CAF are tag types, i.e., usually defined as en empty ``struct``. These
types carry no data on their own and only exist to annotate messages. For
example, we could create the two tag types ``add_atom`` and ``multiply_atom``
for implementing a simple math actor like this:
.. code-block:: C++
atom_value a1 = atom("add");
atom_value a2 = atom("multiply");
CAF_BEGIN_TYPE_ID_BLOCK(my_project, caf::first_custom_type_id)
**Warning**: The compiler cannot enforce the restrictions at compile time,
except for a length check. The assertion ``atom("!?") != atom("?!")``
is not true, because each invalid character translates to a whitespace
character.
CAF_ADD_ATOM(my_project, add_atom)
CAF_ADD_ATOM(my_project, multiply_atom)
While the ``atom_value`` is computed at compile time, it is not
uniquely typed and thus cannot be used in the signature of a callback. To
accomplish this, CAF offers compile-time *atom constants*.
.. code-block:: C++
using add_atom = atom_constant<atom("add")>;
using multiply_atom = atom_constant<atom("multiply")>;
Using these constants, we can now define message passing interfaces in a
convenient way:
.. code-block:: C++
CAF_END_TYPE_ID_BLOCK(my_project)
behavior do_math{
[](add_atom, int a, int b) {
[](add_atom, int32_t a, int32_t b) {
return a + b;
},
[](multiply_atom, int a, int b) {
[](multiply_atom, int32_t a, int32_t b) {
return a * b;
}
};
// caller side: send(math_actor, add_atom::value, 1, 2)
Atom constants define a static member ``value``. Please note that this
static ``value`` member does *not* have the type
``atom_value``, unlike ``std::integral_constant`` for example.
// caller side: send(math_actor, add_atom_v, int32_t{1}, int32_t{2})
The macro ``CAF_ADD_ATOM`` defined an empty ``struct`` with the given name as
well as a ``constexpr`` variable for conveniently creating a value of that type
that uses the type name plus a ``_v`` suffix. In the example above,
``atom_value`` is the type name and ``atom_value_v`` is the constant.
This diff is collapsed.
This diff is collapsed.
Overview
========
Compiling CAF requires CMake and a C++11-compatible compiler. To get and
compile the sources on UNIX-like systems, type the following in a terminal:
Compiling CAF requires CMake and a recent C++ compiler. To get and compile the
sources on UNIX-like systems, type the following in a terminal:
.. ::
.. code-block:: bash
git clone https://github.com/actor-framework/actor-framework
cd actor-framework
./configure
make
make install [as root, optional]
make -C build
make -C build install [as root, optional]
We recommended to run the unit tests as well:
.. ::
make test
If the output indicates an error, please submit a bug report that includes (a)
your compiler version, (b) your OS, and (c) the content of the file
``build/Testing/Temporary/LastTest.log``.
Running ``configure`` is not a mandatory step. The script merely automates the
CMake setup and makes setting build options slightly more convenient. On
Windows, use CMake directly to generate an MSVC project file.
Features
--------
......@@ -32,19 +26,13 @@ Features
* Thread-mapped actors for soft migration of existing applications
* Publish/subscribe group communication
Minimal Compiler Versions
-------------------------
* GCC 4.8
* Clang 3.4
* Visual Studio 2015, Update 3
Supported Operating Systems
---------------------------
* Linux
* Mac OS X
* Windows (static library only)
* Windows
* macOS
* FreeBSD
Hello World Example
-------------------
......
......@@ -139,6 +139,7 @@ The following example implements two actors, ``ping`` and
.. literalinclude:: /examples/testing/ping_pong.cpp
:language: C++
:lines: 12-60
:start-after: --(rst-ping-pong-begin)--
:end-before: --(rst-ping-pong-end)--
......@@ -21,7 +21,6 @@ Contents
ReferenceCounting
Error
ConfiguringActorApplications
Messages
GroupCommunication
ManagingGroupsOfWorkers
Streaming
......
manual/mailbox_element.png

20 KB | W: | H:

manual/mailbox_element.png

39.8 KB | W: | H:

manual/mailbox_element.png
manual/mailbox_element.png
manual/mailbox_element.png
manual/mailbox_element.png
  • 2-up
  • Swipe
  • Onion skin
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment