silly optimizations

pull/2872/head
Thibault Duplessis 2017-03-28 17:18:51 +02:00
parent fb28781b07
commit db250f0c48
23 changed files with 53 additions and 38 deletions

View File

@ -1,6 +1,8 @@
package lila.app
package templating
import scala.collection.breakOut
import play.api.i18n.Lang
import play.api.libs.json.JsObject
import play.twirl.api.Html
@ -52,7 +54,7 @@ trait I18nHelper {
I18nDomain(ctx.req.domain).commonDomain
def acceptLanguages(implicit ctx: UserContext): List[String] =
ctx.req.acceptLanguages.map(_.language.toString).toList.distinct
(ctx.req.acceptLanguages.map(_.language.toString)(breakOut): List[String]).distinct
def acceptsLanguage(lang: Lang)(implicit ctx: UserContext): Boolean =
ctx.req.acceptLanguages exists (_.language == lang.language)

View File

@ -1,6 +1,8 @@
package lila.app
package templating
import scala.collection.breakOut
import lila.common.paginator.Paginator
trait PaginatorHelper {
@ -21,7 +23,7 @@ trait PaginatorHelper {
case x if showPost => List(none, pager.nbPages.some)
case _ => List(none)
}
pre ::: (fromPage to toPage).toList.map(some) ::: post
pre ::: ((fromPage to toPage).map(some)(breakOut): List[Option[Int]]) ::: post
}
def firstIndex: Int =

@ -1 +1 @@
Subproject commit 93dbad779dc26b86aab08185b1dc1c4afba4ca50
Subproject commit 8cdd646452c375441313268094b7cc0e50a48d3a

View File

@ -35,7 +35,9 @@ object PimpedJson {
(js \ key).asOpt[JsArray]
def arrAs[A](key: String)(as: JsValue => Option[A]): Option[List[A]] =
arr(key) map { _.value.toList map as flatten }
arr(key) map { j =>
(j.value.map(as)(scala.collection.breakOut): List[Option[A]]).flatten
}
def ints(key: String): Option[List[Int]] = arrAs(key)(_.asOpt[Int])

View File

@ -30,7 +30,7 @@ object PlayApp {
play.api.libs.concurrent.Akka.system
}
lazy val langs = loadConfig.getStringList("play.i18n.langs").toList map Lang.apply
lazy val langs = loadConfig.getStringList("play.i18n.langs").map(Lang.apply)(scala.collection.breakOut)
private def enableScheduler = !(loadConfig getBoolean "app.scheduler.disabled")

View File

@ -1,5 +1,6 @@
package lila.db
import scala.collection.breakOut
import org.joda.time.DateTime
import reactivemongo.bson._
import scalaz.NonEmptyList
@ -36,13 +37,13 @@ trait Handlers {
def dateIsoHandler[A](implicit iso: Iso[DateTime, A]): BSONHandler[BSONDateTime, A] = isoHandler[A, DateTime, BSONDateTime](iso)
implicit def bsonArrayToListHandler[T](implicit reader: BSONReader[_ <: BSONValue, T], writer: BSONWriter[T, _ <: BSONValue]): BSONHandler[BSONArray, List[T]] = new BSONHandler[BSONArray, List[T]] {
def read(array: BSONArray) = readStream(array, reader.asInstanceOf[BSONReader[BSONValue, T]]).toList
def read(array: BSONArray) = readStreamList(array, reader.asInstanceOf[BSONReader[BSONValue, T]]).toList
def write(repr: List[T]) =
new BSONArray(repr.map(s => scala.util.Try(writer.write(s))).to[Stream])
}
implicit def bsonArrayToVectorHandler[T](implicit reader: BSONReader[_ <: BSONValue, T], writer: BSONWriter[T, _ <: BSONValue]): BSONHandler[BSONArray, Vector[T]] = new BSONHandler[BSONArray, Vector[T]] {
def read(array: BSONArray) = readStream(array, reader.asInstanceOf[BSONReader[BSONValue, T]]).toVector
def read(array: BSONArray) = readStreamVector(array, reader.asInstanceOf[BSONReader[BSONValue, T]]).toVector
def write(repr: Vector[T]) =
new BSONArray(repr.map(s => scala.util.Try(writer.write(s))).to[Stream])
}
@ -53,11 +54,15 @@ trait Handlers {
def write(repr: NonEmptyList[T]) = listHandler.write(repr.list)
}
private def readStream[T](array: BSONArray, reader: BSONReader[BSONValue, T]): Stream[T] = {
private def readStreamList[T](array: BSONArray, reader: BSONReader[BSONValue, T]): List[T] =
array.stream.filter(_.isSuccess).map { v =>
reader.read(v.get)
}
}
}(breakOut)
private def readStreamVector[T](array: BSONArray, reader: BSONReader[BSONValue, T]): Vector[T] =
array.stream.filter(_.isSuccess).map { v =>
reader.read(v.get)
}(breakOut)
implicit val ipAddressHandler = isoHandler[IpAddress, String, BSONString](ipAddressIso)
}

View File

@ -47,7 +47,7 @@ object JsonHandlers {
private def parsePv(d: JsObject): Option[Pv] = for {
movesStr <- d str "moves"
moves <- movesStr.split(' ').take(EvalCacheEntry.MAX_PV_SIZE).toList.foldLeft(List.empty[Uci].some) {
moves <- movesStr.split(' ').take(EvalCacheEntry.MAX_PV_SIZE).foldLeft(List.empty[Uci].some) {
case (Some(ucis), str) => Uci(str) map (_ :: ucis)
case _ => None
}.flatMap(_.reverse.toNel) map Moves.apply

View File

@ -31,7 +31,7 @@ private[forum] final class Recent(
user.fold("en")(_.langs.mkString(",")) :: {
(user.??(_.troll) ?? List("[troll]")) :::
(user ?? MasterGranter(Permission.StaffForum)).fold(staffCategIds, publicCategIds) :::
(teamIds map teamSlug).toList
(teamIds.map(teamSlug)(scala.collection.breakOut): List[String])
} mkString ";"
}

View File

@ -37,7 +37,9 @@ object BSONHandlers {
def reads(r: BSON.Reader) = Crazyhouse.Data(
pockets = {
val (white, black) = r.str("p").toList.flatMap(chess.Piece.fromChar).partition(_ is chess.White)
val (white, black) = {
r.str("p").flatMap(chess.Piece.fromChar)(scala.collection.breakOut): List[chess.Piece]
}.partition(_ is chess.White)
Pockets(
white = Pocket(white.map(_.role)),
black = Pocket(black.map(_.role))

View File

@ -70,7 +70,7 @@ object BinaryFormat {
ba.value map toInt flatMap { k =>
Array(dec(k >> 4), dec(k & 15))
}
}.take(turns).map(Centis.apply).toVector
}.take(turns).map(Centis.apply)(breakOut)
}
case class clock(since: DateTime) {

View File

@ -79,11 +79,11 @@ private final class Captcher extends Actor {
})
private def solve(game: ChessGame): Option[Captcha.Solutions] =
game.situation.moves.toList flatMap {
(game.situation.moves.flatMap {
case (_, moves) => moves filter { move =>
(move.after situationOf !game.player).checkMate
}
} map { move =>
}(scala.collection.breakOut): List[chess.Move]) map { move =>
s"${move.orig} ${move.dest}"
} toNel

View File

@ -1,5 +1,7 @@
package lila.puzzle
import scala.collection.breakOut
import chess.Color
import chess.format.{ Uci, Forsyth }
import org.joda.time.DateTime
@ -73,7 +75,7 @@ object Puzzle {
case Some(m) => s"$m${move drop 2}"
case _ => sys error s"Invalid piotr move notation: $move"
}
def read(doc: BSONDocument): Lines = doc.elements.toList map {
def read(doc: BSONDocument): Lines = doc.elements.map {
case BSONElement(move, BSONBoolean(true)) => Win(readMove(move))
case BSONElement(move, BSONBoolean(false)) => Retry(readMove(move))
@ -83,7 +85,7 @@ object Puzzle {
case BSONElement(move, value) =>
throw new Exception(s"Can't read value of $move: $value")
}
}(breakOut)
private def writeMove(move: String) = chess.Pos.doubleKeyToPiotr(move take 4) match {
case Some(m) => s"$m${move drop 4}"
case _ => sys error s"Invalid move notation: $move"

View File

@ -31,7 +31,7 @@ final class OnlineDoing(
def friendsOf(userId: User.ID): Fu[OnlineFriends] =
api fetchFollowing userId map userIds.intersect map { friends =>
OnlineFriends(
users = friends.toList.flatMap { lightUser(_) },
users = friends.flatMap { lightUser(_) }(scala.collection.breakOut),
playing = playing intersect friends,
studying = friends filter studying.getAllPresent(friends).contains
)

View File

@ -3,6 +3,7 @@ package lila.relation
import akka.actor.Actor
import akka.pattern.pipe
import scala.concurrent.duration._
import scala.collection.breakOut
import actorApi._
import lila.common.LightUser
@ -34,8 +35,8 @@ private[relation] final class RelationActor(
case ComputeMovement =>
val curIds = online.userIds.keySet
val leaveUsers = (previousOnlineIds diff curIds).toList flatMap { lightUser(_) }
val enterUsers = (curIds diff previousOnlineIds).toList flatMap { lightUser(_) }
val leaveUsers: List[LightUser] = (previousOnlineIds diff curIds).flatMap { lightUser(_) }(breakOut)
val enterUsers: List[LightUser] = (curIds diff previousOnlineIds).flatMap { lightUser(_) }(breakOut)
val friendsEntering = enterUsers map { u =>
FriendEntering(u, online.playing get u.id, online isStudying u.id)

View File

@ -23,7 +23,7 @@ final class History[Metadata](ttl: FiniteDuration) {
if (v > version) None
else if (v == version) Some(Nil)
else {
val msgs = (v + 1 to version).toList flatMap message
val msgs: List[Message] = (v + 1 to version).flatMap(message)(scala.collection.breakOut)
(msgs.size == version - v) option msgs
}

View File

@ -106,7 +106,7 @@ object BSONHandlers {
private implicit def CrazyDataBSONHandler: BSON[Crazyhouse.Data] = new BSON[Crazyhouse.Data] {
private def writePocket(p: Crazyhouse.Pocket) = p.roles.map(_.forsyth).mkString
private def readPocket(p: String) = Crazyhouse.Pocket(p.toList.flatMap(chess.Role.forsyth))
private def readPocket(p: String) = Crazyhouse.Pocket(p.flatMap(chess.Role.forsyth)(scala.collection.breakOut))
def reads(r: Reader) = Crazyhouse.Data(
promoted = r.getsD[Pos]("o").toSet,
pockets = Crazyhouse.Pockets(

View File

@ -20,10 +20,11 @@ case class Path(ids: List[UciCharPair]) extends AnyVal {
object Path {
def apply(str: String): Path = Path {
str.toList.grouped(2).toList.flatMap {
case List(a, b) => UciCharPair(a, b).some
case _ => none[UciCharPair]
}
str.grouped(2).flatMap { p =>
p lift 1 map { b =>
UciCharPair(p(0), b)
}
}.toList
}
val root = Path("")

View File

@ -85,9 +85,9 @@ private[study] object PgnDump {
comments = node.comments.list.map(_.text.value),
opening = none,
result = none,
variations = variations.toList.map { child =>
variations = variations.map { child =>
toTurns(child.mainline, noVariations)
}
}(scala.collection.breakOut)
)
def toTurn(first: Node, second: Option[Node], variations: Variations) = chessPgn.Turn(
@ -109,7 +109,7 @@ private[study] object PgnDump {
}) filterNot (_.isEmpty)
def toTurnsFromWhite(line: List[Node], variations: Variations): List[chessPgn.Turn] =
(line grouped 2).toList.foldLeft(variations -> List.empty[chessPgn.Turn]) {
(line grouped 2).foldLeft(variations -> List.empty[chessPgn.Turn]) {
case ((variations, turns), pair) => pair.headOption.fold(variations -> turns) { first =>
pair.lift(1).getOrElse(first).children.variations -> (toTurn(first, pair lift 1, variations) :: turns)
}

View File

@ -44,5 +44,5 @@ object TreeBuilder {
)
private def toBranches(children: Node.Children): List[tree.Branch] =
children.nodes.toList.map(toBranch)
children.nodes.map(toBranch)(scala.collection.breakOut)
}

View File

@ -38,11 +38,11 @@ private[tournament] case class WaitingUsers(
nowSeconds - d.getSeconds
}
def waiting = {
def waiting: List[User.ID] = {
val since = date minusSeconds waitSeconds
hash.collect {
case (u, d) if d.isBefore(since) => u
}.toList
}(scala.collection.breakOut)
}
def update(us: Set[User.ID], clock: Option[TournamentClock]) = {

View File

@ -188,9 +188,7 @@ object Node {
JsArray(s.list.map(shapeWrites.writes))
}
implicit val glyphWriter: Writes[Glyph] = Json.writes[Glyph]
implicit val glyphsWriter: Writes[Glyphs] = Writes[Glyphs] { gs =>
Json.toJson(gs.toList)
}
implicit val glyphsWriter: Writes[Glyphs] = Writes[Glyphs] { Json.toJson(_) }
implicit val commentIdWrites: Writes[Comment.Id] = Writes { id =>
JsString(id.value)

View File

@ -148,7 +148,7 @@ case class Perfs(
)
def latest: Option[DateTime] =
perfsMap.values.toList.flatMap(_.latest).foldLeft(none[DateTime]) {
perfsMap.values.flatMap(_.latest).foldLeft(none[DateTime]) {
case (None, date) => date.some
case (Some(acc), date) if date isAfter acc => date.some
case (acc, _) => acc

View File

@ -139,7 +139,7 @@ final class RankingApi(
}(scala.collection.breakOut)
(800 to 2800 by Stat.group).map { r =>
hash.getOrElse(r, 0)
}.toList
}(scala.collection.breakOut)
}
}
}