Skip to content

Commit

Permalink
Use cached empty AST instances in apply (#1272)
Browse files Browse the repository at this point in the history
  • Loading branch information
hearnadam authored Feb 1, 2025
1 parent 3c71461 commit 95e7f2e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
24 changes: 19 additions & 5 deletions zio-json/shared/src/main/scala/zio/json/ast/ast.scala
Original file line number Diff line number Diff line change
Expand Up @@ -376,9 +376,15 @@ object Json {
override def mapObjectEntries(f: ((String, Json)) => (String, Json)): Json.Obj = Json.Obj(fields.map(f))
}
object Obj {
val empty: Obj = Obj(Chunk.empty)
val empty: Obj = new Obj(Chunk.empty)

def apply(fields: (String, Json)*): Obj = Obj(Chunk(fields: _*))
def apply(chunk: Chunk[(String, Json)]): Obj =
if (chunk.isEmpty) empty
else new Obj(chunk)

def apply(fields: (String, Json)*): Obj =
if (fields.isEmpty) Obj.empty
else new Obj(Chunk(fields: _*))

private lazy val objd = JsonDecoder.keyValueChunk[String, Json]
implicit val decoder: JsonDecoder[Obj] = new JsonDecoder[Obj] {
Expand Down Expand Up @@ -423,9 +429,15 @@ object Json {
override def mapArrayValues(f: Json => Json): Json.Arr = Json.Arr(elements.map(f))
}
object Arr {
val empty: Arr = Arr(Chunk.empty)
val empty: Arr = new Arr(Chunk.empty)

def apply(chunk: Chunk[Json]): Arr =
if (chunk.isEmpty) empty
else new Arr(chunk)

def apply(elements: Json*): Arr = Arr(Chunk(elements: _*))
def apply(elements: Json*): Arr =
if (elements.isEmpty) empty
else new Arr(Chunk(elements: _*))

private lazy val arrd = JsonDecoder.chunk[Json]
implicit val decoder: JsonDecoder[Arr] = new JsonDecoder[Arr] {
Expand Down Expand Up @@ -595,5 +607,7 @@ object Json {

implicit val codec: JsonCodec[Json] = JsonCodec(encoder, decoder)

def apply(fields: (String, Json)*): Json = Json.Obj(Chunk(fields: _*))
def apply(fields: (String, Json)*): Json =
if (fields.isEmpty) Obj.empty
else new Obj(Chunk(fields: _*))
}
11 changes: 11 additions & 0 deletions zio-json/shared/src/test/scala/zio/json/ast/JsonSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ object JsonSpec extends ZIOSpecDefault {

val spec: Spec[Environment, Any] =
suite("Json")(
suite("apply")(
test("()") {
assertTrue(Json.Obj.empty eq Json()) &&
assertTrue(Json.Obj.empty eq Json.Obj()) &&
assertTrue(Json.Arr.empty eq Json.Arr())
},
test("(Chunk.empty)") {
assertTrue(Json.Obj.empty eq Json.Obj(Chunk.empty)) &&
assertTrue(Json.Arr.empty eq Json.Arr(Chunk.empty))
}
),
suite("delete")(
suite("scalar")(
test("success") {
Expand Down

0 comments on commit 95e7f2e

Please sign in to comment.