File: dictionary_behavior.cpp

package info (click to toggle)
actor-framework 0.17.6-3.2
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 9,008 kB
  • sloc: cpp: 77,684; sh: 674; python: 309; makefile: 13
file content (54 lines) | stat: -rw-r--r-- 1,489 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/******************************************************************************\
 * This example is a simple dictionary implemented * using composable states. *
\******************************************************************************/

// This file is partially included in the manual, do not modify
// without updating the references in the *.tex files!
// Manual references: lines 22-44 (Actor.tex)

#include <string>
#include <iostream>
#include <unordered_map>

#include "caf/all.hpp"

using std::cout;
using std::endl;
using std::string;
using namespace caf;

namespace {

using dict = typed_actor<reacts_to<put_atom, string, string>,
                         replies_to<get_atom, string>::with<string>>;

class dict_behavior : public composable_behavior<dict> {
public:
  result<string> operator()(get_atom, param<string> key) override {
    auto i = values_.find(key);
    if (i == values_.end())
      return "";
    return i->second;
  }

  result<void> operator()(put_atom, param<string> key,
                          param<string> value) override {
    if (values_.count(key) != 0)
      return unit;
    values_.emplace(key.move(), value.move());
    return unit;
  }

protected:
  std::unordered_map<string, string> values_;
};

} // namespace

void caf_main(actor_system& system) {
  auto f = make_function_view(system.spawn<dict_behavior>());
  f(put_atom::value, "CAF", "success");
  cout << "CAF is the key to " << f(get_atom::value, "CAF") << endl;
}

CAF_MAIN()