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

fix breaking change in MediaType.toString #334

Merged
merged 1 commit into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 4 additions & 1 deletion core/src/main/scala/sttp/model/MediaType.scala
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ case class MediaType(

def isModel: Boolean = mainType.equalsIgnoreCase("model")

override lazy val toString: String = {
// Cache 'toString' given that it's called in the hot path
// of request processing to generate headers.
private lazy val toStringCache: String = {
Copy link
Member

Choose a reason for hiding this comment

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

maybe you could add a comment explaining why this particular class has a toStringCache field?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

val sb = new java.lang.StringBuilder(32) // "application/json; charset=utf-8".length == 31 ;)
sb.append(mainType).append('/').append(subType)
charset match {
Expand All @@ -77,6 +79,7 @@ case class MediaType(
sb.toString
}

override def toString() = toStringCache
override lazy val hashCode: Int = toString.toLowerCase.hashCode

override def equals(that: Any): Boolean =
Expand Down
6 changes: 6 additions & 0 deletions core/src/test/scala/sttp/model/MediaTypeTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ class MediaTypeTests extends AnyFlatSpec with Matchers with TableDrivenPropertyC
an[IllegalArgumentException] shouldBe thrownBy(MediaType.unsafeApply("te=xt", "plain"))
}

it should "have a regular toString" in {
val mt = MediaType.ApplicationGzip
mt.toString shouldBe "application/gzip"
mt.toString() shouldBe "application/gzip"
}

private val matchCases = Table(
("media type", "content type range", "matches"),
// simple matching
Expand Down
Loading