Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid repeatedly evaluating the source if it's a complex expression #115

Merged
merged 3 commits into from
Sep 11, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,22 @@ object QuicklensMacros {
case Varargs(args) => focus +: args
}

val modF = modifyImpl(obj, focuses)
val modF = modifyImplCacheObj(obj, focuses)

toPathModify(obj, modF)
}

def toPathModifyFromFocus[S: Type, A: Type](obj: Expr[S], focus: Expr[S => A])(using Quotes): Expr[PathModify[S, A]] =
toPathModify(obj, modifyImpl(obj, Seq(focus)))
toPathModify(obj, modifyImplCacheObj(obj, Seq(focus)))

// #114: in case obj is a complex expression (not a simple by-name reference), we cache it to avoid repeatedly
// evaluating it; this especially matters in chained .modify calls
private def modifyImplCacheObj[S: Type, A: Type](obj: Expr[S], focuses: Seq[Expr[S => A]])(using
Quotes
): Expr[(A => A) => S] = '{
val v = $obj
${ modifyImpl('v, focuses) }
}

private def modifyImpl[S: Type, A: Type](obj: Expr[S], focuses: Seq[Expr[S => A]])(using
Quotes
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.softwaremill.quicklens

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class RepeatedModifyTest extends AnyFlatSpec with Matchers {
import RepeatedModifyTest._

it should "properly handle repeated modify invocations for different fields" in {
val c = C(B(1, 1, 1, 1, 1))
c
.modify(_.b.a1)
.setTo(0.0d)
.modify(_.b.a2)
.setTo(0.0d)
.modify(_.b.a3)
.setTo(0.0d)
.modify(_.b.a4)
.setTo(0.0d)
.modify(_.b.a5)
.setTo(0.0d) shouldBe C(B(0, 0, 0, 0, 0))
}

it should "properly handle repeated modify invocations for the same field" in {
val c = C(B(1, 1, 1, 1, 1))
c
.modify(_.b.a1)
.setTo(0.0d)
.modify(_.b.a1)
.setTo(1.0d)
.modify(_.b.a1)
.setTo(2.0d)
.modify(_.b.a1)
.setTo(3.0d)
.modify(_.b.a1)
.setTo(4.0d) shouldBe C(B(4, 1, 1, 1, 1))
}
}

object RepeatedModifyTest {
case class B(a1: Double, a2: Double, a3: Double, a4: Double, a5: Double)
case class C(b: B)
}