scala.collection.immutable.StringOps Scala Examples

The following examples show how to use scala.collection.immutable.StringOps. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: VMContext.scala    From scala-json   with Apache License 2.0 5 votes vote down vote up
package json.shadow

import json._
import json.internal.DefaultVMContext.PrimitiveArray
import json.internal.PrimitiveJArray.Builder
import json.internal.{PrimitiveJArray, SimpleStringBuilder, BaseVMContext, JValueObjectDeserializer}

import scala.collection.immutable.StringOps
import scala.collection.mutable
import scala.reflect.ClassTag

object VMContext extends BaseVMContext {
  def newVMStringBuilder: SimpleStringBuilder = new SimpleStringBuilder {
    val builder = new StringBuilder(128)

    def append(str: String): internal.SimpleStringBuilder = {
      builder append str
      this
    }

    def append(char: Char): SimpleStringBuilder = {
      builder.append(char)
      this
    }

    def ensureCapacity(cap: Int): Unit = builder.ensureCapacity(cap)

    def result(): String = builder.result()
  }

  val localMapper = new ThreadLocal[JValueObjectDeserializer] {
    override protected def initialValue: JValueObjectDeserializer =
      new JValueObjectDeserializer
  }

  //TODO: do these need to be specialized?
  def createPrimitiveArray[
        case '\b' => sb.append("\\b")
        case '\t' => sb.append("\\t")
        case '\n' => sb.append("\\n")
        case '\f' => sb.append("\\f")
        case '\r' => sb.append("\\r")
        case c if c < ' ' =>
          val t = "000" + Integer.toHexString(c)
          sb.append("\\u" + t.substring(t.length() - 4))
        case c => sb.append(c)
      }
    }
    sb.append('"')

    sb
  }

  def newJValueFromArray(arr: Array[_]): JArray = {
    import json.accessors._

    arr match {
      case x: Array[Byte] => new PrimitiveJArray[Byte](wrapPrimitiveArray(x))
      case x: Array[Short] => new PrimitiveJArray[Short](wrapPrimitiveArray(x))
      case x: Array[Int] => new PrimitiveJArray[Int](wrapPrimitiveArray(x))
      case x: Array[Long] => new PrimitiveJArray[Long](wrapPrimitiveArray(x))
      case x: Array[Double] => new PrimitiveJArray[Double](wrapPrimitiveArray(x))
      case x: Array[Float] => new PrimitiveJArray[Float](wrapPrimitiveArray(x))
      case x: Array[Boolean] => new PrimitiveJArray[Boolean](wrapPrimitiveArray(x))
    }
  }

  def extractPrimitiveJArray[T: ClassTag: PrimitiveJArray.Builder](x: Iterable[T]): Option[JArray] = {
    val builder = implicitly[PrimitiveJArray.Builder[T]]

    x match {
      case x: mutable.WrappedArray[T] => Some(newJValueFromArray(x.array))
      case x: IndexedSeq[T] => Some(builder.createFrom(x))
      case _ => None
    }
  }
} 
Example 2
Source File: JStringLike.scala    From scala-json   with Apache License 2.0 5 votes vote down vote up
package json.internal

import json._

import scala.collection.immutable.StringOps

trait JStringLike extends VM.Context.JStringBase { _: JString =>
  def iterator: Iterator[JString] =
    (new StringOps(str)).toIterator.map(c => JString(c.toString))

  def toJBoolean: JBoolean = if (str.isEmpty) JFalse else JTrue
  def toJNumber: JNumber =
    if (str.trim.isEmpty) JNumber(0)
    else try JNumber(str.trim.toDouble) catch {
      case x: Throwable => JNaN
    }
  def toJString: JString = this
  override def toString = toJSONString

  override def apply(x: JValue): JString =
    str.charAt(x.toJNumber.value.toInt).toString.js

  override def jString: JString = this

  def appendJSONStringBuilder(settings: JSONBuilderSettings = JSONBuilderSettings.pretty,
      out: SimpleStringBuilder, lvl: Int): SimpleStringBuilder = JValue.Context.quoteJSONString(str, out)

  override def jValue = this

  override def hashCode = str.hashCode

  override def canEqual(that: Any) = that match {
    case _: String  => true
    case _: JString => true
    case _          => false
  }

  override def equals(that: Any) = that match {
    case x: String  => x == str
    case JString(x) => x == str
    case _          => false
  }

  def ->>[T <: JValue](other: T): (JString, T) = this -> other
} 
Example 3
Source File: VMContext.scala    From scala-json   with Apache License 2.0 5 votes vote down vote up
package json.shadow

import json._
import json.internal.DefaultVMContext.PrimitiveArray
import json.internal.PrimitiveJArray.Builder
import json.internal.{JanssonDeserializer, PrimitiveJArray, SimpleStringBuilder, BaseVMContext}

import scala.collection.immutable.StringOps
import scala.collection.mutable
import scala.reflect.ClassTag

object VMContext extends BaseVMContext {
  def newVMStringBuilder: SimpleStringBuilder = new SimpleStringBuilder {
    val builder = new StringBuilder(128)

    def append(str: String): internal.SimpleStringBuilder = {
      builder append str
      this
    }

    def append(char: Char): SimpleStringBuilder = {
      builder.append(char)
      this
    }

    def ensureCapacity(cap: Int): Unit = builder.ensureCapacity(cap)

    def result(): String = builder.result()
  }

  //TODO: do these need to be specialized?
  def createPrimitiveArray[T: ClassTag](from: Array[T]): PrimitiveArray[T] = from

  def fromString(str: String): JValue = {
    JanssonDeserializer.parseString(str)
  }

  def fromAny(value: Any): JValue = JValue.fromAnyInternal(value)

  final def quoteJSONString(string: String, sb: SimpleStringBuilder): SimpleStringBuilder = {
    require(string != null)

    sb.ensureCapacity(string.length)

    sb.append(JanssonDeserializer.serializeString(string))

    sb
  }

  def newJValueFromArray(arr: Array[_]): JArray = {
    import json.accessors._

    arr match {
      case x: Array[Byte] => new PrimitiveJArray[Byte](wrapPrimitiveArray(x))
      case x: Array[Short] => new PrimitiveJArray[Short](wrapPrimitiveArray(x))
      case x: Array[Int] => new PrimitiveJArray[Int](wrapPrimitiveArray(x))
      case x: Array[Long] => new PrimitiveJArray[Long](wrapPrimitiveArray(x))
      case x: Array[Double] => new PrimitiveJArray[Double](wrapPrimitiveArray(x))
      case x: Array[Float] => new PrimitiveJArray[Float](wrapPrimitiveArray(x))
      case x: Array[Boolean] => new PrimitiveJArray[Boolean](wrapPrimitiveArray(x))
    }
  }

  def extractPrimitiveJArray[T: ClassTag: PrimitiveJArray.Builder](x: Iterable[T]): Option[JArray] = {
    val builder = implicitly[PrimitiveJArray.Builder[T]]

    x match {
      case x: mutable.WrappedArray[T] => Some(newJValueFromArray(x.array))
      case x: IndexedSeq[T] => Some(builder.createFrom(x))
      case _ => None
    }
  }
} 
Example 4
Source File: LogInstruction.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.core

import scala.collection.immutable.StringOps
import scala.concurrent.duration.Duration

sealed trait LogInstruction {
  def message: String
  def marginNb: Int
  def duration: Option[Duration]
  def colorized: String
  lazy val fullMargin: String = LogInstruction.physicalMargin * marginNb
  lazy val completeMessage: String = {

    def withMarginAndDuration(line: String): String = {
      val d = duration match {
        case None                             => ""
        case Some(dur) if dur.toMillis == 0   => s" [${dur.toMicros} μs]"
        case Some(dur) if dur.toSeconds >= 10 => s" [${dur.toSeconds} s]"
        case Some(dur)                        => s" [${dur.toMillis} ms]"
      }
      fullMargin + line + d
    }

    // Inject duration at the end of the first line
    message.split('\n').toList match {
      case Nil =>
        withMarginAndDuration(message)
      case head :: Nil =>
        withMarginAndDuration(head)
      case head :: tail =>
        (withMarginAndDuration(head) :: tail.map(l => fullMargin + l)).mkString("\n")
    }
  }
}

object LogInstruction {
  val physicalMargin: StringOps = "   "

  def renderLogs(logs: List[LogInstruction], colorized: Boolean = true): String =
    logs.foldLeft(new StringBuilder()) { (b, l) =>
      l match {
        case NoShowLogInstruction(_, _, _) => b
        case l: LogInstruction             => b.append("\n").append(if (colorized) l.colorized else l.completeMessage)
      }
    }.append("\n").result()

  def printLogs(logs: List[LogInstruction]): Unit =
    println(renderLogs(logs))

}

case class ScenarioTitleLogInstruction(message: String, marginNb: Int, duration: Option[Duration] = None) extends LogInstruction {
  lazy val colorized = fansi.Color.LightGray(completeMessage).overlay(attrs = fansi.Underlined.On, start = fullMargin.length).render
}

case class InfoLogInstruction(message: String, marginNb: Int, duration: Option[Duration] = None) extends LogInstruction {
  lazy val colorized = fansi.Color.DarkGray(completeMessage).render
}

case class SuccessLogInstruction(message: String, marginNb: Int, duration: Option[Duration] = None) extends LogInstruction {
  lazy val colorized = fansi.Color.Green(completeMessage).render
}

case class WarningLogInstruction(message: String, marginNb: Int, duration: Option[Duration] = None) extends LogInstruction {
  lazy val colorized = fansi.Color.Yellow(completeMessage).render
}

case class FailureLogInstruction(message: String, marginNb: Int, duration: Option[Duration] = None) extends LogInstruction {
  lazy val colorized = fansi.Color.Red(completeMessage).render
}

case class DebugLogInstruction(message: String, marginNb: Int, duration: Option[Duration] = None) extends LogInstruction {
  lazy val colorized = fansi.Color.Cyan(completeMessage).render
}

case class NoShowLogInstruction(message: String, marginNb: Int, duration: Option[Duration] = None) extends LogInstruction {
  lazy val colorized = fansi.Color.Black(completeMessage).render
} 
Example 5
Source File: ParadoxLogger.scala    From paradox   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.paradox

import java.io.{ PrintWriter, StringWriter }

import scala.collection.immutable.StringOps

trait ParadoxLogger {
  def debug(t: Throwable): Unit = {
    // we provide our own implementation because sbt doesn't offer any exception logging at debug
    val writer = new StringWriter()
    t.printStackTrace(new PrintWriter(writer))
    new StringOps(writer.toString).lines.foreach(debug(_))
  }
  def debug(msg: => String): Unit
  def info(msg: => String): Unit
  def warn(msg: => String): Unit
  def error(msg: => String): Unit
}

object NullLogger extends ParadoxLogger {
  override def debug(msg: => String): Unit = ()
  override def info(msg: => String): Unit = ()
  override def warn(msg: => String): Unit = ()
  override def error(msg: => String): Unit = ()
}

object PrintlnLogger extends ParadoxLogger {
  override def debug(msg: => String): Unit = println(s"[debug] $msg")
  override def info(msg: => String): Unit = println(s"[info] $msg")
  override def warn(msg: => String): Unit = println(s"[warn] $msg")
  override def error(msg: => String): Unit = println(s"[error] $msg")
}