| 1 | package org.aiotrade.httpd |
|---|
| 2 | |
|---|
| 3 | import scala.actors.Actor |
|---|
| 4 | import scala.collection.mutable.ListBuffer |
|---|
| 5 | |
|---|
| 6 | object ChainActor { |
|---|
| 7 | /** a private case object None that will not accessable outside here */ |
|---|
| 8 | private case object None |
|---|
| 9 | /** noneAction will never be matched since None is private */ |
|---|
| 10 | private val noneAction: PartialFunction[Any, Unit] = {case None => ()} |
|---|
| 11 | } |
|---|
| 12 | |
|---|
| 13 | trait ChainActor extends Actor { |
|---|
| 14 | protected val actorActions = new ListBuffer[PartialFunction[Any, Unit]] |
|---|
| 15 | |
|---|
| 16 | def stop { |
|---|
| 17 | super.exit |
|---|
| 18 | } |
|---|
| 19 | |
|---|
| 20 | def act = loop { |
|---|
| 21 | react { |
|---|
| 22 | chainReactions |
|---|
| 23 | } |
|---|
| 24 | } |
|---|
| 25 | |
|---|
| 26 | private def chainReactions: PartialFunction[Any, Unit] = |
|---|
| 27 | (ChainActor.noneAction /: actorActions)(_ orElse _) |
|---|
| 28 | } |
|---|
| 29 | |
|---|
| 30 | /** |
|---|
| 31 | * A O-producer is a coroutine that produces type-O objects for consumption by other coroutines. |
|---|
| 32 | */ |
|---|
| 33 | trait Producer[O] extends ChainActor { |
|---|
| 34 | protected var consumer: Actor = _ |
|---|
| 35 | |
|---|
| 36 | actorActions += { |
|---|
| 37 | case output: O => consumer ! output |
|---|
| 38 | } |
|---|
| 39 | |
|---|
| 40 | /** |
|---|
| 41 | * Called by the coroutine's <code>run</code> method when it has produced a new output. |
|---|
| 42 | */ |
|---|
| 43 | def produce(output: O) { |
|---|
| 44 | consumer ! output |
|---|
| 45 | } |
|---|
| 46 | |
|---|
| 47 | /** |
|---|
| 48 | * Composes this producing coroutine with a transducing coroutine. |
|---|
| 49 | * |
|---|
| 50 | * @return A fused producing coroutine. |
|---|
| 51 | */ |
|---|
| 52 | def ==>[O2](to: Transducer[O, O2]): Producer[O2] = { |
|---|
| 53 | consumer = to |
|---|
| 54 | to |
|---|
| 55 | } |
|---|
| 56 | |
|---|
| 57 | /** |
|---|
| 58 | * Composes this producing coroutine with a consuming coroutine. |
|---|
| 59 | * |
|---|
| 60 | * @return A fused coroutine. |
|---|
| 61 | */ |
|---|
| 62 | def ==>(to: Consumer[O]): Actor = { |
|---|
| 63 | consumer = to |
|---|
| 64 | to |
|---|
| 65 | } |
|---|
| 66 | } |
|---|
| 67 | |
|---|
| 68 | /** |
|---|
| 69 | * An I-consumer is a coroutine that consumes type-I objects. |
|---|
| 70 | */ |
|---|
| 71 | trait Consumer[I] extends ChainActor { |
|---|
| 72 | |
|---|
| 73 | actorActions += { |
|---|
| 74 | case input: I => consume(input) |
|---|
| 75 | } |
|---|
| 76 | |
|---|
| 77 | protected def consume(input: I) |
|---|
| 78 | |
|---|
| 79 | } |
|---|
| 80 | |
|---|
| 81 | /** |
|---|
| 82 | * An I,O-transducer consumes type-I objects and produces type-O objects. |
|---|
| 83 | */ |
|---|
| 84 | trait Transducer[I, O] extends Consumer[I] with Producer[O] |
|---|