/src/compiler/scala/tools/nsc/util/package.scala

http://github.com/greedy/scala-llvm · Scala · 70 lines · 42 code · 14 blank · 14 comment · 3 complexity · a2d37c0019eb2980b5325e615f683ad8 MD5 · raw file

  1. /* NSC -- new Scala compiler
  2. * Copyright 2005-2011 LAMP/EPFL
  3. * @author Paul Phillips
  4. */
  5. package scala.tools.nsc
  6. import java.io.{ OutputStream, PrintStream, ByteArrayOutputStream, PrintWriter, StringWriter }
  7. package object util {
  8. // forwarder for old code that builds against 2.9 and 2.10
  9. val Chars = scala.reflect.internal.Chars
  10. type Set[T <: AnyRef] = scala.reflect.internal.util.Set[T]
  11. type HashSet[T >: Null <: AnyRef] = scala.reflect.internal.util.HashSet[T]
  12. val HashSet = scala.reflect.internal.util.HashSet
  13. def onull[T](value: T, orElse: => T): T = if (value == null) orElse else value
  14. /** Apply a function and return the passed value */
  15. def returning[T](x: T)(f: T => Unit): T = { f(x) ; x }
  16. /** Frequency counter */
  17. def freq[T](xs: Traversable[T]): Map[T, Int] = xs groupBy identity mapValues (_.size)
  18. def freqrank[T](xs: Traversable[(T, Int)]): List[(Int, T)] = xs.toList map (_.swap) sortBy (-_._1)
  19. /** Execute code and then wait for all Threads created during its
  20. * execution to complete.
  21. */
  22. def waitingForThreads[T](body: => T) = {
  23. val ts1 = sys.allThreads()
  24. val result = body
  25. val ts2 = sys.allThreads()
  26. val newThreads = ts2.toSet -- ts1 filterNot (_.isDaemon())
  27. newThreads foreach (_.join())
  28. result
  29. }
  30. /** Given a function and a block of code, evaluates code block,
  31. * calls function with milliseconds elapsed, and returns block result.
  32. */
  33. def millisElapsedTo[T](f: Long => Unit)(body: => T): T = {
  34. val start = System.currentTimeMillis
  35. val result = body
  36. val end = System.currentTimeMillis
  37. f(end - start)
  38. result
  39. }
  40. /** Generate a string using a routine that wants to write on a stream. */
  41. def stringFromWriter(writer: PrintWriter => Unit): String = {
  42. val stringWriter = new StringWriter()
  43. val stream = new NewLinePrintWriter(stringWriter)
  44. writer(stream)
  45. stream.close()
  46. stringWriter.toString
  47. }
  48. def stringFromStream(stream: OutputStream => Unit): String = {
  49. val bs = new ByteArrayOutputStream()
  50. val ps = new PrintStream(bs)
  51. stream(ps)
  52. ps.close()
  53. bs.toString()
  54. }
  55. def stackTraceString(ex: Throwable): String = stringFromWriter(ex printStackTrace _)
  56. }