Skip to content

Commit

Permalink
More efficient initialization of JSON decoders for case classes
Browse files Browse the repository at this point in the history
  • Loading branch information
plokhotnyuk committed Jan 11, 2025
1 parent a59764e commit c526e65
Showing 1 changed file with 19 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1621,33 +1621,40 @@ object JsonCodec {
private object CaseClassJsonDecoder {

def apply[Z](schema: Schema.Record[Z], discriminator: Option[String]): CaseClassJsonDecoder[Z] = {
val len = schema.fields.length
val hasDiscriminator = discriminator.isDefined
val len = schema.fields.length
var nameLen = len
if (hasDiscriminator) nameLen += 1
val aliasLen = schema.fields.foldLeft(0)(_ + _.nameAndAliases.size) - len
val fields = new Array[Schema.Field[Z, _]](len)
val decoders = new Array[ZJsonDecoder[_]](len)
val spans = Array.newBuilder[JsonError.ObjectAccess]
val names = Array.newBuilder[String]
val aliases = Array.newBuilder[(String, Int)]
val spans = new Array[JsonError.ObjectAccess](nameLen)
val names = new Array[String](nameLen)
val aliases = new Array[(String, Int)](aliasLen)
var idx = 0
var aliasIdx = 0
schema.fields.foreach { field =>
fields(idx) = field
decoders(idx) = schemaDecoder(field.schema)
val name = field.fieldName
names += name
spans += JsonError.ObjectAccess(name)
(field.nameAndAliases - name).foreach(a => aliases += ((a, idx)))
names(idx) = name
spans(idx) = JsonError.ObjectAccess(name)
(field.nameAndAliases - name).foreach { a =>
aliases(aliasIdx) = (a, idx)
aliasIdx += 1
}
idx += 1
}
val hasDiscriminator = discriminator.isDefined
if (hasDiscriminator) {
val discriminatorName = discriminator.get
names += discriminatorName
spans += JsonError.ObjectAccess(discriminatorName)
names(idx) = discriminatorName
spans(idx) = JsonError.ObjectAccess(discriminatorName)
}
new CaseClassJsonDecoder(
fields,
decoders,
spans.result(),
new StringMatrix(names.result(), aliases.result()),
spans,
new StringMatrix(names, aliases),
!hasDiscriminator,
!schema.annotations.exists(_.isInstanceOf[rejectExtraFields])
)
Expand Down

0 comments on commit c526e65

Please sign in to comment.