Debian Codegraph @

tests/inputs/ring.pony

raw
1 /*
2 * https://github.com/ponylang/ponyc/raw/908402b60f083d66d3b59a1879efb6adee5ca3cc/examples/ring/main.pony
3 */
4
5 """
6 A ring is a group of processes connected to each other using
7 unidirectional links through which messages can pass from process to
8 process in a cyclic manner.
9
10 The logic of this program is as follows:
11 * Each process in a ring is represented by the actor `Ring`
12 * `Main` creates Ring by instantiating `Ring` actors based on the
13 arguments passed and links them with each other by setting the next
14 actor as the previous ones number and at the end linking the last actor
15 to the first one thereby closing the links and completing the ring
16 * Once the ring is complete messages can be passed by calling the `pass`
17 behaviour on the current `Ring` to its neighbour.
18 * The program prints the id of the last `Ring` to receive a message
19
20 For example if you run this program with the following options `--size 3`
21 and `--pass 2`. It will create a ring that looks like this:
22
23
24 * * * *
25 * * * *
26 * 1 *_ _ _ * 2 *
27 * * * *
28 * * * *
29 * * * *
30 \ /
31 \ /
32 \ /
33 \ * * /
34 * *
35 * 3 *
36 * *
37 * *
38 * *
39
40 and print 3 as the id of the last Ring actor that received the
41 message.
42 """
43
44 use "collections"
45
46 actor Ring
47 let _id: U32
48 let _env: Env
49 var _next: (Ring | None)
50
51 new create(id: U32, env: Env, neighbor: (Ring | None) = None) =>
52 _id = id
53 _env = env
54 _next = neighbor
55
56 be set(neighbor: Ring) =>
57 _next = neighbor
58
59 be pass(i: USize) =>
60 if i > 0 then
61 match _next
62 | let n: Ring =>
63 n.pass(i - 1)
64 end
65 else
66 _env.out.print(_id.string())
67 end
68
69 actor Main
70 var _ring_size: U32 = 3
71 var _ring_count: U32 = 1
72 var _pass: USize = 10
73
74 var _env: Env
75
76 new create(env: Env) =>
77 _env = env
78
79 try
80 parse_args()?
81 setup_ring()
82 else
83 usage()
84 end
85
86 fun ref parse_args() ? =>
87 var i: USize = 1
88
89 while i < _env.args.size() do
90 // Every option has an argument.
91 var option = _env.args(i)?
92 var value = _env.args(i + 1)?
93 i = i + 2
94
95 match option
96 | "--size" =>
97 _ring_size = value.u32()?
98 | "--count" =>
99 _ring_count = value.u32()?
100 | "--pass" =>
101 _pass = value.usize()?
102 else
103 error
104 end
105 end
106
107 fun setup_ring() =>
108 for j in Range[U32](0, _ring_count) do
109 let first = Ring(1, _env)
110 var next = first
111
112 for k in Range[U32](0, _ring_size - 1) do
113 let current = Ring(_ring_size - k, _env, next)
114 next = current
115 end
116
117 first.set(next)
118
119 if _pass > 0 then
120 first.pass(_pass)
121 end
122 end
123
124 fun usage() =>
125 _env.out.print(
126 """
127 rings OPTIONS
128 --size N number of actors in each ring
129 --count N number of rings
130 --pass N number of messages to pass around each ring
131 """
132 )