summaryrefslogtreecommitdiff
path: root/src/library/scala/sys/PropImpl.scala
blob: 02f00f682bad138f9b8c74d4c50616c393ecf5d6 (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
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2011, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala.sys

import scala.collection.mutable

/** The internal implementation of scala.sys.Prop.
 */
private[sys] class PropImpl[T](val key: String, valueFn: String => T) extends Prop[T] {
  def value: T = if (isSet) valueFn(get) else zero
  def isSet    = underlying contains key
  def set(newValue: String): String = {
    val old = if (isSet) get else null
    underlying(key) = newValue
    old
  }
  def get: String =
    if (isSet) underlying(key)
    else ""

  def clear() = underlying -= key

  /** The underlying property map, in our case always sys.props */
  protected def underlying: mutable.Map[String, String] = scala.sys.props
  protected def zero: T = null.asInstanceOf[T]
  private def getString = if (isSet) "currently: " + get else "unset"
  override def toString = "%s (%s)".format(key, getString)
}

trait PropCompanion {
  self: Prop.type =>

  private[sys] class BooleanPropImpl(key: String, valueFn: String => Boolean) extends PropImpl[Boolean](key, valueFn) with BooleanProp {
    def enable()  = this set "true"
    def disable() = this.clear()
    def toggle()  = if (value) disable() else enable()
  }
  private[sys] abstract class CreatorImpl[T](f: String => T) extends Creator[T] {
    def apply(key: String): Prop[T] = new PropImpl[T](key, f)
  }
  /** Implicit objects for the standard types.  Custom ones can also be
   *  created by implementing Creator[T].
   */
  private[sys] trait BooleanCreatorImpl extends Creator[Boolean] {
    self: BooleanProp.type =>

    /** As implemented in java.lang.Boolean.getBoolean. */
    private def javaStyleTruth(s: String) = s.toLowerCase == "true"

    def apply(key: String): BooleanProp = new BooleanPropImpl(key, javaStyleTruth)
  }
}