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

Add Cats and ScalaCheck instances #1071

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

bpholt
Copy link
Member

@bpholt bpholt commented Oct 4, 2024

I'd like to use these in a forthcoming PR to natchez-http4s, and I thought they might be useful generally.

@@ -21,4 +23,10 @@ final case class Kernel(toHeaders: Map[CIString, String]) {
object Kernel {
private[natchez] def fromJava(headers: util.Map[String, String]): Kernel =
apply(headers.asScala.map { case (k, v) => CIString(k) -> v }.toMap)

implicit val kernelMonoid: Monoid[Kernel] =
Monoid.instance(Kernel(Map.empty), (a, b) => Kernel(a.toHeaders |+| b.toHeaders))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: a.toHeaders is a Map[CIString, *], so its monoid will use the monoid of String to combine values under the same (case insensitive) key - it will concatenate them. I don't think these are safe semantics for this monoid.

scala-cli --toolkit typelevel:default
Welcome to Scala 3.5.0 (21.0.2, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.

scala> import org.typelevel.ci.*, cats.*, cats.implicits.*

scala> Map(CIString("aaa") -> "hello") |+| Map(CIString("AAA") -> "goodbye")
val res0: Map[org.typelevel.ci.CIString, String] = Map(AAA -> hellogoodbye)

I think the desired semantics would likely be to prefer RHS in case of conflict. So,

Suggested change
Monoid.instance(Kernel(Map.empty), (a, b) => Kernel(a.toHeaders |+| b.toHeaders))
Monoid.instance(Kernel(Map.empty), (a, b) => Kernel(a.toHeaders ++ b.toHeaders))

and at this point I would suggest a test for the conflicting case, just to prevent accidents.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. I'll update accordingly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants