/* __ *\ ** ________ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2007-2013, LAMP/EPFL ** ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ import java.{ lang => jl } import java.math.{ MathContext, BigDecimal => BigDec } import scala.collection.immutable.NumericRange import scala.language.implicitConversions /** * @author Stephane Micheloud * @version 1.0 * @since 2.7 */ object BigDecimal { private val minCached = -512 private val maxCached = 512 val defaultMathContext = MathContext.DECIMAL128 /** Cache ony for defaultMathContext using BigDecimals in a small range. */ private lazy val cache = new Array[BigDecimal](maxCached - minCached + 1) object RoundingMode extends Enumeration { type RoundingMode = Value // These are supposed to be the same as java.math.RoundingMode.values, // though it seems unwise to rely on the correspondence. val UP, DOWN, CEILING, FLOOR, HALF_UP, HALF_DOWN, HALF_EVEN, UNNECESSARY = Value } /** Constructs a `BigDecimal` using the java BigDecimal static * valueOf constructor. * * @param d the specified double value * @return the constructed `BigDecimal` */ def valueOf(d: Double): BigDecimal = apply(BigDec valueOf d) def valueOf(d: Double, mc: MathContext): BigDecimal = apply(BigDec valueOf d, mc) def valueOf(x: Long): BigDecimal = apply(x.toDouble) /** Constructs a `BigDecimal` whose value is equal to that of the * specified `Integer` value. * * @param i the specified integer value * @return the constructed `BigDecimal` */ def apply(i: Int): BigDecimal = apply(i, defaultMathContext) def apply(i: Int, mc: MathContext): BigDecimal = if (mc == defaultMathContext && minCached <= i && i <= maxCached) { val offset = i - minCached var n = cache(offset) if (n eq null) { n = new BigDecimal(BigDec.valueOf(i.toLong), mc); cache(offset) = n } n } else new BigDecimal(BigDec.valueOf(i.toLong), mc) /** Constructs a `BigDecimal` whose value is equal to that of the * specified long value. * * @param l the specified long value * @return the constructed `BigDecimal` */ def apply(l: Long): BigDecimal = if (minCached <= l && l <= maxCached) apply(l.toInt) else new BigDecimal(BigDec.valueOf(l), defaultMathContext) def apply(l: Long, mc: MathContext): BigDecimal = new BigDecimal(new BigDec(l, mc), mc) /** Constructs a `BigDecimal` whose unscaled value is equal to that * of the specified long value. * * @param unscaledVal the value * @param scale the scale * @return the constructed `BigDecimal` */ def apply(unscaledVal: Long, scale: Int): BigDecimal = apply(BigInt(unscaledVal), scale) def apply(unscaledVal: Long, scale: Int, mc: MathContext): BigDecimal = apply(BigInt(unscaledVal), scale, mc) /** Constructs a `BigDecimal` whose value is equal to that of the * specified double value. * * @param d the specified `Double` value * @return the constructed `BigDecimal` */ def apply(d: Double): BigDecimal = apply(d, defaultMathContext) // note we don't use the static valueOf because it doesn't let us supply // a MathContext, but we should be duplicating its logic, modulo caching. def apply(d: Double, mc: MathContext): BigDecimal = new BigDecimal(new BigDec(jl.Double.toString(d), mc), mc) def apply(x: Float): BigDecimal = apply(x.toDouble) def apply(x: Float, mc: MathContext): BigDecimal = apply(x.toDouble, mc) /** Translates a character array representation of a `BigDecimal` * into a `BigDecimal`. */ def apply(x: Array[Char]): BigDecimal = apply(x, defaultMathContext) def apply(x: Array[Char], mc: MathContext): BigDecimal = new BigDecimal(new BigDec(x.mkString, mc), mc) /** Translates the decimal String representation of a `BigDecimal` * into a `BigDecimal`. */ def apply(x: String): BigDecimal = apply(x, defaultMathContext) def apply(x: String, mc: MathContext): BigDecimal = new BigDecimal(new BigDec(x, mc), mc) /** Constructs a `BigDecimal` whose value is equal to that of the * specified `BigInt` value. * * @param x the specified `BigInt` value * @return the constructed `BigDecimal` */ def apply(x: BigInt): BigDecimal = apply(x, defaultMathContext) def apply(x: BigInt, mc: MathContext): BigDecimal = new BigDecimal(new BigDec(x.bigInteger, mc), mc) /** Constructs a `BigDecimal` whose unscaled value is equal to that * of the specified `BigInt` value. * * @param unscaledVal the specified `BigInt` value * @param scale the scale * @return the constructed `BigDecimal` */ def apply(unscaledVal: BigInt, scale: Int): BigDecimal = apply(unscaledVal, scale, defaultMathContext) def apply(unscaledVal: BigInt, scale: Int, mc: MathContext): BigDecimal = new BigDecimal(new BigDec(unscaledVal.bigInteger, scale, mc), mc) def apply(bd: BigDec): BigDecimal = apply(bd, defaultMathContext) def apply(bd: BigDec, mc: MathContext): BigDecimal = new BigDecimal(bd, mc) /** Implicit conversion from `Int` to `BigDecimal`. */ implicit def int2bigDecimal(i: Int): BigDecimal = apply(i) /** Implicit conversion from `Long` to `BigDecimal`. */ implicit def long2bigDecimal(l: Long): BigDecimal = apply(l) /** Implicit conversion from `Double` to `BigDecimal`. */ implicit def double2bigDecimal(d: Double): BigDecimal = valueOf(d, defaultMathContext) /** Implicit conversion from `java.math.BigDecimal` to `scala.BigDecimal`. */ implicit def javaBigDecimal2bigDecimal(x: BigDec): BigDecimal = apply(x) } /** * @author Stephane Micheloud * @version 1.0 */ class BigDecimal( val bigDecimal: BigDec, val mc: MathContext) extends scala.math.ScalaNumber with scala.math.ScalaNumericConversions with Serializable { def this(bigDecimal: BigDec) = this(bigDecimal, BigDecimal.defaultMathContext) import BigDecimal.RoundingMode._ /** Cuts way down on the wrapper noise. */ private implicit def bigdec2BigDecimal(x: BigDec): BigDecimal = new BigDecimal(x, mc) /** Returns the hash code for this BigDecimal. * Note that this does not use the underlying java object's * hashCode because we compare BigDecimals with compareTo * which deems 2 == 2.00, whereas in java these are unequal * with unequal hashCodes. */ override def hashCode(): Int = if (isWhole()) unifiedPrimitiveHashcode() else doubleValue.## /** Compares this BigDecimal with the specified value for equality. */ override def equals (that: Any): Boolean = that match { case that: BigDecimal => this equals that case that: BigInt => this.toBigIntExact exists (that equals _) case that: Double => isValidDouble && toDouble == that case that: Float => isValidFloat && toFloat == that case _ => isValidLong && unifiedPrimitiveEquals(that) } override def isValidByte = noArithmeticException(toByteExact) override def isValidShort = noArithmeticException(toShortExact) override def isValidChar = isValidInt && toIntExact >= Char.MinValue && toIntExact <= Char.MaxValue override def isValidInt = noArithmeticException(toIntExact) def isValidLong = noArithmeticException(toLongExact) /** Returns `true` iff this can be represented exactly by [[scala.Float]]; otherwise returns `false`. */ def isValidFloat = { val f = toFloat !f.isInfinity && bigDecimal.compareTo(new java.math.BigDecimal(f.toDouble)) == 0 } /** Returns `true` iff this can be represented exactly by [[scala.Double]]; otherwise returns `false`. */ def isValidDouble = { val d = toDouble !d.isInfinity && bigDecimal.compareTo(new java.math.BigDecimal(d)) == 0 } private def noArithmeticException(body: => Unit): Boolean = { try { body ; true } catch { case _: ArithmeticException => false } } def isWhole() = (this remainder 1) == BigDecimal(0) def underlying = bigDecimal /** Compares this BigDecimal with the specified BigDecimal for equality. */ def equals (that: BigDecimal): Boolean = compare(that) == 0 /** Compares this BigDecimal with the specified BigDecimal */ def compare (that: BigDecimal): Int = this.bigDecimal compareTo that.bigDecimal /** Less-than-or-equals comparison of BigDecimals */ def <= (that: BigDecimal): Boolean = compare(that) <= 0 /** Greater-than-or-equals comparison of BigDecimals */ def >= (that: BigDecimal): Boolean = compare(that) >= 0 /** Less-than of BigDecimals */ def < (that: BigDecimal): Boolean = compare(that) < 0 /** Greater-than comparison of BigDecimals */ def > (that: BigDecimal): Boolean = compare(that) > 0 /** Addition of BigDecimals */ def + (that: BigDecimal): BigDecimal = this.bigDecimal.add(that.bigDecimal) /** Subtraction of BigDecimals */ def - (that: BigDecimal): BigDecimal = this.bigDecimal.subtract(that.bigDecimal) /** Multiplication of BigDecimals */ def * (that: BigDecimal): BigDecimal = this.bigDecimal.multiply(that.bigDecimal, mc) /** Division of BigDecimals */ def / (that: BigDecimal): BigDecimal = this.bigDecimal.divide(that.bigDecimal, mc) /** Division and Remainder - returns tuple containing the result of * divideToIntegralValue and the remainder. */ def /% (that: BigDecimal): (BigDecimal, BigDecimal) = this.bigDecimal.divideAndRemainder(that.bigDecimal) match { case Array(q, r) => (q, r) } /** Divide to Integral value. */ def quot (that: BigDecimal): BigDecimal = this.bigDecimal.divideToIntegralValue(that.bigDecimal) /** Returns the minimum of this and that */ def min (that: BigDecimal): BigDecimal = this.bigDecimal min that.bigDecimal /** Returns the maximum of this and that */ def max (that: BigDecimal): BigDecimal = this.bigDecimal max that.bigDecimal /** Remainder after dividing this by that. */ def remainder (that: BigDecimal): BigDecimal = this.bigDecimal.remainder(that.bigDecimal) /** Remainder after dividing this by that. */ def % (that: BigDecimal): BigDecimal = this.remainder(that) /** Returns a BigDecimal whose value is this ** n. */ def pow (n: Int): BigDecimal = this.bigDecimal.pow(n, mc) /** Returns a BigDecimal whose value is the negation of this BigDecimal */ def unary_- : BigDecimal = this.bigDecimal.negate() /** Returns the absolute value of this BigDecimal */ def abs: BigDecimal = this.bigDecimal.abs /** Returns the sign of this BigDecimal, i.e. * -1 if it is less than 0, * +1 if it is greater than 0 * 0 if it is equal to 0 */ def signum: Int = this.bigDecimal.signum() /** Returns the precision of this `BigDecimal`. */ def precision: Int = this.bigDecimal.precision() /** Returns a BigDecimal rounded according to the MathContext settings. */ def round(mc: MathContext): BigDecimal = this.bigDecimal round mc /** Returns the scale of this `BigDecimal`. */ def scale: Int = this.bigDecimal.scale() /** Returns the size of an ulp, a unit in the last place, of this BigDecimal. */ def ulp: BigDecimal = this.bigDecimal.ulp /** Returns a new BigDecimal based on the supplied MathContext. */ def apply(mc: MathContext): BigDecimal = BigDecimal(this.bigDecimal.toString, mc) /** Returns a `BigDecimal` whose scale is the specified value, and whose value is * numerically equal to this BigDecimal's. */ def setScale(scale: Int): BigDecimal = this.bigDecimal setScale scale def setScale(scale: Int, mode: RoundingMode): BigDecimal = this.bigDecimal.setScale(scale, mode.id) /** Converts this BigDecimal to a Byte. * If the BigDecimal is too big to fit in a Byte, only the low-order 8 bits are returned. * Note that this conversion can lose information about the overall magnitude of the * BigDecimal value as well as return a result with the opposite sign. */ override def byteValue = intValue.toByte /** Converts this BigDecimal to a Short. * If the BigDecimal is too big to fit in a Short, only the low-order 16 bits are returned. * Note that this conversion can lose information about the overall magnitude of the * BigDecimal value as well as return a result with the opposite sign. */ override def shortValue = intValue.toShort /** Converts this BigDecimal to a Char. * If the BigDecimal is too big to fit in a Char, only the low-order 16 bits are returned. * Note that this conversion can lose information about the overall magnitude of the * BigDecimal value and that it always returns a positive result. */ def charValue = intValue.toChar /** Converts this BigDecimal to an Int. * If the BigDecimal is too big to fit in an Int, only the low-order 32 bits * are returned. Note that this conversion can lose information about the * overall magnitude of the BigDecimal value as well as return a result with * the opposite sign. */ def intValue = this.bigDecimal.intValue /** Converts this BigDecimal to a Long. * If the BigDecimal is too big to fit in a Long, only the low-order 64 bits * are returned. Note that this conversion can lose information about the * overall magnitude of the BigDecimal value as well as return a result with * the opposite sign. */ def longValue = this.bigDecimal.longValue /** Converts this BigDecimal to a Float. * if this BigDecimal has too great a magnitude to represent as a float, * it will be converted to `Float.NEGATIVE_INFINITY` or * `Float.POSITIVE_INFINITY` as appropriate. */ def floatValue = this.bigDecimal.floatValue /** Converts this BigDecimal to a Double. * if this BigDecimal has too great a magnitude to represent as a double, * it will be converted to `Double.NEGATIVE_INFINITY` or * `Double.POSITIVE_INFINITY` as appropriate. */ def doubleValue = this.bigDecimal.doubleValue /** Converts this `BigDecimal` to a [[scala.Byte]], checking for lost information. * If this `BigDecimal` has a nonzero fractional part, or is out of the possible * range for a [[scala.Byte]] result, then a `java.lang.ArithmeticException` is * thrown. */ def toByteExact = bigDecimal.byteValueExact /** Converts this `BigDecimal` to a [[scala.Short]], checking for lost information. * If this `BigDecimal` has a nonzero fractional part, or is out of the possible * range for a [[scala.Short]] result, then a `java.lang.ArithmeticException` is * thrown. */ def toShortExact = bigDecimal.shortValueExact /** Converts this `BigDecimal` to a [[scala.Int]], checking for lost information. * If this `BigDecimal` has a nonzero fractional part, or is out of the possible * range for an [[scala.Int]] result, then a `java.lang.ArithmeticException` is * thrown. */ def toIntExact = bigDecimal.intValueExact /** Converts this `BigDecimal` to a [[scala.Long]], checking for lost information. * If this `BigDecimal` has a nonzero fractional part, or is out of the possible * range for a [[scala.Long]] result, then a `java.lang.ArithmeticException` is * thrown. */ def toLongExact = bigDecimal.longValueExact /** Converts this `BigDecimal` to a scala.BigInt. */ def toBigInt(): BigInt = new BigInt(this.bigDecimal.toBigInteger()) /** Converts this `BigDecimal` to a scala.BigInt if it * can be done losslessly, returning Some(BigInt) or None. */ def toBigIntExact(): Option[BigInt] = try Some(new BigInt(this.bigDecimal.toBigIntegerExact())) catch { case _: ArithmeticException => None } /** Returns the decimal String representation of this BigDecimal. */ override def toString(): String = this.bigDecimal.toString() } /** An implementation of Austin Appleby's MurmurHash 3.0 algorithm * (32 bit version); reference: http://code.google.com/p/smhasher * * This is the hash used by collections and case classes (including * tuples). * * @author Rex Kerr * @version 2.9 * @since 2.9 */ import java.lang.Integer.{ rotateLeft => rotl } import scala.collection.Iterator /** A class designed to generate well-distributed non-cryptographic * hashes. It is designed to be passed to a collection's foreach method, * or can take individual hash values with append. Its own hash code is * set equal to the hash code of whatever it is hashing. */ @deprecated("Use the object MurmurHash3 instead.", "2.10.0") class MurmurHash[@specialized(Int,Long,Float,Double) T](seed: Int) extends (T => Unit) { import MurmurHash._ private var h = startHash(seed) private var c = hiddenMagicA private var k = hiddenMagicB private var hashed = false private var hashvalue = h /** Begin a new hash using the same seed. */ def reset() { h = startHash(seed) c = hiddenMagicA k = hiddenMagicB hashed = false } /** Incorporate the hash value of one item. */ def apply(t: T) { h = extendHash(h,t.##,c,k) c = nextMagicA(c) k = nextMagicB(k) hashed = false } /** Incorporate a known hash value. */ def append(i: Int) { h = extendHash(h,i,c,k) c = nextMagicA(c) k = nextMagicB(k) hashed = false } /** Retrieve the hash value */ def hash = { if (!hashed) { hashvalue = finalizeHash(h) hashed = true } hashvalue } override def hashCode = hash } /** An object designed to generate well-distributed non-cryptographic * hashes. It is designed to hash a collection of integers; along with * the integers to hash, it generates two magic streams of integers to * increase the distribution of repetitive input sequences. Thus, * three methods need to be called at each step (to start and to * incorporate a new integer) to update the values. Only one method * needs to be called to finalize the hash. */ @deprecated("Use the object MurmurHash3 instead.", "2.10.0") // NOTE: Used by SBT 0.13.0-M2 and below object MurmurHash { // Magic values used for MurmurHash's 32 bit hash. // Don't change these without consulting a hashing expert! final private val visibleMagic = 0x971e137b final private val hiddenMagicA = 0x95543787 final private val hiddenMagicB = 0x2ad7eb25 final private val visibleMixer = 0x52dce729 final private val hiddenMixerA = 0x7b7d159c final private val hiddenMixerB = 0x6bce6396 final private val finalMixer1 = 0x85ebca6b final private val finalMixer2 = 0xc2b2ae35 // Arbitrary values used for hashing certain classes final private val seedString = 0xf7ca7fd2 final private val seedArray = 0x3c074a61 /** The first 23 magic integers from the first stream are stored here */ val storedMagicA = Iterator.iterate(hiddenMagicA)(nextMagicA).take(23).toArray /** The first 23 magic integers from the second stream are stored here */ val storedMagicB = Iterator.iterate(hiddenMagicB)(nextMagicB).take(23).toArray /** Begin a new hash with a seed value. */ def startHash(seed: Int) = seed ^ visibleMagic /** The initial magic integers in the first stream. */ def startMagicA = hiddenMagicA /** The initial magic integer in the second stream. */ def startMagicB = hiddenMagicB /** Incorporates a new value into an existing hash. * * @param hash the prior hash value * @param value the new value to incorporate * @param magicA a magic integer from the stream * @param magicB a magic integer from a different stream * @return the updated hash value */ def extendHash(hash: Int, value: Int, magicA: Int, magicB: Int) = { (hash ^ rotl(value*magicA,11)*magicB)*3 + visibleMixer } /** Given a magic integer from the first stream, compute the next */ def nextMagicA(magicA: Int) = magicA*5 + hiddenMixerA /** Given a magic integer from the second stream, compute the next */ def nextMagicB(magicB: Int) = magicB*5 + hiddenMixerB /** Once all hashes have been incorporated, this performs a final mixing */ def finalizeHash(hash: Int) = { var i = (hash ^ (hash>>>16)) i *= finalMixer1 i ^= (i >>> 13) i *= finalMixer2 i ^= (i >>> 16) i } /** Compute a high-quality hash of an array */ def arrayHash[@specialized T](a: Array[T]) = { var h = startHash(a.length * seedArray) var c = hiddenMagicA var k = hiddenMagicB var j = 0 while (j < a.length) { h = extendHash(h, a(j).##, c, k) c = nextMagicA(c) k = nextMagicB(k) j += 1 } finalizeHash(h) } /** Compute a high-quality hash of a string */ def stringHash(s: String) = { var h = startHash(s.length * seedString) var c = hiddenMagicA var k = hiddenMagicB var j = 0 while (j+1 < s.length) { val i = (s.charAt(j)<<16) + s.charAt(j+1) h = extendHash(h,i,c,k) c = nextMagicA(c) k = nextMagicB(k) j += 2 } if (j < s.length) h = extendHash(h,s.charAt(j).toInt,c,k) finalizeHash(h) } /** Compute a hash that is symmetric in its arguments--that is, * where the order of appearance of elements does not matter. * This is useful for hashing sets, for example. */ def symmetricHash[T](xs: scala.collection.TraversableOnce[T], seed: Int) = { var a,b,n = 0 var c = 1 xs.seq.foreach(i => { val h = i.## a += h b ^= h if (h != 0) c *= h n += 1 }) var h = startHash(seed * n) h = extendHash(h, a, storedMagicA(0), storedMagicB(0)) h = extendHash(h, b, storedMagicA(1), storedMagicB(1)) h = extendHash(h, c, storedMagicA(2), storedMagicB(2)) finalizeHash(h) } } import scala.collection.immutable.List import scala.reflect.{ ClassTag, classTag } import java.lang.reflect.InvocationTargetException import scala.language.implicitConversions /** Classes representing the components of exception handling. * Each class is independently composable. Some example usages: * {{{ * import scala.util.control.Exception._ * import java.net._ * * val s = "http://www.scala-lang.org/" * val x1 = catching(classOf[MalformedURLException]) opt new URL(s) * val x2 = catching(classOf[MalformedURLException], classOf[NullPointerException]) either new URL(s) * }}} * * This class differs from `scala.util.Try` in that it focuses on composing exception handlers rather than * composing behavior. All behavior should be composed first and fed to a `Catch` object using one of the * `opt` or `either` methods. * * @author Paul Phillips */ object Exception { type Catcher[+T] = PartialFunction[Throwable, T] def mkCatcher[Ex <: Throwable: ClassTag, T](isDef: Ex => Boolean, f: Ex => T) = new Catcher[T] { private def downcast(x: Throwable): Option[Ex] = if (classTag[Ex].runtimeClass.isAssignableFrom(x.getClass)) Some(x.asInstanceOf[Ex]) else None def isDefinedAt(x: Throwable) = downcast(x) exists isDef def apply(x: Throwable): T = f(downcast(x).get) } def mkThrowableCatcher[T](isDef: Throwable => Boolean, f: Throwable => T) = mkCatcher(isDef, f) implicit def throwableSubtypeToCatcher[Ex <: Throwable: ClassTag, T](pf: PartialFunction[Ex, T]) = mkCatcher(pf.isDefinedAt _, pf.apply _) /** !!! Not at all sure of every factor which goes into this, * and/or whether we need multiple standard variations. */ def shouldRethrow(x: Throwable): Boolean = x match { case _: util.control.ControlThrowable => true case _: InterruptedException => true // case _: java.lang.Error => true ? case _ => false } trait Described { protected val name: String private var _desc: String = "" def desc = _desc def withDesc(s: String): this.type = { _desc = s this } override def toString() = name + "(" + desc + ")" } /** A container class for finally code. */ class Finally private[Exception](body: => Unit) extends Described { protected val name = "Finally" def and(other: => Unit): Finally = new Finally({ body ; other }) def invoke() { body } } /** A container class for catch/finally logic. * * Pass a different value for rethrow if you want to probably * unwisely allow catching control exceptions and other throwables * which the rest of the world may expect to get through. */ class Catch[+T]( val pf: Catcher[T], val fin: Option[Finally] = None, val rethrow: Throwable => Boolean = shouldRethrow) extends Described { protected val name = "Catch" /** Create a new Catch with additional exception handling logic. */ def or[U >: T](pf2: Catcher[U]): Catch[U] = new Catch(pf orElse pf2, fin, rethrow) def or[U >: T](other: Catch[U]): Catch[U] = or(other.pf) /** Apply this catch logic to the supplied body. */ def apply[U >: T](body: => U): U = try body catch { case x if rethrow(x) => throw x case x if pf isDefinedAt x => pf(x) } finally fin map (_.invoke()) /* Create an empty Try container with this Catch and the supplied `Finally`. */ def andFinally(body: => Unit): Catch[T] = fin match { case None => new Catch(pf, Some(new Finally(body)), rethrow) case Some(f) => new Catch(pf, Some(f and body), rethrow) } /** Apply this catch logic to the supplied body, mapping the result * into `Option[T]` - `None` if any exception was caught, `Some(T)` otherwise. */ def opt[U >: T](body: => U): Option[U] = toOption(Some(body)) /** Apply this catch logic to the supplied body, mapping the result * into Either[Throwable, T] - Left(exception) if an exception was caught, * Right(T) otherwise. */ def either[U >: T](body: => U): Either[Throwable, U] = toEither(Right(body)) /** Apply this catch logic to the supplied body, mapping the result * into Try[T] - Failure if an exception was caught, Success(T) otherwise. */ def withTry[U >: T](body: => U): scala.util.Try[U] = toTry(util.Success(body)) /** Create a `Catch` object with the same `isDefinedAt` logic as this one, * but with the supplied `apply` method replacing the current one. */ def withApply[U](f: Throwable => U): Catch[U] = { val pf2 = new Catcher[U] { def isDefinedAt(x: Throwable) = pf isDefinedAt x def apply(x: Throwable) = f(x) } new Catch(pf2, fin, rethrow) } /** Convenience methods. */ def toOption: Catch[Option[T]] = withApply(_ => None) def toEither: Catch[Either[Throwable, T]] = withApply(Left(_)) def toTry: Catch[scala.util.Try[T]] = withApply(x => util.Failure(x)) } final val nothingCatcher: Catcher[Nothing] = mkThrowableCatcher(_ => false, throw _) final def nonFatalCatcher[T]: Catcher[T] = mkThrowableCatcher({ case util.control.NonFatal(_) => true; case _ => false }, throw _) final def allCatcher[T]: Catcher[T] = mkThrowableCatcher(_ => true, throw _) /** The empty `Catch` object. */ final val noCatch: Catch[Nothing] = new Catch(nothingCatcher) withDesc "" /** A `Catch` object which catches everything. */ final def allCatch[T]: Catch[T] = new Catch(allCatcher[T]) withDesc "" /** A `Catch` object witch catches non-fatal exceptions. */ final def nonFatalCatch[T]: Catch[T] = new Catch(nonFatalCatcher[T]) withDesc "" /** Creates a `Catch` object which will catch any of the supplied exceptions. * Since the returned `Catch` object has no specific logic defined and will simply * rethrow the exceptions it catches, you will typically want to call `opt` or * `either` on the return value, or assign custom logic by calling "withApply". * * Note that `Catch` objects automatically rethrow `ControlExceptions` and others * which should only be caught in exceptional circumstances. If you really want * to catch exactly what you specify, use `catchingPromiscuously` instead. */ def catching[T](exceptions: Class[_]*): Catch[T] = new Catch(pfFromExceptions(exceptions : _*)) withDesc (exceptions map (_.getName) mkString ", ") def catching[T](c: Catcher[T]): Catch[T] = new Catch(c) /** Creates a `Catch` object which will catch any of the supplied exceptions. * Unlike "catching" which filters out those in shouldRethrow, this one will * catch whatever you ask of it: `ControlThrowable`, `InterruptedException`, * `OutOfMemoryError`, you name it. */ def catchingPromiscuously[T](exceptions: Class[_]*): Catch[T] = catchingPromiscuously(pfFromExceptions(exceptions : _*)) def catchingPromiscuously[T](c: Catcher[T]): Catch[T] = new Catch(c, None, _ => false) /** Creates a `Catch` object which catches and ignores any of the supplied exceptions. */ def ignoring(exceptions: Class[_]*): Catch[Unit] = catching(exceptions: _*) withApply (_ => ()) /** Creates a `Catch` object which maps all the supplied exceptions to `None`. */ def failing[T](exceptions: Class[_]*): Catch[Option[T]] = catching(exceptions: _*) withApply (_ => None) /** Creates a `Catch` object which maps all the supplied exceptions to the given value. */ def failAsValue[T](exceptions: Class[_]*)(value: => T): Catch[T] = catching(exceptions: _*) withApply (_ => value) /** Returns a partially constructed `Catch` object, which you must give * an exception handler function as an argument to `by`. Example: * {{{ * handling(ex1, ex2) by (_.printStackTrace) * }}} */ class By[T,R](f: T => R) { def by(x: T): R = f(x) } def handling[T](exceptions: Class[_]*) = { def fun(f: Throwable => T) = catching(exceptions: _*) withApply f new By[Throwable => T, Catch[T]](fun _) } /** Returns a `Catch` object with no catch logic and the argument as `Finally`. */ def ultimately[T](body: => Unit): Catch[T] = noCatch andFinally body /** Creates a `Catch` object which unwraps any of the supplied exceptions. */ def unwrapping[T](exceptions: Class[_]*): Catch[T] = { def unwrap(x: Throwable): Throwable = if (wouldMatch(x, exceptions) && x.getCause != null) unwrap(x.getCause) else x catching(exceptions: _*) withApply (x => throw unwrap(x)) } /** Private **/ private def wouldMatch(x: Throwable, classes: scala.collection.Seq[Class[_]]): Boolean = classes exists (_ isAssignableFrom x.getClass) private def pfFromExceptions(exceptions: Class[_]*): PartialFunction[Throwable, Nothing] = { case x if wouldMatch(x, exceptions) => throw x } } import java.io.Writer @deprecated("This object will be removed.", "2.11.0") case object DocNil extends Document @deprecated("This object will be removed.", "2.11.0") case object DocBreak extends Document @deprecated("This class will be removed.", "2.11.0") case class DocText(txt: String) extends Document @deprecated("This class will be removed.", "2.11.0") case class DocGroup(doc: Document) extends Document @deprecated("This class will be removed.", "2.11.0") case class DocNest(indent: Int, doc: Document) extends Document @deprecated("This class will be removed.", "2.11.0") case class DocCons(hd: Document, tl: Document) extends Document /** * A basic pretty-printing library, based on Lindig's strict version * of Wadler's adaptation of Hughes' pretty-printer. * * @author Michel Schinz * @version 1.0 */ @deprecated("This class will be removed.", "2.11.0") abstract class Document { def ::(hd: Document): Document = DocCons(hd, this) def ::(hd: String): Document = DocCons(DocText(hd), this) def :/:(hd: Document): Document = hd :: DocBreak :: this def :/:(hd: String): Document = hd :: DocBreak :: this /** * Format this document on `writer` and try to set line * breaks so that the result fits in `width` columns. */ def format(width: Int, writer: Writer) { type FmtState = (Int, Boolean, Document) def fits(w: Int, state: List[FmtState]): Boolean = state match { case _ if w < 0 => false case List() => true case (_, _, DocNil) :: z => fits(w, z) case (i, b, DocCons(h, t)) :: z => fits(w, (i,b,h) :: (i,b,t) :: z) case (_, _, DocText(t)) :: z => fits(w - t.length(), z) case (i, b, DocNest(ii, d)) :: z => fits(w, (i + ii, b, d) :: z) case (_, false, DocBreak) :: z => fits(w - 1, z) case (_, true, DocBreak) :: z => true case (i, _, DocGroup(d)) :: z => fits(w, (i, false, d) :: z) } def spaces(n: Int) { var rem = n while (rem >= 16) { writer write " "; rem -= 16 } if (rem >= 8) { writer write " "; rem -= 8 } if (rem >= 4) { writer write " "; rem -= 4 } if (rem >= 2) { writer write " "; rem -= 2} if (rem == 1) { writer write " " } } def fmt(k: Int, state: List[FmtState]): Unit = state match { case List() => () case (_, _, DocNil) :: z => fmt(k, z) case (i, b, DocCons(h, t)) :: z => fmt(k, (i, b, h) :: (i, b, t) :: z) case (i, _, DocText(t)) :: z => writer write t fmt(k + t.length(), z) case (i, b, DocNest(ii, d)) :: z => fmt(k, (i + ii, b, d) :: z) case (i, true, DocBreak) :: z => writer write "\n" spaces(i) fmt(i, z) case (i, false, DocBreak) :: z => writer write " " fmt(k + 1, z) case (i, b, DocGroup(d)) :: z => val fitsFlat = fits(width - k, (i, false, d) :: z) fmt(k, (i, !fitsFlat, d) :: z) case _ => () } fmt(0, (0, false, DocGroup(this)) :: Nil) } } @deprecated("This object will be removed.", "2.11.0") object Document { /** The empty document */ def empty = DocNil /** A break, which will either be turned into a space or a line break */ def break = DocBreak /** A document consisting of some text literal */ def text(s: String): Document = DocText(s) /** * A group, whose components will either be printed with all breaks * rendered as spaces, or with all breaks rendered as line breaks. */ def group(d: Document): Document = DocGroup(d) /** A nested document, which will be indented as specified. */ def nest(i: Int, d: Document): Document = DocNest(i, d) } import scala.collection.mutable.ArrayBuffer import scala.collection.generic.CanBuildFrom import scala.collection.immutable.{ List, Stream } import scala.language.{implicitConversions, higherKinds} /** * @author Stephane Micheloud * */ class Random(val self: java.util.Random) extends AnyRef with Serializable { /** Creates a new random number generator using a single long seed. */ def this(seed: Long) = this(new java.util.Random(seed)) /** Creates a new random number generator using a single integer seed. */ def this(seed: Int) = this(seed.toLong) /** Creates a new random number generator. */ def this() = this(new java.util.Random()) /** Returns the next pseudorandom, uniformly distributed boolean value * from this random number generator's sequence. */ def nextBoolean(): Boolean = self.nextBoolean() /** Generates random bytes and places them into a user-supplied byte * array. */ def nextBytes(bytes: Array[Byte]) { self.nextBytes(bytes) } /** Returns the next pseudorandom, uniformly distributed double value * between 0.0 and 1.0 from this random number generator's sequence. */ def nextDouble(): Double = self.nextDouble() /** Returns the next pseudorandom, uniformly distributed float value * between 0.0 and 1.0 from this random number generator's sequence. */ def nextFloat(): Float = self.nextFloat() /** Returns the next pseudorandom, Gaussian ("normally") distributed * double value with mean 0.0 and standard deviation 1.0 from this * random number generator's sequence. */ def nextGaussian(): Double = self.nextGaussian() /** Returns the next pseudorandom, uniformly distributed int value * from this random number generator's sequence. */ def nextInt(): Int = self.nextInt() /** Returns a pseudorandom, uniformly distributed int value between 0 * (inclusive) and the specified value (exclusive), drawn from this * random number generator's sequence. */ def nextInt(n: Int): Int = self.nextInt(n) /** Returns the next pseudorandom, uniformly distributed long value * from this random number generator's sequence. */ def nextLong(): Long = self.nextLong() /** Returns a pseudorandomly generated String. This routine does * not take any measures to preserve the randomness of the distribution * in the face of factors like unicode's variable-length encoding, * so please don't use this for anything important. It's primarily * intended for generating test data. * * @param length the desired length of the String * @return the String */ def nextString(length: Int) = { def safeChar() = { val surrogateStart: Int = 0xD800 val res = nextInt(surrogateStart - 1) + 1 res.toChar } List.fill(length)(safeChar()).mkString } /** Returns the next pseudorandom, uniformly distributed value * from the ASCII range 33-126. */ def nextPrintableChar(): Char = { val low = 33 val high = 127 (self.nextInt(high - low) + low).toChar } def setSeed(seed: Long) { self.setSeed(seed) } /** Returns a new collection of the same type in a randomly chosen order. * * @return the shuffled collection */ def shuffle[T, CC[X] <: TraversableOnce[X]](xs: CC[T])(implicit bf: CanBuildFrom[CC[T], T, CC[T]]): CC[T] = { val buf = new ArrayBuffer[T] ++= xs def swap(i1: Int, i2: Int) { val tmp = buf(i1) buf(i1) = buf(i2) buf(i2) = tmp } for (n <- buf.length to 2 by -1) { val k = nextInt(n) swap(n - 1, k) } (bf(xs) ++= buf).result() } /** Returns a Stream of pseudorandomly chosen alphanumeric characters, * equally chosen from A-Z, a-z, and 0-9. * * @since 2.8 */ def alphanumeric: Stream[Char] = { def isAlphaNum(c: Char) = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') Stream continually nextPrintableChar filter isAlphaNum } } /** The object `Random` offers a default implementation * of scala.util.Random and random-related convenience methods. * * @since 2.8 */ object Random extends Random { implicit def javaRandomToRandom(r: java.util.Random): Random = new Random(r) } import scala.reflect.{ ClassTag, classTag } import scala.math.{ Ordering, max, min } /** The Sorting object provides functions that can sort various kinds of * objects. You can provide a comparison function, or you can request a sort * of items that are viewable as [[scala.math.Ordered]]. Some sorts that * operate directly on a subset of value types are also provided. These * implementations are derived from those in the Sun JDK. * * Note that stability doesn't matter for value types, so use the `quickSort` * variants for those. `stableSort` is intended to be used with * objects when the prior ordering should be preserved, where possible. * * @author Ross Judson * @version 1.0 */ object Sorting { /** Quickly sort an array of Doubles. */ def quickSort(a: Array[Double]) { sort1(a, 0, a.length) } /** Quickly sort an array of items with an implicit Ordering. */ def quickSort[K: Ordering](a: Array[K]) { sort1(a, 0, a.length) } /** Quickly sort an array of Ints. */ def quickSort(a: Array[Int]) { sort1(a, 0, a.length) } /** Quickly sort an array of Floats. */ def quickSort(a: Array[Float]) { sort1(a, 0, a.length) } /** Sort an array of K where K is Ordered, preserving the existing order * where the values are equal. */ def stableSort[K: ClassTag: Ordering](a: Array[K]) { stableSort(a, 0, a.length-1, new Array[K](a.length), Ordering[K].lt _) } /** Sorts an array of `K` given an ordering function `f`. * `f` should return `true` iff its first parameter is strictly less than its second parameter. */ def stableSort[K: ClassTag](a: Array[K], f: (K, K) => Boolean) { stableSort(a, 0, a.length-1, new Array[K](a.length), f) } /** Sorts an arbitrary sequence into an array, given a comparison function * that should return `true` iff parameter one is strictly less than parameter two. * * @param a the sequence to be sorted. * @param f the comparison function. * @return the sorted sequence of items. */ def stableSort[K: ClassTag](a: Seq[K], f: (K, K) => Boolean): Array[K] = { val ret = a.toArray stableSort(ret, f) ret } /** Sorts an arbitrary sequence of items that are viewable as ordered. */ def stableSort[K: ClassTag: Ordering](a: Seq[K]): Array[K] = stableSort(a, Ordering[K].lt _) /** Stably sorts a sequence of items given an extraction function that will * return an ordered key from an item. * * @param a the sequence to be sorted. * @param f the comparison function. * @return the sorted sequence of items. */ def stableSort[K: ClassTag, M: Ordering](a: Seq[K], f: K => M): Array[K] = stableSort(a)(implicitly[ClassTag[K]], Ordering[M] on f) private def sort1[K: Ordering](x: Array[K], off: Int, len: Int) { val ord = Ordering[K] import ord._ def swap(a: Int, b: Int) { val t = x(a) x(a) = x(b) x(b) = t } def vecswap(_a: Int, _b: Int, n: Int) { var a = _a var b = _b var i = 0 while (i < n) { swap(a, b) i += 1 a += 1 b += 1 } } def med3(a: Int, b: Int, c: Int) = { if (x(a) < x(b)) { if (x(b) < x(c)) b else if (x(a) < x(c)) c else a } else { if (x(b) > x(c)) b else if (x(a) > x(c)) c else a } } def sort2(off: Int, len: Int) { // Insertion sort on smallest arrays if (len < 7) { var i = off while (i < len + off) { var j = i while (j > off && x(j-1) > x(j)) { swap(j, j-1) j -= 1 } i += 1 } } else { // Choose a partition element, v var m = off + (len >> 1) // Small arrays, middle element if (len > 7) { var l = off var n = off + len - 1 if (len > 40) { // Big arrays, pseudomedian of 9 val s = len / 8 l = med3(l, l+s, l+2*s) m = med3(m-s, m, m+s) n = med3(n-2*s, n-s, n) } m = med3(l, m, n) // Mid-size, med of 3 } val v = x(m) // Establish Invariant: v* (v)* v* var a = off var b = a var c = off + len - 1 var d = c var done = false while (!done) { while (b <= c && x(b) <= v) { if (x(b) == v) { swap(a, b) a += 1 } b += 1 } while (c >= b && x(c) >= v) { if (x(c) == v) { swap(c, d) d -= 1 } c -= 1 } if (b > c) { done = true } else { swap(b, c) c -= 1 b += 1 } } // Swap partition elements back to middle val n = off + len var s = math.min(a-off, b-a) vecswap(off, b-s, s) s = math.min(d-c, n-d-1) vecswap(b, n-s, s) // Recursively sort non-partition-elements s = b - a if (s > 1) sort2(off, s) s = d - c if (s > 1) sort2(n-s, s) } } sort2(off, len) } private def sort1(x: Array[Int], off: Int, len: Int) { def swap(a: Int, b: Int) { val t = x(a) x(a) = x(b) x(b) = t } def vecswap(_a: Int, _b: Int, n: Int) { var a = _a var b = _b var i = 0 while (i < n) { swap(a, b) i += 1 a += 1 b += 1 } } def med3(a: Int, b: Int, c: Int) = { if (x(a) < x(b)) { if (x(b) < x(c)) b else if (x(a) < x(c)) c else a } else { if (x(b) > x(c)) b else if (x(a) > x(c)) c else a } } def sort2(off: Int, len: Int) { // Insertion sort on smallest arrays if (len < 7) { var i = off while (i < len + off) { var j = i while (j>off && x(j-1) > x(j)) { swap(j, j-1) j -= 1 } i += 1 } } else { // Choose a partition element, v var m = off + (len >> 1) // Small arrays, middle element if (len > 7) { var l = off var n = off + len - 1 if (len > 40) { // Big arrays, pseudomedian of 9 val s = len / 8 l = med3(l, l+s, l+2*s) m = med3(m-s, m, m+s) n = med3(n-2*s, n-s, n) } m = med3(l, m, n) // Mid-size, med of 3 } val v = x(m) // Establish Invariant: v* (v)* v* var a = off var b = a var c = off + len - 1 var d = c var done = false while (!done) { while (b <= c && x(b) <= v) { if (x(b) == v) { swap(a, b) a += 1 } b += 1 } while (c >= b && x(c) >= v) { if (x(c) == v) { swap(c, d) d -= 1 } c -= 1 } if (b > c) { done = true } else { swap(b, c) c -= 1 b += 1 } } // Swap partition elements back to middle val n = off + len var s = math.min(a-off, b-a) vecswap(off, b-s, s) s = math.min(d-c, n-d-1) vecswap(b, n-s, s) // Recursively sort non-partition-elements s = b - a if (s > 1) sort2(off, s) s = d - c if (s > 1) sort2(n-s, s) } } sort2(off, len) } private def sort1(x: Array[Double], off: Int, len: Int) { def swap(a: Int, b: Int) { val t = x(a) x(a) = x(b) x(b) = t } def vecswap(_a: Int, _b: Int, n: Int) { var a = _a var b = _b var i = 0 while (i < n) { swap(a, b) i += 1 a += 1 b += 1 } } def med3(a: Int, b: Int, c: Int) = { val ab = x(a) compare x(b) val bc = x(b) compare x(c) val ac = x(a) compare x(c) if (ab < 0) { if (bc < 0) b else if (ac < 0) c else a } else { if (bc > 0) b else if (ac > 0) c else a } } def sort2(off: Int, len: Int) { // Insertion sort on smallest arrays if (len < 7) { var i = off while (i < len + off) { var j = i while (j > off && (x(j-1) compare x(j)) > 0) { swap(j, j-1) j -= 1 } i += 1 } } else { // Choose a partition element, v var m = off + (len >> 1) // Small arrays, middle element if (len > 7) { var l = off var n = off + len - 1 if (len > 40) { // Big arrays, pseudomedian of 9 val s = len / 8 l = med3(l, l+s, l+2*s) m = med3(m-s, m, m+s) n = med3(n-2*s, n-s, n) } m = med3(l, m, n) // Mid-size, med of 3 } val v = x(m) // Establish Invariant: v* (v)* v* var a = off var b = a var c = off + len - 1 var d = c var done = false while (!done) { var bv = x(b) compare v while (b <= c && bv <= 0) { if (bv == 0) { swap(a, b) a += 1 } b += 1 if (b <= c) bv = x(b) compare v } var cv = x(c) compare v while (c >= b && cv >= 0) { if (cv == 0) { swap(c, d) d -= 1 } c -= 1 if (c >= b) cv = x(c) compare v } if (b > c) { done = true } else { swap(b, c) c -= 1 b += 1 } } // Swap partition elements back to middle val n = off + len var s = math.min(a-off, b-a) vecswap(off, b-s, s) s = math.min(d-c, n-d-1) vecswap(b, n-s, s) // Recursively sort non-partition-elements s = b - a if (s > 1) sort2(off, s) s = d - c if (s > 1) sort2(n-s, s) } } sort2(off, len) } private def sort1(x: Array[Float], off: Int, len: Int) { def swap(a: Int, b: Int) { val t = x(a) x(a) = x(b) x(b) = t } def vecswap(_a: Int, _b: Int, n: Int) { var a = _a var b = _b var i = 0 while (i < n) { swap(a, b) i += 1 a += 1 b += 1 } } def med3(a: Int, b: Int, c: Int) = { val ab = x(a) compare x(b) val bc = x(b) compare x(c) val ac = x(a) compare x(c) if (ab < 0) { if (bc < 0) b else if (ac < 0) c else a } else { if (bc > 0) b else if (ac > 0) c else a } } def sort2(off: Int, len: Int) { // Insertion sort on smallest arrays if (len < 7) { var i = off while (i < len + off) { var j = i while (j > off && (x(j-1) compare x(j)) > 0) { swap(j, j-1) j -= 1 } i += 1 } } else { // Choose a partition element, v var m = off + (len >> 1) // Small arrays, middle element if (len > 7) { var l = off var n = off + len - 1 if (len > 40) { // Big arrays, pseudomedian of 9 val s = len / 8 l = med3(l, l+s, l+2*s) m = med3(m-s, m, m+s) n = med3(n-2*s, n-s, n) } m = med3(l, m, n) // Mid-size, med of 3 } val v = x(m) // Establish Invariant: v* (v)* v* var a = off var b = a var c = off + len - 1 var d = c var done = false while (!done) { var bv = x(b) compare v while (b <= c && bv <= 0) { if (bv == 0) { swap(a, b) a += 1 } b += 1 if (b <= c) bv = x(b) compare v } var cv = x(c) compare v while (c >= b && cv >= 0) { if (cv == 0) { swap(c, d) d -= 1 } c -= 1 if (c >= b) cv = x(c) compare v } if (b > c) { done = true } else { swap(b, c) c -= 1 b += 1 } } // Swap partition elements back to middle val n = off + len var s = math.min(a-off, b-a) vecswap(off, b-s, s) s = math.min(d-c, n-d-1) vecswap(b, n-s, s) // Recursively sort non-partition-elements s = b - a if (s > 1) sort2(off, s) s = d - c if (s > 1) sort2(n-s, s) } } sort2(off, len) } private def stableSort[K : ClassTag](a: Array[K], lo: Int, hi: Int, scratch: Array[K], f: (K,K) => Boolean) { if (lo < hi) { val mid = (lo+hi) / 2 stableSort(a, lo, mid, scratch, f) stableSort(a, mid+1, hi, scratch, f) var k, t_lo = lo var t_hi = mid + 1 while (k <= hi) { if ((t_lo <= mid) && ((t_hi > hi) || (!f(a(t_hi), a(t_lo))))) { scratch(k) = a(t_lo) t_lo += 1 } else { scratch(k) = a(t_hi) t_hi += 1 } k += 1 } k = lo while (k <= hi) { a(k) = scratch(k) k += 1 } } } } trait AnsiColor { /** Foreground color for ANSI black */ final val BLACK = "\u001b[30m" /** Foreground color for ANSI red */ final val RED = "\u001b[31m" /** Foreground color for ANSI green */ final val GREEN = "\u001b[32m" /** Foreground color for ANSI yellow */ final val YELLOW = "\u001b[33m" /** Foreground color for ANSI blue */ final val BLUE = "\u001b[34m" /** Foreground color for ANSI magenta */ final val MAGENTA = "\u001b[35m" /** Foreground color for ANSI cyan */ final val CYAN = "\u001b[36m" /** Foreground color for ANSI white */ final val WHITE = "\u001b[37m" /** Background color for ANSI black */ final val BLACK_B = "\u001b[40m" /** Background color for ANSI red */ final val RED_B = "\u001b[41m" /** Background color for ANSI green */ final val GREEN_B = "\u001b[42m" /** Background color for ANSI yellow */ final val YELLOW_B = "\u001b[43m" /** Background color for ANSI blue */ final val BLUE_B = "\u001b[44m" /** Background color for ANSI magenta */ final val MAGENTA_B = "\u001b[45m" /** Background color for ANSI cyan */ final val CYAN_B = "\u001b[46m" /** Background color for ANSI white */ final val WHITE_B = "\u001b[47m" /** Reset ANSI styles */ final val RESET = "\u001b[0m" /** ANSI bold */ final val BOLD = "\u001b[1m" /** ANSI underlines */ final val UNDERLINED = "\u001b[4m" /** ANSI blink */ final val BLINK = "\u001b[5m" /** ANSI reversed */ final val REVERSED = "\u001b[7m" /** ANSI invisible */ final val INVISIBLE = "\u001b[8m" } object AnsiColor extends AnsiColor { }