summaryrefslogtreecommitdiff
path: root/src/actors/scala/actors/ReactorCanReply.scala
blob: e30efcbed80a18c782af7f47949ad9c6266e7315 (plain) (blame)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2005-2013, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */


package scala.actors

/**
 * Provides message send operations that
 * may result in a response from the receiver.
 *
 * @author Philipp Haller
 */
private[actors] trait ReactorCanReply extends CanReply[Any, Any] {
  _: InternalReplyReactor =>

  type Future[+P] = scala.actors.Future[P]

  def !?(msg: Any): Any =
    (this !! msg)()

  def !?(msec: Long, msg: Any): Option[Any] = {
    val myself = Actor.rawSelf(this.scheduler)
    val res = new scala.concurrent.SyncVar[Any]
    val out = new OutputChannel[Any] {
      def !(msg: Any) =
        res set msg
      def send(msg: Any, replyTo: OutputChannel[Any]) =
        res set msg
      def forward(msg: Any) =
        res set msg
      def receiver =
        myself.asInstanceOf[Actor]
    }
    this.send(msg, out)
    res.get(msec)
  }

  def !!(msg: Any): Future[Any] =
    this !! (msg, { case x => x })

  def !![A](msg: Any, handler: PartialFunction[Any, A]): Future[A] = {
    val myself = Actor.rawSelf(this.scheduler)
    val ftch = new ReactChannel[A](myself)
    val res = new scala.concurrent.SyncVar[A]

    val out = new OutputChannel[Any] {
      def !(msg: Any) = {
        val msg1 = handler(msg)
        ftch ! msg1
        res set msg1
      }
      def send(msg: Any, replyTo: OutputChannel[Any]) = {
        val msg1 = handler(msg)
        ftch.send(msg1, replyTo)
        res set msg1
      }
      def forward(msg: Any) = {
        val msg1 = handler(msg)
        ftch forward msg1
        res set msg1
      }
      def receiver =
        myself.asInstanceOf[Actor]
    }

    this.send(msg, out)

    new Future[A] {
      def apply() = {
        if (!isSet)
          fvalue = Some(res.get)

        fvalueTyped
      }
      def respond(k: A => Unit): Unit =
        if (isSet) k(fvalueTyped)
        else inputChannel.react {
          case any => fvalue = Some(any); k(fvalueTyped)
        }
      def isSet =
        !fvalue.isEmpty
      def inputChannel = ftch
    }
  }
}