From 2189d28104dd2c558af54b614fae2e533bc9fa11 Mon Sep 17 00:00:00 2001 From: Michael Braun Date: Tue, 21 Apr 2020 00:46:13 +0000 Subject: [PATCH] scrooge-generator - Optimize Scrooge-generated Scala classes from thrift Problem Scala classes generated by Scrooge in Scala take a long time to compile and generate inefficient bytecode which can hurt likelihood of JVM inlining methods. Solution Remove 'match' which does not translate into a tableswitch in favor of if-else, remove most uses of implicit functions, shadow variables to generate smaller bytecode, eliminate some redundant methods, move common functionality around throwing exceptions into an internal ApplicationExceptions class. Result Compile times for Scrooge-generated Scala times are improved, and smaller bytecode is generated for key methods. JIRA Issues: CSL-8870 Differential Revision: https://phabricator.twitter.biz/D454297 --- CHANGELOG.rst | 3 + .../internal/ApplicationExceptions.scala | 42 + .../gold/thriftscala/AnotherException.scala | 151 +- .../test/gold/thriftscala/CollectionId.scala | 257 ++- .../GoldService$FinagleClient.scala | 128 +- .../GoldService$FinagleService.scala | 26 +- .../test/gold/thriftscala/GoldService.scala | 625 +++--- .../thriftscala/OverCapacityException.scala | 155 +- .../PlatinumService$FinagleClient.scala | 50 +- .../PlatinumService$FinagleService.scala | 2 +- .../gold/thriftscala/PlatinumService.scala | 458 ++--- .../test/gold/thriftscala/Recursive.scala | 350 ++-- .../test/gold/thriftscala/Request.scala | 1800 ++++++++--------- .../test/gold/thriftscala/RequestType.scala | 35 +- .../test/gold/thriftscala/Response.scala | 350 ++-- .../test/gold/thriftscala/ResponseUnion.scala | 79 +- .../src/main/resources/scalagen/enum.mustache | 36 +- .../resources/scalagen/finagleClient.mustache | 28 +- .../scalagen/finagleClientFunction.mustache | 50 +- .../scalagen/finagleService.mustache | 28 +- .../resources/scalagen/methodFilter.mustache | 46 +- .../scalagen/readAdaptField.mustache | 28 +- .../resources/scalagen/readField.mustache | 23 +- .../resources/scalagen/readLazyField.mustache | 29 +- .../main/resources/scalagen/readList.mustache | 4 +- .../main/resources/scalagen/readMap.mustache | 4 +- .../main/resources/scalagen/readSet.mustache | 6 +- .../scalagen/readUnionField.mustache | 14 +- .../main/resources/scalagen/service.mustache | 102 +- .../main/resources/scalagen/struct.mustache | 247 ++- .../main/resources/scalagen/union.mustache | 61 +- .../scalagen/withoutPassthrough.mustache | 10 +- .../resources/scalagen/writeField.mustache | 8 +- .../resources/scalagen/writeList.mustache | 25 +- .../scrooge/backend/ServiceTemplate.scala | 38 +- .../scrooge/backend/StructTemplate.scala | 30 + 36 files changed, 2500 insertions(+), 2828 deletions(-) create mode 100644 scrooge-core/src/main/scala/com/twitter/scrooge/internal/ApplicationExceptions.scala diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 7b38a5068..68f0457df 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -10,6 +10,9 @@ Unreleased * scrooge-generator: Respect the proper order of separators in function declarations. ``PHAB_ID=D467476`` +* scrooge-generator: Optimized generated Scala code for compile time and smaller bytecode. + Companion objects for thrift enum traits are no longer case objects. ``PHAB_ID=D454297`` + 20.4.0 ------ diff --git a/scrooge-core/src/main/scala/com/twitter/scrooge/internal/ApplicationExceptions.scala b/scrooge-core/src/main/scala/com/twitter/scrooge/internal/ApplicationExceptions.scala new file mode 100644 index 000000000..e8ff05f64 --- /dev/null +++ b/scrooge-core/src/main/scala/com/twitter/scrooge/internal/ApplicationExceptions.scala @@ -0,0 +1,42 @@ +package com.twitter.scrooge.internal + +import com.twitter.scrooge.ThriftStruct +import org.apache.thrift.TApplicationException +import org.apache.thrift.protocol.TProtocolException + +/** + * Internal helpers for Scrooge classes - should not be called by user code + */ +object ApplicationExceptions { + + /** + * Given a service name, return a TApplicationException of type MISSING_RESULT + * where the message includes the service name + * @param serviceName + * @return + */ + def missingResult(serviceName: String): TApplicationException = { + new TApplicationException( + TApplicationException.MISSING_RESULT, + serviceName + " failed: unknown result" + ) + } + + /** + * Given a message and the expected and actual type (byte representation), throws a + * TProtocolException - will call String.format on the message with the ttypeToString of the + * expected and actual type bytes as the two args. + * @param message + * @param expectedType + * @param actualType + */ + @throws[TProtocolException] + def throwWrongFieldTypeException(message: String, expectedType: Byte, actualType: Byte): Unit = { + throw new TProtocolException( + String.format( + message, + ThriftStruct.ttypeToString(expectedType), + ThriftStruct.ttypeToString(actualType))) + } + +} diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/AnotherException.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/AnotherException.scala index 25198facb..b50fccdc1 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/AnotherException.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/AnotherException.scala @@ -30,7 +30,7 @@ object AnotherException extends ValidatingThriftStructCodec3[AnotherException] w val NoPassthroughFields: immutable$Map[Short, TFieldBlob] = immutable$Map.empty[Short, TFieldBlob] val Struct: TStruct = new TStruct("AnotherException") val ErrorCodeField: TField = new TField("errorCode", TType.I32, 1) - val ErrorCodeFieldManifest: Manifest[Int] = implicitly[Manifest[Int]] + val ErrorCodeFieldManifest: Manifest[Int] = manifest[Int] /** * Field information in declaration order. @@ -49,26 +49,25 @@ object AnotherException extends ValidatingThriftStructCodec3[AnotherException] w ) ) - lazy val structAnnotations: immutable$Map[String, String] = + + val structAnnotations: immutable$Map[String, String] = immutable$Map.empty[String, String] - private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq( + private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq[ClassTag[_]]( classTag[Int].asInstanceOf[ClassTag[_]] ) - private[this] val structFields: Seq[ThriftStructField[AnotherException]] = { - Seq( - new ThriftStructField[AnotherException]( - ErrorCodeField, - _root_.scala.Some(ErrorCodeFieldManifest), - classOf[AnotherException]) { - def getValue[R](struct: AnotherException): R = struct.errorCode.asInstanceOf[R] - } - ) - } + private[this] val structFields: Seq[ThriftStructField[AnotherException]] = Seq[ThriftStructField[AnotherException]]( + new ThriftStructField[AnotherException]( + ErrorCodeField, + _root_.scala.Some(ErrorCodeFieldManifest), + classOf[AnotherException]) { + def getValue[R](struct: AnotherException): R = struct.errorCode.asInstanceOf[R] + } + ) override lazy val metaData: ThriftStructMetaData[AnotherException] = - new ThriftStructMetaData(this, structFields, fieldInfos, Seq(), structAnnotations) + new ThriftStructMetaData(this, structFields, fieldInfos, Nil, structAnnotations) /** * Checks that all required fields are non-null. @@ -89,11 +88,7 @@ object AnotherException extends ValidatingThriftStructCodec3[AnotherException] w def withoutPassthroughFields(original: AnotherException): AnotherException = new AnotherException( - errorCode = - { - val field = original.errorCode - field - } + errorCode = original.errorCode ) def newBuilder(): StructBuilder[AnotherException] = new AnotherExceptionStructBuilder(_root_.scala.None, fieldTypes) @@ -109,38 +104,36 @@ object AnotherException extends ValidatingThriftStructCodec3[AnotherException] w var _done = false _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 1 => - _field.`type` match { - case TType.I32 => - errorCode = readErrorCodeValue(_iprot) - case _actualType => - val _expectedType = TType.I32 - throw new TProtocolException( - "Received wrong type for field 'errorCode' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I32) { + errorCode = readErrorCodeValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'errorCode' (expected=%s, actual=%s).", + TType.I32, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() new AnotherException( errorCode, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() @@ -216,37 +209,33 @@ class AnotherException( * is known and not optional and set to None, then the field is serialized and returned. */ def getFieldBlob(_fieldId: Short): _root_.scala.Option[TFieldBlob] = { - lazy val _buff = new TMemoryBuffer(32) - lazy val _oprot = new TCompactProtocol(_buff) - _passthroughFields.get(_fieldId) match { - case blob: _root_.scala.Some[TFieldBlob] => blob - case _root_.scala.None => { - val _fieldOpt: _root_.scala.Option[TField] = - _fieldId match { - case 1 => - if (true) { - writeErrorCodeValue(errorCode, _oprot) - _root_.scala.Some(AnotherException.ErrorCodeField) - } else { - _root_.scala.None - } - case _ => _root_.scala.None - } - _fieldOpt match { - case _root_.scala.Some(_field) => - _root_.scala.Some(TFieldBlob(_field, Buf.ByteArray.Owned(_buff.getArray()))) - case _root_.scala.None => - _root_.scala.None - } + val passedthroughValue = _passthroughFields.get(_fieldId) + if (passedthroughValue.isDefined) { + passedthroughValue + } else { + val _buff = new TMemoryBuffer(32) + val _oprot = new TCompactProtocol(_buff) + + val _fieldOpt: _root_.scala.Option[TField] = _fieldId match { + case 1 => + writeErrorCodeValue(errorCode, _oprot) + _root_.scala.Some(AnotherException.ErrorCodeField) + case _ => _root_.scala.None + } + if (_fieldOpt.isDefined) { + _root_.scala.Some(TFieldBlob(_fieldOpt.get, Buf.ByteArray.Owned(_buff.getArray))) + } else { + _root_.scala.None } } } + /** * Collects TCompactProtocol-encoded field values according to `getFieldBlob` into a map. */ def getFieldBlobs(ids: TraversableOnce[Short]): immutable$Map[Short, TFieldBlob] = - (ids flatMap { id => getFieldBlob(id) map { id -> _ } }).toMap + (ids.flatMap { id => getFieldBlob(id).map { fieldBlob => (id, fieldBlob) } }).toMap /** * Sets a field using a TCompactProtocol-encoded binary blob. If the field is a known @@ -260,7 +249,7 @@ class AnotherException( _blob.id match { case 1 => errorCode = readErrorCodeValue(_blob.read) - case _ => _passthroughFields += (_blob.id -> _blob) + case _ => _passthroughFields += _root_.scala.Tuple2(_blob.id, _blob) } new AnotherException( errorCode, @@ -317,15 +306,14 @@ class AnotherException( override def canEqual(other: Any): Boolean = other.isInstanceOf[AnotherException] - private def _equals(x: AnotherException, y: AnotherException): Boolean = - x.productArity == y.productArity && - x.productIterator.sameElements(y.productIterator) && - x.flags == y.flags && - x._passthroughFields == y._passthroughFields + private[this] def _equals(other: AnotherException): Boolean = + this.productArity == other.productArity && + this.productIterator.sameElements(other.productIterator) && + this.flags == other.flags && + this._passthroughFields == other._passthroughFields override def equals(other: Any): Boolean = - canEqual(other) && - _equals(this, other.asInstanceOf[AnotherException]) + canEqual(other) && _equals(other.asInstanceOf[AnotherException]) override def hashCode: Int = { 31 * _root_.scala.runtime.ScalaRunTime._hashCode(this) + @@ -334,14 +322,6 @@ class AnotherException( override def toString: String = _root_.scala.runtime.ScalaRunTime._toString(this) - - override def productArity: Int = 1 - - override def productElement(n: Int): Any = n match { - case 0 => this.errorCode - case _ => throw new IndexOutOfBoundsException(n.toString) - } - override def productPrefix: String = "AnotherException" def _codec: ValidatingThriftStructCodec3[AnotherException] = AnotherException @@ -359,18 +339,19 @@ class AnotherException( private[thriftscala] class AnotherExceptionStructBuilder(instance: _root_.scala.Option[AnotherException], fieldTypes: IndexedSeq[ClassTag[_]]) extends StructBuilder[AnotherException](fieldTypes) { - def build(): AnotherException = instance match { - case _root_.scala.Some(i) => + def build(): AnotherException = { + val _fieldArray = fieldArray // shadow variable + if (instance.isDefined) { + val instanceValue = instance.get AnotherException( - (if (fieldArray(0) == null) i.errorCode else fieldArray(0)).asInstanceOf[Int] + if (_fieldArray(0) == null) instanceValue.errorCode else _fieldArray(0).asInstanceOf[Int] + ) + } else { + if (genericArrayOps(_fieldArray).contains(null)) throw new InvalidFieldsException(structBuildError("AnotherException")) + AnotherException( + _fieldArray(0).asInstanceOf[Int] ) - case _root_.scala.None => - if (fieldArray.contains(null)) throw new InvalidFieldsException(structBuildError("AnotherException")) - else { - AnotherException( - fieldArray(0).asInstanceOf[Int] - ) - } } + } } diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/CollectionId.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/CollectionId.scala index 5e9d2d0d5..a63ab83a8 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/CollectionId.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/CollectionId.scala @@ -33,7 +33,7 @@ object CollectionId extends ValidatingThriftStructCodec3[CollectionId] with Stru val NoPassthroughFields: immutable$Map[Short, TFieldBlob] = immutable$Map.empty[Short, TFieldBlob] val Struct: TStruct = new TStruct("CollectionId") val CollectionLongIdField: TField = new TField("collectionLongId", TType.I64, 1) - val CollectionLongIdFieldManifest: Manifest[Long] = implicitly[Manifest[Long]] + val CollectionLongIdFieldManifest: Manifest[Long] = manifest[Long] /** * Field information in declaration order. @@ -52,26 +52,25 @@ object CollectionId extends ValidatingThriftStructCodec3[CollectionId] with Stru ) ) - lazy val structAnnotations: immutable$Map[String, String] = + + val structAnnotations: immutable$Map[String, String] = immutable$Map.empty[String, String] - private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq( + private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq[ClassTag[_]]( classTag[Long].asInstanceOf[ClassTag[_]] ) - private[this] val structFields: Seq[ThriftStructField[CollectionId]] = { - Seq( - new ThriftStructField[CollectionId]( - CollectionLongIdField, - _root_.scala.Some(CollectionLongIdFieldManifest), - classOf[CollectionId]) { - def getValue[R](struct: CollectionId): R = struct.collectionLongId.asInstanceOf[R] - } - ) - } + private[this] val structFields: Seq[ThriftStructField[CollectionId]] = Seq[ThriftStructField[CollectionId]]( + new ThriftStructField[CollectionId]( + CollectionLongIdField, + _root_.scala.Some(CollectionLongIdFieldManifest), + classOf[CollectionId]) { + def getValue[R](struct: CollectionId): R = struct.collectionLongId.asInstanceOf[R] + } + ) override lazy val metaData: ThriftStructMetaData[CollectionId] = - new ThriftStructMetaData(this, structFields, fieldInfos, Seq(), structAnnotations) + new ThriftStructMetaData(this, structFields, fieldInfos, Nil, structAnnotations) /** * Checks that all required fields are non-null. @@ -92,11 +91,7 @@ object CollectionId extends ValidatingThriftStructCodec3[CollectionId] with Stru def withoutPassthroughFields(original: CollectionId): CollectionId = new Immutable( - collectionLongId = - { - val field = original.collectionLongId - field - } + collectionLongId = original.collectionLongId ) def newBuilder(): StructBuilder[CollectionId] = new CollectionIdStructBuilder(_root_.scala.None, fieldTypes) @@ -119,7 +114,7 @@ object CollectionId extends ValidatingThriftStructCodec3[CollectionId] with Stru val adaptContext = _iprot.adaptContext val reloadRequired = adaptContext.shouldReloadDecoder synchronized { - if (adaptiveDecoder == null || reloadRequired) { + if ((adaptiveDecoder eq null) || reloadRequired) { adaptiveDecoder = adaptContext.buildDecoder(this, fallbackDecoder, accessRecordingDecoderBuilder) } } @@ -150,35 +145,32 @@ object CollectionId extends ValidatingThriftStructCodec3[CollectionId] with Stru val _start_offset = _iprot.offset _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 1 => - _field.`type` match { - case TType.I64 => - - collectionLongId = readCollectionLongIdValue(_iprot) - _got_collectionLongId = true - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'collectionLongId' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + collectionLongId = readCollectionLongIdValue(_iprot) + _got_collectionLongId = true + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'collectionLongId' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() if (!_got_collectionLongId) throw new TProtocolException("Required field 'collectionLongId' was not found in serialized data for struct CollectionId") @@ -188,19 +180,22 @@ object CollectionId extends ValidatingThriftStructCodec3[CollectionId] with Stru _start_offset, _iprot.offset, collectionLongId, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() ) } - override def decode(_iprot: TProtocol): CollectionId = - _iprot match { - case i: AdaptTProtocol => adaptiveDecode(i) - case i: LazyTProtocol => lazyDecode(i) - case i => eagerDecode(i) + override def decode(_iprot: TProtocol): CollectionId = { + if (_iprot.isInstanceOf[LazyTProtocol]) { + lazyDecode(_iprot.asInstanceOf[LazyTProtocol]) + } else if (_iprot.isInstanceOf[AdaptTProtocol]) { + adaptiveDecode(_iprot.asInstanceOf[AdaptTProtocol]) + } else { + eagerDecode(_iprot) } + } private[thriftscala] def eagerDecode(_iprot: TProtocol): CollectionId = { var collectionLongId: Long = 0L @@ -209,40 +204,38 @@ object CollectionId extends ValidatingThriftStructCodec3[CollectionId] with Stru var _done = false _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 1 => - _field.`type` match { - case TType.I64 => - collectionLongId = readCollectionLongIdValue(_iprot) - _got_collectionLongId = true - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'collectionLongId' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + collectionLongId = readCollectionLongIdValue(_iprot) + _got_collectionLongId = true + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'collectionLongId' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() if (!_got_collectionLongId) throw new TProtocolException("Required field 'collectionLongId' was not found in serialized data for struct CollectionId") new Immutable( collectionLongId, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() @@ -311,9 +304,10 @@ object CollectionId extends ValidatingThriftStructCodec3[CollectionId] with Stru extends CollectionId { override def write(_oprot: TProtocol): Unit = { - _oprot match { - case i: LazyTProtocol => i.writeRaw(_buf, _start_offset, _end_offset - _start_offset) - case _ => super.write(_oprot) + if (_oprot.isInstanceOf[LazyTProtocol]) { + _oprot.asInstanceOf[LazyTProtocol].writeRaw(_buf, _start_offset, _end_offset - _start_offset) + } else { + super.write(_oprot) } } @@ -329,7 +323,7 @@ object CollectionId extends ValidatingThriftStructCodec3[CollectionId] with Stru * With the class private and the contract that we throw away our mutable references * having the hash code lazy here is safe. */ - override lazy val hashCode = super.hashCode + override lazy val hashCode: Int = super.hashCode } /** @@ -369,37 +363,33 @@ trait CollectionId * is known and not optional and set to None, then the field is serialized and returned. */ def getFieldBlob(_fieldId: Short): _root_.scala.Option[TFieldBlob] = { - lazy val _buff = new TMemoryBuffer(32) - lazy val _oprot = new TCompactProtocol(_buff) - _passthroughFields.get(_fieldId) match { - case blob: _root_.scala.Some[TFieldBlob] => blob - case _root_.scala.None => { - val _fieldOpt: _root_.scala.Option[TField] = - _fieldId match { - case 1 => - if (true) { - writeCollectionLongIdValue(collectionLongId, _oprot) - _root_.scala.Some(CollectionId.CollectionLongIdField) - } else { - _root_.scala.None - } - case _ => _root_.scala.None - } - _fieldOpt match { - case _root_.scala.Some(_field) => - _root_.scala.Some(TFieldBlob(_field, Buf.ByteArray.Owned(_buff.getArray()))) - case _root_.scala.None => - _root_.scala.None - } + val passedthroughValue = _passthroughFields.get(_fieldId) + if (passedthroughValue.isDefined) { + passedthroughValue + } else { + val _buff = new TMemoryBuffer(32) + val _oprot = new TCompactProtocol(_buff) + + val _fieldOpt: _root_.scala.Option[TField] = _fieldId match { + case 1 => + writeCollectionLongIdValue(collectionLongId, _oprot) + _root_.scala.Some(CollectionId.CollectionLongIdField) + case _ => _root_.scala.None + } + if (_fieldOpt.isDefined) { + _root_.scala.Some(TFieldBlob(_fieldOpt.get, Buf.ByteArray.Owned(_buff.getArray))) + } else { + _root_.scala.None } } } + /** * Collects TCompactProtocol-encoded field values according to `getFieldBlob` into a map. */ def getFieldBlobs(ids: TraversableOnce[Short]): immutable$Map[Short, TFieldBlob] = - (ids flatMap { id => getFieldBlob(id) map { id -> _ } }).toMap + (ids.flatMap { id => getFieldBlob(id).map { fieldBlob => (id, fieldBlob) } }).toMap /** * Sets a field using a TCompactProtocol-encoded binary blob. If the field is a known @@ -413,7 +403,7 @@ trait CollectionId _blob.id match { case 1 => collectionLongId = readCollectionLongIdValue(_blob.read) - case _ => _passthroughFields += (_blob.id -> _blob) + case _ => _passthroughFields += _root_.scala.Tuple2(_blob.id, _blob) } new Immutable( collectionLongId, @@ -470,14 +460,13 @@ trait CollectionId override def canEqual(other: Any): Boolean = other.isInstanceOf[CollectionId] - private def _equals(x: CollectionId, y: CollectionId): Boolean = - x.productArity == y.productArity && - x.productIterator.sameElements(y.productIterator) && - x._passthroughFields == y._passthroughFields + private[this] def _equals(other: CollectionId): Boolean = + this.productArity == other.productArity && + this.productIterator.sameElements(other.productIterator) && + this._passthroughFields == other._passthroughFields override def equals(other: Any): Boolean = - canEqual(other) && - _equals(this, other.asInstanceOf[CollectionId]) + canEqual(other) && _equals(other.asInstanceOf[CollectionId]) override def hashCode: Int = { _root_.scala.runtime.ScalaRunTime._hashCode(this) @@ -485,14 +474,6 @@ trait CollectionId override def toString: String = _root_.scala.runtime.ScalaRunTime._toString(this) - - override def productArity: Int = 1 - - override def productElement(n: Int): Any = n match { - case 0 => this.collectionLongId - case _ => throw new IndexOutOfBoundsException(n.toString) - } - override def productPrefix: String = "CollectionId" def _codec: ValidatingThriftStructCodec3[CollectionId] = CollectionId @@ -503,19 +484,20 @@ trait CollectionId private[thriftscala] class CollectionIdStructBuilder(instance: _root_.scala.Option[CollectionId], fieldTypes: IndexedSeq[ClassTag[_]]) extends StructBuilder[CollectionId](fieldTypes) { - def build(): CollectionId = instance match { - case _root_.scala.Some(i) => + def build(): CollectionId = { + val _fieldArray = fieldArray // shadow variable + if (instance.isDefined) { + val instanceValue = instance.get CollectionId( - (if (fieldArray(0) == null) i.collectionLongId else fieldArray(0)).asInstanceOf[Long] + if (_fieldArray(0) == null) instanceValue.collectionLongId else _fieldArray(0).asInstanceOf[Long] + ) + } else { + if (genericArrayOps(_fieldArray).contains(null)) throw new InvalidFieldsException(structBuildError("CollectionId")) + CollectionId( + _fieldArray(0).asInstanceOf[Long] ) - case _root_.scala.None => - if (fieldArray.contains(null)) throw new InvalidFieldsException(structBuildError("CollectionId")) - else { - CollectionId( - fieldArray(0).asInstanceOf[Long] - ) - } } + } } private class CollectionId__AdaptDecoder { @@ -536,44 +518,46 @@ private class CollectionId__AdaptDecoder { AdaptTProtocol.usedEndMarker(1) _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() + val _fieldType = _field.`type` if (_field.`type` == TType.STOP) { _done = true } else { _field.id match { case 1 => { - _field.`type` match { - case TType.I64 => - AdaptTProtocol.usedStartMarker(1) - collectionLongId = CollectionId.readCollectionLongIdValue(_iprot) - AdaptTProtocol.usedEndMarker(1) - AdaptTProtocol.unusedStartMarker(1) - _iprot.offsetSkipI64() - AdaptTProtocol.unusedEndMarker(1) - _got_collectionLongId = true - case _actualType => - val _expectedType = TType.I64 - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "collectionLongId") + if (_fieldType == TType.I64) { + AdaptTProtocol.usedStartMarker(1) + collectionLongId = CollectionId.readCollectionLongIdValue(_iprot) + AdaptTProtocol.usedEndMarker(1) + AdaptTProtocol.unusedStartMarker(1) + _iprot.offsetSkipI64() + AdaptTProtocol.unusedEndMarker(1) + _got_collectionLongId = true + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.I64, + _fieldType, + "collectionLongId" + ) } AdaptTProtocol.usedStartMarker(1) adapt.set_collectionLongId(collectionLongId) AdaptTProtocol.usedEndMarker(1) } - case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() if (!_got_collectionLongId) throw new TProtocolException("Required field 'collectionLongId' was not found in serialized data for struct CollectionId") adapt.set__endOffset(_iprot.offset) - if (_passthroughFields != null) { + if (_passthroughFields ne null) { adapt.set__passthroughFields(_passthroughFields.result()) } adapt @@ -607,7 +591,7 @@ private class CollectionId__Adapt( private[this] var _end_offset: Int = _ - def set__endOffset(offset: Int) = _end_offset = offset + def set__endOffset(offset: Int): Unit = _end_offset = offset private[this] var __passthroughFields: immutable$Map[Short, TFieldBlob] = CollectionId.NoPassthroughFields def set__passthroughFields(passthroughFields: immutable$Map[Short, TFieldBlob]): Unit = @@ -629,9 +613,10 @@ private class CollectionId__Adapt( override lazy val hashCode: Int = super.hashCode override def write(_oprot: TProtocol): Unit = { - _oprot match { - case i: AdaptTProtocol => i.writeRaw(_buf, _start_offset, _end_offset - _start_offset) - case _ => super.write(_oprot) + if (_oprot.isInstanceOf[AdaptTProtocol]) { + _oprot.asInstanceOf[AdaptTProtocol].writeRaw(_buf, _start_offset, _end_offset - _start_offset) + } else { + super.write(_oprot) } } } diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/GoldService$FinagleClient.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/GoldService$FinagleClient.scala index 8cefaa4ba..0f316394c 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/GoldService$FinagleClient.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/GoldService$FinagleClient.scala @@ -56,7 +56,7 @@ class GoldService$FinagleClient( oprot.writeMessageBegin(new TMessage(name, TMessageType.CALL, 0)) args.write(oprot) oprot.writeMessageEnd() - oprot.getTransport().flush() + oprot.getTransport.flush() val bytes = _root_.java.util.Arrays.copyOfRange( memoryBuffer.getArray(), 0, @@ -78,12 +78,8 @@ class GoldService$FinagleClient( val msg = iprot.readMessageBegin() try { if (msg.`type` == TMessageType.EXCEPTION) { - val exception = TApplicationException.readFrom(iprot) match { - case sourced: _root_.com.twitter.finagle.SourcedException => - if (serviceName != "") sourced.serviceName = serviceName - sourced - case e => e - } + val exception = TApplicationException.readFrom(iprot) + setServiceName(exception) throw exception } else { codec.decode(iprot) @@ -93,24 +89,10 @@ class GoldService$FinagleClient( } } - protected def missingResult(name: String): TApplicationException = { - new TApplicationException( - TApplicationException.MISSING_RESULT, - name + " failed: unknown result" - ) + protected def setServiceName(ex: Throwable): Throwable = { + _root_.com.twitter.finagle.SourcedException.setServiceName(ex, serviceName) } - protected def setServiceName(ex: Throwable): Throwable = - if (this.serviceName == "") ex - else { - ex match { - case se: _root_.com.twitter.finagle.SourcedException => - se.serviceName = this.serviceName - se - case _ => ex - } - } - // ----- end boilerplate. private[this] def stats: StatsReceiver = clientParam.clientStats @@ -118,21 +100,21 @@ class GoldService$FinagleClient( private[this] val scopedStats: StatsReceiver = if (serviceName != "") stats.scope(serviceName) else stats private[this] object __stats_doGreatThings { - val RequestsCounter = scopedStats.scope("doGreatThings").counter("requests") - val SuccessCounter = scopedStats.scope("doGreatThings").counter("success") - val FailuresCounter = scopedStats.scope("doGreatThings").counter("failures") - val FailuresScope = scopedStats.scope("doGreatThings").scope("failures") + val RequestsCounter: _root_.com.twitter.finagle.stats.Counter = scopedStats.scope("doGreatThings").counter("requests") + val SuccessCounter: _root_.com.twitter.finagle.stats.Counter = scopedStats.scope("doGreatThings").counter("success") + val FailuresCounter: _root_.com.twitter.finagle.stats.Counter = scopedStats.scope("doGreatThings").counter("failures") + val FailuresScope: StatsReceiver = scopedStats.scope("doGreatThings").scope("failures") } val doGreatThingsGoldServiceReplyDeserializer: Array[Byte] => _root_.com.twitter.util.Try[com.twitter.scrooge.test.gold.thriftscala.Response] = { response: Array[Byte] => { - val result = decodeResponse(response, DoGreatThings.Result) - - result.firstException() match { - case Some(exception) => _root_.com.twitter.util.Throw(setServiceName(exception)) - case _ => result.successField match { - case Some(success) => _root_.com.twitter.util.Return(success) - case _ => _root_.com.twitter.util.Throw(missingResult("doGreatThings")) - } + val result: DoGreatThings.Result = decodeResponse(response, DoGreatThings.Result) + val firstException = result.firstException() + if (firstException.isDefined) { + _root_.com.twitter.util.Throw(setServiceName(firstException.get)) + } else if (result.successField.isDefined) { + _root_.com.twitter.util.Return(result.successField.get) + } else { + _root_.com.twitter.util.Throw(_root_.com.twitter.scrooge.internal.ApplicationExceptions.missingResult("doGreatThings")) } } } @@ -155,42 +137,38 @@ class GoldService$FinagleClient( this.service(serialized).flatMap { response => Future.const(serdeCtx.deserialize(response)) }.respond { response => - val responseClass = responseClassifier.applyOrElse( + val classified = responseClassifier.applyOrElse( ctfs.ReqRep(inputArgs, response), ctfs.ResponseClassifier.Default) - responseClass match { - case ctfs.ResponseClass.Ignorable => // Do nothing. - case ctfs.ResponseClass.Successful(_) => - __stats_doGreatThings.SuccessCounter.incr() - case ctfs.ResponseClass.Failed(_) => - __stats_doGreatThings.FailuresCounter.incr() - response match { - case _root_.com.twitter.util.Throw(ex) => - setServiceName(ex) - __stats_doGreatThings.FailuresScope.counter( - _root_.com.twitter.util.Throwables.mkString(ex): _*).incr() - case _ => - } - } + if (classified.isInstanceOf[ctfs.ResponseClass.Successful]) { + __stats_doGreatThings.SuccessCounter.incr() + } else if (classified.isInstanceOf[ctfs.ResponseClass.Failed]) { + __stats_doGreatThings.FailuresCounter.incr() + if (response.isThrow) { + setServiceName(response.throwable) + __stats_doGreatThings.FailuresScope.counter( + _root_.com.twitter.util.Throwables.mkString(response.throwable): _*).incr() + } + } // Last ResponseClass is Ignorable, which we do not need to record } } } private[this] object __stats_noExceptionCall { - val RequestsCounter = scopedStats.scope("noExceptionCall").counter("requests") - val SuccessCounter = scopedStats.scope("noExceptionCall").counter("success") - val FailuresCounter = scopedStats.scope("noExceptionCall").counter("failures") - val FailuresScope = scopedStats.scope("noExceptionCall").scope("failures") + val RequestsCounter: _root_.com.twitter.finagle.stats.Counter = scopedStats.scope("noExceptionCall").counter("requests") + val SuccessCounter: _root_.com.twitter.finagle.stats.Counter = scopedStats.scope("noExceptionCall").counter("success") + val FailuresCounter: _root_.com.twitter.finagle.stats.Counter = scopedStats.scope("noExceptionCall").counter("failures") + val FailuresScope: StatsReceiver = scopedStats.scope("noExceptionCall").scope("failures") } val noExceptionCallGoldServiceReplyDeserializer: Array[Byte] => _root_.com.twitter.util.Try[com.twitter.scrooge.test.gold.thriftscala.Response] = { response: Array[Byte] => { - val result = decodeResponse(response, NoExceptionCall.Result) - - result.firstException() match { - case Some(exception) => _root_.com.twitter.util.Throw(setServiceName(exception)) - case _ => result.successField match { - case Some(success) => _root_.com.twitter.util.Return(success) - case _ => _root_.com.twitter.util.Throw(missingResult("noExceptionCall")) - } + val result: NoExceptionCall.Result = decodeResponse(response, NoExceptionCall.Result) + val firstException = result.firstException() + if (firstException.isDefined) { + _root_.com.twitter.util.Throw(setServiceName(firstException.get)) + } else if (result.successField.isDefined) { + _root_.com.twitter.util.Return(result.successField.get) + } else { + _root_.com.twitter.util.Throw(_root_.com.twitter.scrooge.internal.ApplicationExceptions.missingResult("noExceptionCall")) } } } @@ -213,23 +191,19 @@ class GoldService$FinagleClient( this.service(serialized).flatMap { response => Future.const(serdeCtx.deserialize(response)) }.respond { response => - val responseClass = responseClassifier.applyOrElse( + val classified = responseClassifier.applyOrElse( ctfs.ReqRep(inputArgs, response), ctfs.ResponseClassifier.Default) - responseClass match { - case ctfs.ResponseClass.Ignorable => // Do nothing. - case ctfs.ResponseClass.Successful(_) => - __stats_noExceptionCall.SuccessCounter.incr() - case ctfs.ResponseClass.Failed(_) => - __stats_noExceptionCall.FailuresCounter.incr() - response match { - case _root_.com.twitter.util.Throw(ex) => - setServiceName(ex) - __stats_noExceptionCall.FailuresScope.counter( - _root_.com.twitter.util.Throwables.mkString(ex): _*).incr() - case _ => - } - } + if (classified.isInstanceOf[ctfs.ResponseClass.Successful]) { + __stats_noExceptionCall.SuccessCounter.incr() + } else if (classified.isInstanceOf[ctfs.ResponseClass.Failed]) { + __stats_noExceptionCall.FailuresCounter.incr() + if (response.isThrow) { + setServiceName(response.throwable) + __stats_noExceptionCall.FailuresScope.counter( + _root_.com.twitter.util.Throwables.mkString(response.throwable): _*).incr() + } + } // Last ResponseClass is Ignorable, which we do not need to record } } } diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/GoldService$FinagleService.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/GoldService$FinagleService.scala index c1b23c933..948174157 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/GoldService$FinagleService.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/GoldService$FinagleService.scala @@ -51,7 +51,7 @@ class GoldService$FinagleService( ) = this(iface, protocolFactory, NullStatsReceiver, Thrift.param.maxThriftBufferSize) def serviceName: String = serverParam.serviceName - private[this] val filters = new Filter(serverParam) + private[this] val filters: Filter = new Filter(serverParam) private[this] def protocolFactory: TProtocolFactory = serverParam.restrictedProtocolFactory @@ -63,25 +63,27 @@ class GoldService$FinagleService( } final def apply(request: Array[Byte]): Future[Array[Byte]] = { - val inputTransport = new TMemoryInputTransport(request) - val iprot = protocolFactory.getProtocol(inputTransport) + val iprot = protocolFactory.getProtocol(new TMemoryInputTransport(request)) try { val msg = iprot.readMessageBegin() - val service = serviceMap.get(msg.name) - service match { - case _root_.scala.Some(svc) => - svc((iprot, msg.seqid)) - case _ => - TProtocolUtil.skip(iprot, TType.STRUCT) - Future.value(Buf.ByteArray.Owned.extract( - filters.exception(msg.name, msg.seqid, TApplicationException.UNKNOWN_METHOD, - "Invalid method name: '" + msg.name + "'"))) + val svcOpt = serviceMap.get(msg.name) + if (svcOpt.isDefined) { + svcOpt.get.apply((iprot, msg.seqid)) + } else { + TProtocolUtil.skip(iprot, TType.STRUCT) + invalidMethodNameFuture(msg) } } catch { case e: Exception => Future.exception(e) } } + + private[this] def invalidMethodNameFuture(msg: TMessage): Future[Array[Byte]] = { + Future.value(Buf.ByteArray.Owned.extract( + filters.exception(msg.name, msg.seqid, TApplicationException.UNKNOWN_METHOD, + "Invalid method name: '" + msg.name + "'"))) + } // ---- end boilerplate. addService("doGreatThings", { diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/GoldService.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/GoldService.scala index c98e5859b..dd85065a1 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/GoldService.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/GoldService.scala @@ -51,7 +51,7 @@ trait GoldService[+MM[_]] extends _root_.com.twitter.finagle.thrift.ThriftServic object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftService { self => val annotations: immutable$Map[String, String] = immutable$Map( - "an.annotation" -> "true" + ("an.annotation", "true") ) val methods: immutable$Set[ThriftMethod] = immutable$Set( @@ -200,13 +200,15 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ } def unsafeBuildFromMethods(methods: immutable$Map[ThriftMethod, _root_.com.twitter.finagle.Service[_root_.com.twitter.scrooge.Request[_], _root_.com.twitter.scrooge.Response[_]]]): ReqRepServicePerEndpoint = { - val doGreatThings = methods.get(self.DoGreatThings) match { - case Some(impl) => impl.asInstanceOf[self.DoGreatThings.ReqRepServicePerEndpointServiceType] - case _ => throw new IllegalArgumentException(s"No implementation found for method DoGreatThings in ${methods.keySet}") + val doGreatThings = { + val doGreatThingsOpt = methods.get(self.DoGreatThings) + if (doGreatThingsOpt.isEmpty) throw new IllegalArgumentException(_root_.java.lang.String.format("No implementation found for method DoGreatThings in %s", methods.keySet)) + doGreatThingsOpt.get.asInstanceOf[self.DoGreatThings.ReqRepServicePerEndpointServiceType] } - val noExceptionCall = methods.get(self.NoExceptionCall) match { - case Some(impl) => impl.asInstanceOf[self.NoExceptionCall.ReqRepServicePerEndpointServiceType] - case _ => throw new IllegalArgumentException(s"No implementation found for method NoExceptionCall in ${methods.keySet}") + val noExceptionCall = { + val noExceptionCallOpt = methods.get(self.NoExceptionCall) + if (noExceptionCallOpt.isEmpty) throw new IllegalArgumentException(_root_.java.lang.String.format("No implementation found for method NoExceptionCall in %s", methods.keySet)) + noExceptionCallOpt.get.asInstanceOf[self.NoExceptionCall.ReqRepServicePerEndpointServiceType] } ReqRepServicePerEndpoint(doGreatThings, noExceptionCall) @@ -289,7 +291,7 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ val NoPassthroughFields: immutable$Map[Short, TFieldBlob] = immutable$Map.empty[Short, TFieldBlob] val Struct: TStruct = new TStruct("doGreatThings_args") val RequestField: TField = new TField("request", TType.STRUCT, 1) - val RequestFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Request] = implicitly[Manifest[com.twitter.scrooge.test.gold.thriftscala.Request]] + val RequestFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Request] = manifest[com.twitter.scrooge.test.gold.thriftscala.Request] /** * Field information in declaration order. @@ -308,26 +310,25 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ ) ) - lazy val structAnnotations: immutable$Map[String, String] = + + val structAnnotations: immutable$Map[String, String] = immutable$Map.empty[String, String] - private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq( + private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq[ClassTag[_]]( classTag[com.twitter.scrooge.test.gold.thriftscala.Request].asInstanceOf[ClassTag[_]] ) - private[this] val structFields: Seq[ThriftStructField[Args]] = { - Seq( - new ThriftStructField[Args]( - RequestField, - _root_.scala.Some(RequestFieldManifest), - classOf[Args]) { - def getValue[R](struct: Args): R = struct.request.asInstanceOf[R] - } - ) - } + private[this] val structFields: Seq[ThriftStructField[Args]] = Seq[ThriftStructField[Args]]( + new ThriftStructField[Args]( + RequestField, + _root_.scala.Some(RequestFieldManifest), + classOf[Args]) { + def getValue[R](struct: Args): R = struct.request.asInstanceOf[R] + } + ) override lazy val metaData: ThriftStructMetaData[Args] = - new ThriftStructMetaData(this, structFields, fieldInfos, Seq(), structAnnotations) + new ThriftStructMetaData(this, structFields, fieldInfos, Nil, structAnnotations) /** * Checks that all required fields are non-null. @@ -368,38 +369,36 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ var _done = false _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 1 => - _field.`type` match { - case TType.STRUCT => - request = readRequestValue(_iprot) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'request' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + request = readRequestValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'request' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() new Args( request, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() @@ -476,14 +475,13 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ override def canEqual(other: Any): Boolean = other.isInstanceOf[Args] - private def _equals(x: Args, y: Args): Boolean = - x.productArity == y.productArity && - x.productIterator.sameElements(y.productIterator) && - x._passthroughFields == y._passthroughFields + private[this] def _equals(other: Args): Boolean = + this.productArity == other.productArity && + this.productIterator.sameElements(other.productIterator) && + this._passthroughFields == other._passthroughFields override def equals(other: Any): Boolean = - canEqual(other) && - _equals(this, other.asInstanceOf[Args]) + canEqual(other) && _equals(other.asInstanceOf[Args]) override def hashCode: Int = { _root_.scala.runtime.ScalaRunTime._hashCode(this) @@ -491,14 +489,6 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ override def toString: String = _root_.scala.runtime.ScalaRunTime._toString(this) - - override def productArity: Int = 1 - - override def productElement(n: Int): Any = n match { - case 0 => this.request - case _ => throw new IndexOutOfBoundsException(n.toString) - } - override def productPrefix: String = "Args" def _codec: ValidatingThriftStructCodec3[Args] = Args @@ -509,19 +499,20 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ private[thriftscala] class ArgsStructBuilder(instance: _root_.scala.Option[Args], fieldTypes: IndexedSeq[ClassTag[_]]) extends StructBuilder[Args](fieldTypes) { - def build(): Args = instance match { - case _root_.scala.Some(i) => + def build(): Args = { + val _fieldArray = fieldArray // shadow variable + if (instance.isDefined) { + val instanceValue = instance.get Args( - (if (fieldArray(0) == null) i.request else fieldArray(0)).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.Request] + if (_fieldArray(0) == null) instanceValue.request else _fieldArray(0).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.Request] + ) + } else { + if (genericArrayOps(_fieldArray).contains(null)) throw new InvalidFieldsException(structBuildError("Args")) + Args( + _fieldArray(0).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.Request] ) - case _root_.scala.None => - if (fieldArray.contains(null)) throw new InvalidFieldsException(structBuildError("Args")) - else { - Args( - fieldArray(0).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.Request] - ) - } } + } } type SuccessType = com.twitter.scrooge.test.gold.thriftscala.Response @@ -530,9 +521,9 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ val NoPassthroughFields: immutable$Map[Short, TFieldBlob] = immutable$Map.empty[Short, TFieldBlob] val Struct: TStruct = new TStruct("doGreatThings_result") val SuccessField: TField = new TField("success", TType.STRUCT, 0) - val SuccessFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Response] = implicitly[Manifest[com.twitter.scrooge.test.gold.thriftscala.Response]] + val SuccessFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Response] = manifest[com.twitter.scrooge.test.gold.thriftscala.Response] val ExField: TField = new TField("ex", TType.STRUCT, 1) - val ExFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException] = implicitly[Manifest[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] + val ExFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException] = manifest[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException] /** * Field information in declaration order. @@ -562,33 +553,32 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ ) ) - lazy val structAnnotations: immutable$Map[String, String] = + + val structAnnotations: immutable$Map[String, String] = immutable$Map.empty[String, String] - private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq( + private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq[ClassTag[_]]( classTag[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Response]].asInstanceOf[ClassTag[_]], classTag[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]].asInstanceOf[ClassTag[_]] ) - private[this] val structFields: Seq[ThriftStructField[Result]] = { - Seq( - new ThriftStructField[Result]( - SuccessField, - _root_.scala.Some(SuccessFieldManifest), - classOf[Result]) { - def getValue[R](struct: Result): R = struct.success.asInstanceOf[R] - }, - new ThriftStructField[Result]( - ExField, - _root_.scala.Some(ExFieldManifest), - classOf[Result]) { - def getValue[R](struct: Result): R = struct.ex.asInstanceOf[R] - } - ) - } + private[this] val structFields: Seq[ThriftStructField[Result]] = Seq[ThriftStructField[Result]]( + new ThriftStructField[Result]( + SuccessField, + _root_.scala.Some(SuccessFieldManifest), + classOf[Result]) { + def getValue[R](struct: Result): R = struct.success.asInstanceOf[R] + }, + new ThriftStructField[Result]( + ExField, + _root_.scala.Some(ExFieldManifest), + classOf[Result]) { + def getValue[R](struct: Result): R = struct.ex.asInstanceOf[R] + } + ) override lazy val metaData: ThriftStructMetaData[Result] = - new ThriftStructMetaData(this, structFields, fieldInfos, Seq(), structAnnotations) + new ThriftStructMetaData(this, structFields, fieldInfos, Nil, structAnnotations) /** * Checks that all required fields are non-null. @@ -640,52 +630,47 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ var _done = false _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 0 => - _field.`type` match { - case TType.STRUCT => - success = _root_.scala.Some(readSuccessValue(_iprot)) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'success' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + success = _root_.scala.Some(readSuccessValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'success' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case 1 => - _field.`type` match { - case TType.STRUCT => - ex = _root_.scala.Some(readExValue(_iprot)) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'ex' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + ex = _root_.scala.Some(readExValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'ex' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() new Result( success, ex, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() @@ -758,12 +743,11 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ def _1: _root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Response] = success def _2: _root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException] = ex - def toTuple: _root_.scala.Tuple2[Option[com.twitter.scrooge.test.gold.thriftscala.Response], Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] = { - ( + def toTuple: _root_.scala.Tuple2[Option[com.twitter.scrooge.test.gold.thriftscala.Response], Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] = + _root_.scala.Tuple2[Option[com.twitter.scrooge.test.gold.thriftscala.Response], Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]]( success, ex ) - } def successField: Option[com.twitter.scrooge.test.gold.thriftscala.Response] = success def exceptionFields: Iterable[Option[com.twitter.scrooge.ThriftException]] = Seq(ex) @@ -794,14 +778,13 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ override def canEqual(other: Any): Boolean = other.isInstanceOf[Result] - private def _equals(x: Result, y: Result): Boolean = - x.productArity == y.productArity && - x.productIterator.sameElements(y.productIterator) && - x._passthroughFields == y._passthroughFields + private[this] def _equals(other: Result): Boolean = + this.productArity == other.productArity && + this.productIterator.sameElements(other.productIterator) && + this._passthroughFields == other._passthroughFields override def equals(other: Any): Boolean = - canEqual(other) && - _equals(this, other.asInstanceOf[Result]) + canEqual(other) && _equals(other.asInstanceOf[Result]) override def hashCode: Int = { _root_.scala.runtime.ScalaRunTime._hashCode(this) @@ -809,15 +792,6 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ override def toString: String = _root_.scala.runtime.ScalaRunTime._toString(this) - - override def productArity: Int = 2 - - override def productElement(n: Int): Any = n match { - case 0 => this.success - case 1 => this.ex - case _ => throw new IndexOutOfBoundsException(n.toString) - } - override def productPrefix: String = "Result" def _codec: ValidatingThriftStructCodec3[Result] = Result @@ -828,21 +802,22 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ private[thriftscala] class ResultStructBuilder(instance: _root_.scala.Option[Result], fieldTypes: IndexedSeq[ClassTag[_]]) extends StructBuilder[Result](fieldTypes) { - def build(): Result = instance match { - case _root_.scala.Some(i) => + def build(): Result = { + val _fieldArray = fieldArray // shadow variable + if (instance.isDefined) { + val instanceValue = instance.get Result( - (if (fieldArray(0) == null) i.success else fieldArray(0)).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Response]], - (if (fieldArray(1) == null) i.ex else fieldArray(1)).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] + if (_fieldArray(0) == null) instanceValue.success else _fieldArray(0).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Response]], + if (_fieldArray(1) == null) instanceValue.ex else _fieldArray(1).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] + ) + } else { + if (genericArrayOps(_fieldArray).contains(null)) throw new InvalidFieldsException(structBuildError("Result")) + Result( + _fieldArray(0).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Response]], + _fieldArray(1).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] ) - case _root_.scala.None => - if (fieldArray.contains(null)) throw new InvalidFieldsException(structBuildError("Result")) - else { - Result( - fieldArray(0).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Response]], - fieldArray(1).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] - ) - } } + } } val annotations: immutable$Map[String, String] = immutable$Map( @@ -886,7 +861,7 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ val NoPassthroughFields: immutable$Map[Short, TFieldBlob] = immutable$Map.empty[Short, TFieldBlob] val Struct: TStruct = new TStruct("noExceptionCall_args") val RequestField: TField = new TField("request", TType.STRUCT, 1) - val RequestFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Request] = implicitly[Manifest[com.twitter.scrooge.test.gold.thriftscala.Request]] + val RequestFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Request] = manifest[com.twitter.scrooge.test.gold.thriftscala.Request] /** * Field information in declaration order. @@ -905,26 +880,25 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ ) ) - lazy val structAnnotations: immutable$Map[String, String] = + + val structAnnotations: immutable$Map[String, String] = immutable$Map.empty[String, String] - private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq( + private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq[ClassTag[_]]( classTag[com.twitter.scrooge.test.gold.thriftscala.Request].asInstanceOf[ClassTag[_]] ) - private[this] val structFields: Seq[ThriftStructField[Args]] = { - Seq( - new ThriftStructField[Args]( - RequestField, - _root_.scala.Some(RequestFieldManifest), - classOf[Args]) { - def getValue[R](struct: Args): R = struct.request.asInstanceOf[R] - } - ) - } + private[this] val structFields: Seq[ThriftStructField[Args]] = Seq[ThriftStructField[Args]]( + new ThriftStructField[Args]( + RequestField, + _root_.scala.Some(RequestFieldManifest), + classOf[Args]) { + def getValue[R](struct: Args): R = struct.request.asInstanceOf[R] + } + ) override lazy val metaData: ThriftStructMetaData[Args] = - new ThriftStructMetaData(this, structFields, fieldInfos, Seq(), structAnnotations) + new ThriftStructMetaData(this, structFields, fieldInfos, Nil, structAnnotations) /** * Checks that all required fields are non-null. @@ -965,38 +939,36 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ var _done = false _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 1 => - _field.`type` match { - case TType.STRUCT => - request = readRequestValue(_iprot) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'request' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + request = readRequestValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'request' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() new Args( request, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() @@ -1073,14 +1045,13 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ override def canEqual(other: Any): Boolean = other.isInstanceOf[Args] - private def _equals(x: Args, y: Args): Boolean = - x.productArity == y.productArity && - x.productIterator.sameElements(y.productIterator) && - x._passthroughFields == y._passthroughFields + private[this] def _equals(other: Args): Boolean = + this.productArity == other.productArity && + this.productIterator.sameElements(other.productIterator) && + this._passthroughFields == other._passthroughFields override def equals(other: Any): Boolean = - canEqual(other) && - _equals(this, other.asInstanceOf[Args]) + canEqual(other) && _equals(other.asInstanceOf[Args]) override def hashCode: Int = { _root_.scala.runtime.ScalaRunTime._hashCode(this) @@ -1088,14 +1059,6 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ override def toString: String = _root_.scala.runtime.ScalaRunTime._toString(this) - - override def productArity: Int = 1 - - override def productElement(n: Int): Any = n match { - case 0 => this.request - case _ => throw new IndexOutOfBoundsException(n.toString) - } - override def productPrefix: String = "Args" def _codec: ValidatingThriftStructCodec3[Args] = Args @@ -1106,19 +1069,20 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ private[thriftscala] class ArgsStructBuilder(instance: _root_.scala.Option[Args], fieldTypes: IndexedSeq[ClassTag[_]]) extends StructBuilder[Args](fieldTypes) { - def build(): Args = instance match { - case _root_.scala.Some(i) => + def build(): Args = { + val _fieldArray = fieldArray // shadow variable + if (instance.isDefined) { + val instanceValue = instance.get Args( - (if (fieldArray(0) == null) i.request else fieldArray(0)).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.Request] + if (_fieldArray(0) == null) instanceValue.request else _fieldArray(0).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.Request] + ) + } else { + if (genericArrayOps(_fieldArray).contains(null)) throw new InvalidFieldsException(structBuildError("Args")) + Args( + _fieldArray(0).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.Request] ) - case _root_.scala.None => - if (fieldArray.contains(null)) throw new InvalidFieldsException(structBuildError("Args")) - else { - Args( - fieldArray(0).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.Request] - ) - } } + } } type SuccessType = com.twitter.scrooge.test.gold.thriftscala.Response @@ -1127,7 +1091,7 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ val NoPassthroughFields: immutable$Map[Short, TFieldBlob] = immutable$Map.empty[Short, TFieldBlob] val Struct: TStruct = new TStruct("noExceptionCall_result") val SuccessField: TField = new TField("success", TType.STRUCT, 0) - val SuccessFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Response] = implicitly[Manifest[com.twitter.scrooge.test.gold.thriftscala.Response]] + val SuccessFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Response] = manifest[com.twitter.scrooge.test.gold.thriftscala.Response] /** * Field information in declaration order. @@ -1146,26 +1110,25 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ ) ) - lazy val structAnnotations: immutable$Map[String, String] = + + val structAnnotations: immutable$Map[String, String] = immutable$Map.empty[String, String] - private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq( + private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq[ClassTag[_]]( classTag[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Response]].asInstanceOf[ClassTag[_]] ) - private[this] val structFields: Seq[ThriftStructField[Result]] = { - Seq( - new ThriftStructField[Result]( - SuccessField, - _root_.scala.Some(SuccessFieldManifest), - classOf[Result]) { - def getValue[R](struct: Result): R = struct.success.asInstanceOf[R] - } - ) - } + private[this] val structFields: Seq[ThriftStructField[Result]] = Seq[ThriftStructField[Result]]( + new ThriftStructField[Result]( + SuccessField, + _root_.scala.Some(SuccessFieldManifest), + classOf[Result]) { + def getValue[R](struct: Result): R = struct.success.asInstanceOf[R] + } + ) override lazy val metaData: ThriftStructMetaData[Result] = - new ThriftStructMetaData(this, structFields, fieldInfos, Seq(), structAnnotations) + new ThriftStructMetaData(this, structFields, fieldInfos, Nil, structAnnotations) /** * Checks that all required fields are non-null. @@ -1208,38 +1171,36 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ var _done = false _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 0 => - _field.`type` match { - case TType.STRUCT => - success = _root_.scala.Some(readSuccessValue(_iprot)) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'success' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + success = _root_.scala.Some(readSuccessValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'success' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() new Result( success, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() @@ -1318,14 +1279,13 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ override def canEqual(other: Any): Boolean = other.isInstanceOf[Result] - private def _equals(x: Result, y: Result): Boolean = - x.productArity == y.productArity && - x.productIterator.sameElements(y.productIterator) && - x._passthroughFields == y._passthroughFields + private[this] def _equals(other: Result): Boolean = + this.productArity == other.productArity && + this.productIterator.sameElements(other.productIterator) && + this._passthroughFields == other._passthroughFields override def equals(other: Any): Boolean = - canEqual(other) && - _equals(this, other.asInstanceOf[Result]) + canEqual(other) && _equals(other.asInstanceOf[Result]) override def hashCode: Int = { _root_.scala.runtime.ScalaRunTime._hashCode(this) @@ -1333,14 +1293,6 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ override def toString: String = _root_.scala.runtime.ScalaRunTime._toString(this) - - override def productArity: Int = 1 - - override def productElement(n: Int): Any = n match { - case 0 => this.success - case _ => throw new IndexOutOfBoundsException(n.toString) - } - override def productPrefix: String = "Result" def _codec: ValidatingThriftStructCodec3[Result] = Result @@ -1351,19 +1303,20 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ private[thriftscala] class ResultStructBuilder(instance: _root_.scala.Option[Result], fieldTypes: IndexedSeq[ClassTag[_]]) extends StructBuilder[Result](fieldTypes) { - def build(): Result = instance match { - case _root_.scala.Some(i) => + def build(): Result = { + val _fieldArray = fieldArray // shadow variable + if (instance.isDefined) { + val instanceValue = instance.get Result( - (if (fieldArray(0) == null) i.success else fieldArray(0)).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Response]] + if (_fieldArray(0) == null) instanceValue.success else _fieldArray(0).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Response]] + ) + } else { + if (genericArrayOps(_fieldArray).contains(null)) throw new InvalidFieldsException(structBuildError("Result")) + Result( + _fieldArray(0).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Response]] ) - case _root_.scala.None => - if (fieldArray.contains(null)) throw new InvalidFieldsException(structBuildError("Result")) - else { - Result( - fieldArray(0).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Response]] - ) - } } + } } val annotations: immutable$Map[String, String] = immutable$Map.empty @@ -1443,12 +1396,12 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ def doGreatThings(request: com.twitter.scrooge.test.gold.thriftscala.Request): Future[com.twitter.scrooge.test.gold.thriftscala.Response] = { val requestCtx = _root_.com.twitter.finagle.context.Contexts.local.getOrElse(_root_.com.twitter.finagle.thrift.Headers.Request.Key, () => _root_.com.twitter.finagle.thrift.Headers.Request.newValues) val scroogeRequest = _root_.com.twitter.scrooge.Request(requestCtx.values, self.DoGreatThings.Args(request)) - servicePerEndpoint.doGreatThings(scroogeRequest).transform(_root_.com.twitter.finagle.thrift.service.ThriftReqRepServicePerEndpoint.transformResult(_)) + servicePerEndpoint.doGreatThings(scroogeRequest).transform(_root_.com.twitter.finagle.thrift.service.ThriftReqRepServicePerEndpoint.transformResult) } def noExceptionCall(request: com.twitter.scrooge.test.gold.thriftscala.Request): Future[com.twitter.scrooge.test.gold.thriftscala.Response] = { val requestCtx = _root_.com.twitter.finagle.context.Contexts.local.getOrElse(_root_.com.twitter.finagle.thrift.Headers.Request.Key, () => _root_.com.twitter.finagle.thrift.Headers.Request.newValues) val scroogeRequest = _root_.com.twitter.scrooge.Request(requestCtx.values, self.NoExceptionCall.Args(request)) - servicePerEndpoint.noExceptionCall(scroogeRequest).transform(_root_.com.twitter.finagle.thrift.service.ThriftReqRepServicePerEndpoint.transformResult(_)) + servicePerEndpoint.noExceptionCall(scroogeRequest).transform(_root_.com.twitter.finagle.thrift.service.ThriftReqRepServicePerEndpoint.transformResult) } override def asClosable: _root_.com.twitter.util.Closable = @@ -1572,7 +1525,7 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ oprot.writeMessageBegin(new TMessage(name, TMessageType.EXCEPTION, seqid)) x.write(oprot) oprot.writeMessageEnd() - oprot.getTransport().flush() + oprot.getTransport.flush() // make a copy of the array of bytes to construct a new buffer because memoryBuffer is reusable Buf.ByteArray.Shared(memoryBuffer.getArray(), 0, memoryBuffer.length()) @@ -1581,7 +1534,7 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ } } - private def reply(name: String, seqid: Int, result: ThriftStruct): Buf = { + private[this] def reply(name: String, seqid: Int, result: ThriftStruct): Buf = { val memoryBuffer = tlReusableBuffer.get() try { val oprot = protocolFactory.getProtocol(memoryBuffer) @@ -1590,7 +1543,7 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ result.write(oprot) oprot.writeMessageEnd() _root_.com.twitter.finagle.tracing.Trace.recordBinary("srv/response_serialization_ns", System.nanoTime - start) - oprot.getTransport().flush() + oprot.getTransport.flush() // make a copy of the array of bytes to construct a new buffer because memoryBuffer is reusable Buf.ByteArray.Shared(memoryBuffer.getArray(), 0, memoryBuffer.length()) @@ -1599,43 +1552,17 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ } } - private def missingResult(name: String): TApplicationException = { - new TApplicationException( - TApplicationException.MISSING_RESULT, - name + " failed: unknown result" - ) - } - - private def setServiceName(ex: Throwable): Throwable = - if (this.serviceName == "") ex - else { - ex match { - case se: _root_.com.twitter.finagle.SourcedException => - se.serviceName = this.serviceName - se - case _ => ex - } - } - - private def recordRequest(methodStats: _root_.com.twitter.finagle.thrift.ThriftMethodStats): Unit = { - methodStats.requestsCounter.incr() - } - - private def recordResponse(reqRep: ctfs.ReqRep, methodStats: _root_.com.twitter.finagle.thrift.ThriftMethodStats): Unit = { + private[this] def recordResponse(reqRep: ctfs.ReqRep, methodStats: _root_.com.twitter.finagle.thrift.ThriftMethodStats): Unit = { ServerToReqRep.setCtx(reqRep) - val responseClass = responseClassifier.applyOrElse(reqRep, ctfs.ResponseClassifier.Default) - responseClass match { - case ctfs.ResponseClass.Ignorable => // Do nothing. - case ctfs.ResponseClass.Successful(_) => - methodStats.successCounter.incr() - case ctfs.ResponseClass.Failed(_) => - methodStats.failuresCounter.incr() - reqRep.response match { - case Throw(ex) => - methodStats.failuresScope.counter(Throwables.mkString(ex): _*).incr() - case _ => - } - } + val classified = responseClassifier.applyOrElse(reqRep, ctfs.ResponseClassifier.Default) + if (classified.isInstanceOf[ctfs.ResponseClass.Successful]) { + methodStats.successCounter.incr() + } else if (classified.isInstanceOf[ctfs.ResponseClass.Failed]) { + methodStats.failuresCounter.incr() + if (reqRep.response.isThrow) { + methodStats.failuresScope.counter(Throwables.mkString(reqRep.response.throwable): _*).incr() + } + } // Last ResponseClass is Ignorable, which we do not need to record } final protected def perMethodStatsFilter( @@ -1652,25 +1579,30 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ req: (TProtocol, Int), service: finagle$Service[(TProtocol, Int), RichResponse[method.Args, method.Result]] ): Future[Array[Byte]] = { - recordRequest(methodStats) - service(req).transform { - case Return(value) => - value match { - case SuccessfulResponse(args, _, result) => - recordResponse(ctfs.ReqRep(args, _root_.com.twitter.util.Return(result.successField.get)), methodStats) - case ProtocolExceptionResponse(args, _, exp) => - recordResponse(ctfs.ReqRep(args, _root_.com.twitter.util.Throw(exp)), methodStats) - case ThriftExceptionResponse(args, _, ex) => - val rep = ex match { - case exp: ThriftException => setServiceName(exp) - case _ => missingResult(serviceName) - } - recordResponse(ctfs.ReqRep(args, _root_.com.twitter.util.Throw(rep)), methodStats) + methodStats.requestsCounter.incr() + service(req).transform { response => + if (response.isReturn) { + val value = response.apply() + if (value.isInstanceOf[SuccessfulResponse[method.Args, method.Result]]) { + val succResp = value.asInstanceOf[SuccessfulResponse[method.Args, method.Result]] + recordResponse(ctfs.ReqRep(succResp.input, _root_.com.twitter.util.Return(succResp.result.successField.get)), methodStats) + } else if (value.isInstanceOf[ProtocolExceptionResponse[method.Args, method.Result]]) { + val protExResp = value.asInstanceOf[ProtocolExceptionResponse[method.Args, method.Result]] + recordResponse(ctfs.ReqRep(protExResp.input, _root_.com.twitter.util.Throw(protExResp.exception)), methodStats) + } else if (value.isInstanceOf[ThriftExceptionResponse[method.Args, method.Result]]) { + val thriftExResp = value.asInstanceOf[ThriftExceptionResponse[method.Args, method.Result]] + val rep: Throwable = if (thriftExResp.ex.isInstanceOf[ThriftException]) { + _root_.com.twitter.finagle.SourcedException.setServiceName(thriftExResp.ex, serviceName) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.missingResult(serviceName) + } + recordResponse(ctfs.ReqRep(thriftExResp.input, _root_.com.twitter.util.Throw(rep)), methodStats) } Future.value(Buf.ByteArray.Owned.extract(value.response)) - case t @ Throw(_) => - recordResponse(ctfs.ReqRep(req, t), methodStats) - Future.const(t.cast[Array[Byte]]) + } else { // Throw[_] + recordResponse(ctfs.ReqRep(req, response), methodStats) + Future.const(response.asInstanceOf[Throw[Array[Byte]]]) + } } } } @@ -1688,17 +1620,19 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ val iprot = request._1 val seqid = request._2 val res = service(request) - res.transform { - case _root_.com.twitter.util.Throw(e: TProtocolException) => + res.transform(resTry => { + if (resTry.isThrow && resTry.throwable.isInstanceOf[TProtocolException]) { + val underlyingException = resTry.throwable iprot.readMessageEnd() Future.value( ProtocolExceptionResponse( null, - exception("doGreatThings", seqid, TApplicationException.PROTOCOL_ERROR, e.getMessage), - new TApplicationException(TApplicationException.PROTOCOL_ERROR, e.getMessage))) - case _ => + exception("doGreatThings", seqid, TApplicationException.PROTOCOL_ERROR, underlyingException.getMessage), + new TApplicationException(TApplicationException.PROTOCOL_ERROR, underlyingException.getMessage))) + } else { res - } + } + }) } } @@ -1713,32 +1647,32 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ val args = DoGreatThings.Args.decode(iprot) iprot.readMessageEnd() _root_.com.twitter.finagle.tracing.Trace.recordBinary("srv/request_deserialization_ns", System.nanoTime - start) - val res = _root_.com.twitter.finagle.context.Contexts.local.let( + _root_.com.twitter.finagle.context.Contexts.local.let( _root_.com.twitter.finagle.thrift.MethodMetadata.Key, _root_.com.twitter.finagle.thrift.MethodMetadata(DoGreatThings)) { service(args) - } - res.transform { - case _root_.com.twitter.util.Return(value) => - val methodResult = DoGreatThings.Result(success = Some(value)) + }.transform(resTry => { + if (resTry.isReturn) { + val methodResult = DoGreatThings.Result(success = Some(resTry.apply())) Future.value( SuccessfulResponse( args, reply("doGreatThings", seqid, methodResult), methodResult)) - case _root_.com.twitter.util.Throw(e: com.twitter.scrooge.test.gold.thriftscala.OverCapacityException) => { - Future.value( - ThriftExceptionResponse( - args, - reply("doGreatThings", seqid, DoGreatThings.Result(ex = Some(e))), - e)) + } else { // Throw[_] + val underlyingException = resTry.throwable + if (underlyingException.isInstanceOf[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]) + Future.value( + ThriftExceptionResponse( + args, + reply("doGreatThings", seqid, DoGreatThings.Result(ex = Some(underlyingException.asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]))), + underlyingException.asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException])) + else + Future.const(resTry.asInstanceOf[Throw[RichResponse[DoGreatThings.Args, DoGreatThings.Result]]]) } - case t @ _root_.com.twitter.util.Throw(_) => - Future.const(t.cast[RichResponse[DoGreatThings.Args, DoGreatThings.Result]]) - } + }) } } - statsFilter.andThen(protocolExnFilter).andThen(serdeFilter) } val noExceptionCall: finagle$Filter[(TProtocol, Int), Array[Byte], NoExceptionCall.Args, NoExceptionCall.SuccessType] = { @@ -1752,17 +1686,19 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ val iprot = request._1 val seqid = request._2 val res = service(request) - res.transform { - case _root_.com.twitter.util.Throw(e: TProtocolException) => + res.transform(resTry => { + if (resTry.isThrow && resTry.throwable.isInstanceOf[TProtocolException]) { + val underlyingException = resTry.throwable iprot.readMessageEnd() Future.value( ProtocolExceptionResponse( null, - exception("noExceptionCall", seqid, TApplicationException.PROTOCOL_ERROR, e.getMessage), - new TApplicationException(TApplicationException.PROTOCOL_ERROR, e.getMessage))) - case _ => + exception("noExceptionCall", seqid, TApplicationException.PROTOCOL_ERROR, underlyingException.getMessage), + new TApplicationException(TApplicationException.PROTOCOL_ERROR, underlyingException.getMessage))) + } else { res - } + } + }) } } @@ -1777,25 +1713,24 @@ object GoldService extends _root_.com.twitter.finagle.thrift.GeneratedThriftServ val args = NoExceptionCall.Args.decode(iprot) iprot.readMessageEnd() _root_.com.twitter.finagle.tracing.Trace.recordBinary("srv/request_deserialization_ns", System.nanoTime - start) - val res = _root_.com.twitter.finagle.context.Contexts.local.let( + _root_.com.twitter.finagle.context.Contexts.local.let( _root_.com.twitter.finagle.thrift.MethodMetadata.Key, _root_.com.twitter.finagle.thrift.MethodMetadata(NoExceptionCall)) { service(args) - } - res.transform { - case _root_.com.twitter.util.Return(value) => - val methodResult = NoExceptionCall.Result(success = Some(value)) + }.transform(resTry => { + if (resTry.isReturn) { + val methodResult = NoExceptionCall.Result(success = Some(resTry.apply())) Future.value( SuccessfulResponse( args, reply("noExceptionCall", seqid, methodResult), methodResult)) - case t @ _root_.com.twitter.util.Throw(_) => - Future.const(t.cast[RichResponse[NoExceptionCall.Args, NoExceptionCall.Result]]) - } + } else { // Throw[_] + Future.const(resTry.asInstanceOf[Throw[RichResponse[NoExceptionCall.Args, NoExceptionCall.Result]]]) + } + }) } } - statsFilter.andThen(protocolExnFilter).andThen(serdeFilter) } } diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/OverCapacityException.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/OverCapacityException.scala index 244ab2506..478cfb7c1 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/OverCapacityException.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/OverCapacityException.scala @@ -30,7 +30,7 @@ object OverCapacityException extends ValidatingThriftStructCodec3[OverCapacityEx val NoPassthroughFields: immutable$Map[Short, TFieldBlob] = immutable$Map.empty[Short, TFieldBlob] val Struct: TStruct = new TStruct("OverCapacityException") val ChillTimeSecondsField: TField = new TField("chillTimeSeconds", TType.I32, 1) - val ChillTimeSecondsFieldManifest: Manifest[Int] = implicitly[Manifest[Int]] + val ChillTimeSecondsFieldManifest: Manifest[Int] = manifest[Int] /** * Field information in declaration order. @@ -44,35 +44,34 @@ object OverCapacityException extends ValidatingThriftStructCodec3[OverCapacityEx _root_.scala.None, _root_.scala.None, immutable$Map.empty[String, String], - immutable$Map( - "e.field.annotation" -> "false" + immutable$Map.apply[String, String]( + ("e.field.annotation", "false") ), None ) ) + lazy val structAnnotations: immutable$Map[String, String] = immutable$Map[String, String]( - "e.annotation" -> "true" + ("e.annotation", "true") ) - private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq( + private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq[ClassTag[_]]( classTag[Int].asInstanceOf[ClassTag[_]] ) - private[this] val structFields: Seq[ThriftStructField[OverCapacityException]] = { - Seq( - new ThriftStructField[OverCapacityException]( - ChillTimeSecondsField, - _root_.scala.Some(ChillTimeSecondsFieldManifest), - classOf[OverCapacityException]) { - def getValue[R](struct: OverCapacityException): R = struct.chillTimeSeconds.asInstanceOf[R] - } - ) - } + private[this] val structFields: Seq[ThriftStructField[OverCapacityException]] = Seq[ThriftStructField[OverCapacityException]]( + new ThriftStructField[OverCapacityException]( + ChillTimeSecondsField, + _root_.scala.Some(ChillTimeSecondsFieldManifest), + classOf[OverCapacityException]) { + def getValue[R](struct: OverCapacityException): R = struct.chillTimeSeconds.asInstanceOf[R] + } + ) override lazy val metaData: ThriftStructMetaData[OverCapacityException] = - new ThriftStructMetaData(this, structFields, fieldInfos, Seq(), structAnnotations) + new ThriftStructMetaData(this, structFields, fieldInfos, Nil, structAnnotations) /** * Checks that all required fields are non-null. @@ -93,11 +92,7 @@ object OverCapacityException extends ValidatingThriftStructCodec3[OverCapacityEx def withoutPassthroughFields(original: OverCapacityException): OverCapacityException = new OverCapacityException( - chillTimeSeconds = - { - val field = original.chillTimeSeconds - field - } + chillTimeSeconds = original.chillTimeSeconds ) def newBuilder(): StructBuilder[OverCapacityException] = new OverCapacityExceptionStructBuilder(_root_.scala.None, fieldTypes) @@ -113,38 +108,36 @@ object OverCapacityException extends ValidatingThriftStructCodec3[OverCapacityEx var _done = false _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 1 => - _field.`type` match { - case TType.I32 => - chillTimeSeconds = readChillTimeSecondsValue(_iprot) - case _actualType => - val _expectedType = TType.I32 - throw new TProtocolException( - "Received wrong type for field 'chillTimeSeconds' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I32) { + chillTimeSeconds = readChillTimeSecondsValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'chillTimeSeconds' (expected=%s, actual=%s).", + TType.I32, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() new OverCapacityException( chillTimeSeconds, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() @@ -220,37 +213,33 @@ class OverCapacityException( * is known and not optional and set to None, then the field is serialized and returned. */ def getFieldBlob(_fieldId: Short): _root_.scala.Option[TFieldBlob] = { - lazy val _buff = new TMemoryBuffer(32) - lazy val _oprot = new TCompactProtocol(_buff) - _passthroughFields.get(_fieldId) match { - case blob: _root_.scala.Some[TFieldBlob] => blob - case _root_.scala.None => { - val _fieldOpt: _root_.scala.Option[TField] = - _fieldId match { - case 1 => - if (true) { - writeChillTimeSecondsValue(chillTimeSeconds, _oprot) - _root_.scala.Some(OverCapacityException.ChillTimeSecondsField) - } else { - _root_.scala.None - } - case _ => _root_.scala.None - } - _fieldOpt match { - case _root_.scala.Some(_field) => - _root_.scala.Some(TFieldBlob(_field, Buf.ByteArray.Owned(_buff.getArray()))) - case _root_.scala.None => - _root_.scala.None - } + val passedthroughValue = _passthroughFields.get(_fieldId) + if (passedthroughValue.isDefined) { + passedthroughValue + } else { + val _buff = new TMemoryBuffer(32) + val _oprot = new TCompactProtocol(_buff) + + val _fieldOpt: _root_.scala.Option[TField] = _fieldId match { + case 1 => + writeChillTimeSecondsValue(chillTimeSeconds, _oprot) + _root_.scala.Some(OverCapacityException.ChillTimeSecondsField) + case _ => _root_.scala.None + } + if (_fieldOpt.isDefined) { + _root_.scala.Some(TFieldBlob(_fieldOpt.get, Buf.ByteArray.Owned(_buff.getArray))) + } else { + _root_.scala.None } } } + /** * Collects TCompactProtocol-encoded field values according to `getFieldBlob` into a map. */ def getFieldBlobs(ids: TraversableOnce[Short]): immutable$Map[Short, TFieldBlob] = - (ids flatMap { id => getFieldBlob(id) map { id -> _ } }).toMap + (ids.flatMap { id => getFieldBlob(id).map { fieldBlob => (id, fieldBlob) } }).toMap /** * Sets a field using a TCompactProtocol-encoded binary blob. If the field is a known @@ -264,7 +253,7 @@ class OverCapacityException( _blob.id match { case 1 => chillTimeSeconds = readChillTimeSecondsValue(_blob.read) - case _ => _passthroughFields += (_blob.id -> _blob) + case _ => _passthroughFields += _root_.scala.Tuple2(_blob.id, _blob) } new OverCapacityException( chillTimeSeconds, @@ -321,15 +310,14 @@ class OverCapacityException( override def canEqual(other: Any): Boolean = other.isInstanceOf[OverCapacityException] - private def _equals(x: OverCapacityException, y: OverCapacityException): Boolean = - x.productArity == y.productArity && - x.productIterator.sameElements(y.productIterator) && - x.flags == y.flags && - x._passthroughFields == y._passthroughFields + private[this] def _equals(other: OverCapacityException): Boolean = + this.productArity == other.productArity && + this.productIterator.sameElements(other.productIterator) && + this.flags == other.flags && + this._passthroughFields == other._passthroughFields override def equals(other: Any): Boolean = - canEqual(other) && - _equals(this, other.asInstanceOf[OverCapacityException]) + canEqual(other) && _equals(other.asInstanceOf[OverCapacityException]) override def hashCode: Int = { 31 * _root_.scala.runtime.ScalaRunTime._hashCode(this) + @@ -338,14 +326,6 @@ class OverCapacityException( override def toString: String = _root_.scala.runtime.ScalaRunTime._toString(this) - - override def productArity: Int = 1 - - override def productElement(n: Int): Any = n match { - case 0 => this.chillTimeSeconds - case _ => throw new IndexOutOfBoundsException(n.toString) - } - override def productPrefix: String = "OverCapacityException" def _codec: ValidatingThriftStructCodec3[OverCapacityException] = OverCapacityException @@ -363,18 +343,19 @@ class OverCapacityException( private[thriftscala] class OverCapacityExceptionStructBuilder(instance: _root_.scala.Option[OverCapacityException], fieldTypes: IndexedSeq[ClassTag[_]]) extends StructBuilder[OverCapacityException](fieldTypes) { - def build(): OverCapacityException = instance match { - case _root_.scala.Some(i) => + def build(): OverCapacityException = { + val _fieldArray = fieldArray // shadow variable + if (instance.isDefined) { + val instanceValue = instance.get OverCapacityException( - (if (fieldArray(0) == null) i.chillTimeSeconds else fieldArray(0)).asInstanceOf[Int] + if (_fieldArray(0) == null) instanceValue.chillTimeSeconds else _fieldArray(0).asInstanceOf[Int] + ) + } else { + if (genericArrayOps(_fieldArray).contains(null)) throw new InvalidFieldsException(structBuildError("OverCapacityException")) + OverCapacityException( + _fieldArray(0).asInstanceOf[Int] ) - case _root_.scala.None => - if (fieldArray.contains(null)) throw new InvalidFieldsException(structBuildError("OverCapacityException")) - else { - OverCapacityException( - fieldArray(0).asInstanceOf[Int] - ) - } } + } } diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/PlatinumService$FinagleClient.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/PlatinumService$FinagleClient.scala index f5fb165fb..0938c2c84 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/PlatinumService$FinagleClient.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/PlatinumService$FinagleClient.scala @@ -44,21 +44,21 @@ class PlatinumService$FinagleClient( private[this] val scopedStats: StatsReceiver = if (serviceName != "") stats.scope(serviceName) else stats private[this] object __stats_moreCoolThings { - val RequestsCounter = scopedStats.scope("moreCoolThings").counter("requests") - val SuccessCounter = scopedStats.scope("moreCoolThings").counter("success") - val FailuresCounter = scopedStats.scope("moreCoolThings").counter("failures") - val FailuresScope = scopedStats.scope("moreCoolThings").scope("failures") + val RequestsCounter: _root_.com.twitter.finagle.stats.Counter = scopedStats.scope("moreCoolThings").counter("requests") + val SuccessCounter: _root_.com.twitter.finagle.stats.Counter = scopedStats.scope("moreCoolThings").counter("success") + val FailuresCounter: _root_.com.twitter.finagle.stats.Counter = scopedStats.scope("moreCoolThings").counter("failures") + val FailuresScope: StatsReceiver = scopedStats.scope("moreCoolThings").scope("failures") } val moreCoolThingsPlatinumServiceReplyDeserializer: Array[Byte] => _root_.com.twitter.util.Try[Int] = { response: Array[Byte] => { - val result = decodeResponse(response, MoreCoolThings.Result) - - result.firstException() match { - case Some(exception) => _root_.com.twitter.util.Throw(setServiceName(exception)) - case _ => result.successField match { - case Some(success) => _root_.com.twitter.util.Return(success) - case _ => _root_.com.twitter.util.Throw(missingResult("moreCoolThings")) - } + val result: MoreCoolThings.Result = decodeResponse(response, MoreCoolThings.Result) + val firstException = result.firstException() + if (firstException.isDefined) { + _root_.com.twitter.util.Throw(setServiceName(firstException.get)) + } else if (result.successField.isDefined) { + _root_.com.twitter.util.Return(result.successField.get) + } else { + _root_.com.twitter.util.Throw(_root_.com.twitter.scrooge.internal.ApplicationExceptions.missingResult("moreCoolThings")) } } } @@ -81,23 +81,19 @@ class PlatinumService$FinagleClient( this.service(serialized).flatMap { response => Future.const(serdeCtx.deserialize(response)) }.respond { response => - val responseClass = responseClassifier.applyOrElse( + val classified = responseClassifier.applyOrElse( ctfs.ReqRep(inputArgs, response), ctfs.ResponseClassifier.Default) - responseClass match { - case ctfs.ResponseClass.Ignorable => // Do nothing. - case ctfs.ResponseClass.Successful(_) => - __stats_moreCoolThings.SuccessCounter.incr() - case ctfs.ResponseClass.Failed(_) => - __stats_moreCoolThings.FailuresCounter.incr() - response match { - case _root_.com.twitter.util.Throw(ex) => - setServiceName(ex) - __stats_moreCoolThings.FailuresScope.counter( - _root_.com.twitter.util.Throwables.mkString(ex): _*).incr() - case _ => - } - } + if (classified.isInstanceOf[ctfs.ResponseClass.Successful]) { + __stats_moreCoolThings.SuccessCounter.incr() + } else if (classified.isInstanceOf[ctfs.ResponseClass.Failed]) { + __stats_moreCoolThings.FailuresCounter.incr() + if (response.isThrow) { + setServiceName(response.throwable) + __stats_moreCoolThings.FailuresScope.counter( + _root_.com.twitter.util.Throwables.mkString(response.throwable): _*).incr() + } + } // Last ResponseClass is Ignorable, which we do not need to record } } } diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/PlatinumService$FinagleService.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/PlatinumService$FinagleService.scala index 59a345baf..38bb21cf1 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/PlatinumService$FinagleService.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/PlatinumService$FinagleService.scala @@ -48,7 +48,7 @@ class PlatinumService$FinagleService( ) = this(iface, protocolFactory, NullStatsReceiver, Thrift.param.maxThriftBufferSize) override def serviceName: String = serverParam.serviceName - private[this] val filters = new Filter(serverParam) + private[this] val filters: Filter = new Filter(serverParam) // ---- end boilerplate. diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/PlatinumService.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/PlatinumService.scala index ee49ccdd3..b60c4acb1 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/PlatinumService.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/PlatinumService.scala @@ -214,17 +214,20 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift } def unsafeBuildFromMethods(methods: immutable$Map[ThriftMethod, _root_.com.twitter.finagle.Service[_root_.com.twitter.scrooge.Request[_], _root_.com.twitter.scrooge.Response[_]]]): ReqRepServicePerEndpoint = { - val moreCoolThings = methods.get(self.MoreCoolThings) match { - case Some(impl) => impl.asInstanceOf[self.MoreCoolThings.ReqRepServicePerEndpointServiceType] - case _ => throw new IllegalArgumentException(s"No implementation found for method MoreCoolThings in ${methods.keySet}") + val moreCoolThings = { + val moreCoolThingsOpt = methods.get(self.MoreCoolThings) + if (moreCoolThingsOpt.isEmpty) throw new IllegalArgumentException(_root_.java.lang.String.format("No implementation found for method MoreCoolThings in %s", methods.keySet)) + moreCoolThingsOpt.get.asInstanceOf[self.MoreCoolThings.ReqRepServicePerEndpointServiceType] } - val doGreatThings = methods.get(com.twitter.scrooge.test.gold.thriftscala.GoldService.DoGreatThings) match { - case Some(impl) => impl.asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.GoldService.DoGreatThings.ReqRepServicePerEndpointServiceType] - case _ => throw new IllegalArgumentException(s"No implementation found for method DoGreatThings in ${methods.keySet}") + val doGreatThings = { + val doGreatThingsOpt = methods.get(com.twitter.scrooge.test.gold.thriftscala.GoldService.DoGreatThings) + if (doGreatThingsOpt.isEmpty) throw new IllegalArgumentException(_root_.java.lang.String.format("No implementation found for method DoGreatThings in %s", methods.keySet)) + doGreatThingsOpt.get.asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.GoldService.DoGreatThings.ReqRepServicePerEndpointServiceType] } - val noExceptionCall = methods.get(com.twitter.scrooge.test.gold.thriftscala.GoldService.NoExceptionCall) match { - case Some(impl) => impl.asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.GoldService.NoExceptionCall.ReqRepServicePerEndpointServiceType] - case _ => throw new IllegalArgumentException(s"No implementation found for method NoExceptionCall in ${methods.keySet}") + val noExceptionCall = { + val noExceptionCallOpt = methods.get(com.twitter.scrooge.test.gold.thriftscala.GoldService.NoExceptionCall) + if (noExceptionCallOpt.isEmpty) throw new IllegalArgumentException(_root_.java.lang.String.format("No implementation found for method NoExceptionCall in %s", methods.keySet)) + noExceptionCallOpt.get.asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.GoldService.NoExceptionCall.ReqRepServicePerEndpointServiceType] } ReqRepServicePerEndpoint(moreCoolThings, doGreatThings, noExceptionCall) @@ -321,7 +324,7 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift val NoPassthroughFields: immutable$Map[Short, TFieldBlob] = immutable$Map.empty[Short, TFieldBlob] val Struct: TStruct = new TStruct("moreCoolThings_args") val RequestField: TField = new TField("request", TType.STRUCT, 1) - val RequestFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Request] = implicitly[Manifest[com.twitter.scrooge.test.gold.thriftscala.Request]] + val RequestFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Request] = manifest[com.twitter.scrooge.test.gold.thriftscala.Request] /** * Field information in declaration order. @@ -340,26 +343,25 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift ) ) - lazy val structAnnotations: immutable$Map[String, String] = + + val structAnnotations: immutable$Map[String, String] = immutable$Map.empty[String, String] - private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq( + private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq[ClassTag[_]]( classTag[com.twitter.scrooge.test.gold.thriftscala.Request].asInstanceOf[ClassTag[_]] ) - private[this] val structFields: Seq[ThriftStructField[Args]] = { - Seq( - new ThriftStructField[Args]( - RequestField, - _root_.scala.Some(RequestFieldManifest), - classOf[Args]) { - def getValue[R](struct: Args): R = struct.request.asInstanceOf[R] - } - ) - } + private[this] val structFields: Seq[ThriftStructField[Args]] = Seq[ThriftStructField[Args]]( + new ThriftStructField[Args]( + RequestField, + _root_.scala.Some(RequestFieldManifest), + classOf[Args]) { + def getValue[R](struct: Args): R = struct.request.asInstanceOf[R] + } + ) override lazy val metaData: ThriftStructMetaData[Args] = - new ThriftStructMetaData(this, structFields, fieldInfos, Seq(), structAnnotations) + new ThriftStructMetaData(this, structFields, fieldInfos, Nil, structAnnotations) /** * Checks that all required fields are non-null. @@ -400,38 +402,36 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift var _done = false _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 1 => - _field.`type` match { - case TType.STRUCT => - request = readRequestValue(_iprot) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'request' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + request = readRequestValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'request' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() new Args( request, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() @@ -508,14 +508,13 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift override def canEqual(other: Any): Boolean = other.isInstanceOf[Args] - private def _equals(x: Args, y: Args): Boolean = - x.productArity == y.productArity && - x.productIterator.sameElements(y.productIterator) && - x._passthroughFields == y._passthroughFields + private[this] def _equals(other: Args): Boolean = + this.productArity == other.productArity && + this.productIterator.sameElements(other.productIterator) && + this._passthroughFields == other._passthroughFields override def equals(other: Any): Boolean = - canEqual(other) && - _equals(this, other.asInstanceOf[Args]) + canEqual(other) && _equals(other.asInstanceOf[Args]) override def hashCode: Int = { _root_.scala.runtime.ScalaRunTime._hashCode(this) @@ -523,14 +522,6 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift override def toString: String = _root_.scala.runtime.ScalaRunTime._toString(this) - - override def productArity: Int = 1 - - override def productElement(n: Int): Any = n match { - case 0 => this.request - case _ => throw new IndexOutOfBoundsException(n.toString) - } - override def productPrefix: String = "Args" def _codec: ValidatingThriftStructCodec3[Args] = Args @@ -541,19 +532,20 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift private[thriftscala] class ArgsStructBuilder(instance: _root_.scala.Option[Args], fieldTypes: IndexedSeq[ClassTag[_]]) extends StructBuilder[Args](fieldTypes) { - def build(): Args = instance match { - case _root_.scala.Some(i) => + def build(): Args = { + val _fieldArray = fieldArray // shadow variable + if (instance.isDefined) { + val instanceValue = instance.get Args( - (if (fieldArray(0) == null) i.request else fieldArray(0)).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.Request] + if (_fieldArray(0) == null) instanceValue.request else _fieldArray(0).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.Request] + ) + } else { + if (genericArrayOps(_fieldArray).contains(null)) throw new InvalidFieldsException(structBuildError("Args")) + Args( + _fieldArray(0).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.Request] ) - case _root_.scala.None => - if (fieldArray.contains(null)) throw new InvalidFieldsException(structBuildError("Args")) - else { - Args( - fieldArray(0).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.Request] - ) - } } + } } type SuccessType = Int @@ -562,11 +554,11 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift val NoPassthroughFields: immutable$Map[Short, TFieldBlob] = immutable$Map.empty[Short, TFieldBlob] val Struct: TStruct = new TStruct("moreCoolThings_result") val SuccessField: TField = new TField("success", TType.I32, 0) - val SuccessFieldManifest: Manifest[Int] = implicitly[Manifest[Int]] + val SuccessFieldManifest: Manifest[Int] = manifest[Int] val AxField: TField = new TField("ax", TType.STRUCT, 1) - val AxFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.AnotherException] = implicitly[Manifest[com.twitter.scrooge.test.gold.thriftscala.AnotherException]] + val AxFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.AnotherException] = manifest[com.twitter.scrooge.test.gold.thriftscala.AnotherException] val OceField: TField = new TField("oce", TType.STRUCT, 2) - val OceFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException] = implicitly[Manifest[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] + val OceFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException] = manifest[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException] /** * Field information in declaration order. @@ -607,40 +599,39 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift ) ) - lazy val structAnnotations: immutable$Map[String, String] = + + val structAnnotations: immutable$Map[String, String] = immutable$Map.empty[String, String] - private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq( + private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq[ClassTag[_]]( classTag[_root_.scala.Option[Int]].asInstanceOf[ClassTag[_]], classTag[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.AnotherException]].asInstanceOf[ClassTag[_]], classTag[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]].asInstanceOf[ClassTag[_]] ) - private[this] val structFields: Seq[ThriftStructField[Result]] = { - Seq( - new ThriftStructField[Result]( - SuccessField, - _root_.scala.Some(SuccessFieldManifest), - classOf[Result]) { - def getValue[R](struct: Result): R = struct.success.asInstanceOf[R] - }, - new ThriftStructField[Result]( - AxField, - _root_.scala.Some(AxFieldManifest), - classOf[Result]) { - def getValue[R](struct: Result): R = struct.ax.asInstanceOf[R] - }, - new ThriftStructField[Result]( - OceField, - _root_.scala.Some(OceFieldManifest), - classOf[Result]) { - def getValue[R](struct: Result): R = struct.oce.asInstanceOf[R] - } - ) - } + private[this] val structFields: Seq[ThriftStructField[Result]] = Seq[ThriftStructField[Result]]( + new ThriftStructField[Result]( + SuccessField, + _root_.scala.Some(SuccessFieldManifest), + classOf[Result]) { + def getValue[R](struct: Result): R = struct.success.asInstanceOf[R] + }, + new ThriftStructField[Result]( + AxField, + _root_.scala.Some(AxFieldManifest), + classOf[Result]) { + def getValue[R](struct: Result): R = struct.ax.asInstanceOf[R] + }, + new ThriftStructField[Result]( + OceField, + _root_.scala.Some(OceFieldManifest), + classOf[Result]) { + def getValue[R](struct: Result): R = struct.oce.asInstanceOf[R] + } + ) override lazy val metaData: ThriftStructMetaData[Result] = - new ThriftStructMetaData(this, structFields, fieldInfos, Seq(), structAnnotations) + new ThriftStructMetaData(this, structFields, fieldInfos, Nil, structAnnotations) /** * Checks that all required fields are non-null. @@ -663,13 +654,7 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift def withoutPassthroughFields(original: Result): Result = new Result( - success = - { - val field = original.success - field.map { field => - field - } - }, + success = original.success, ax = { val field = original.ax @@ -701,66 +686,58 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift var _done = false _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 0 => - _field.`type` match { - case TType.I32 => - success = _root_.scala.Some(readSuccessValue(_iprot)) - case _actualType => - val _expectedType = TType.I32 - throw new TProtocolException( - "Received wrong type for field 'success' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I32) { + success = _root_.scala.Some(readSuccessValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'success' (expected=%s, actual=%s).", + TType.I32, + _fieldType + ) } case 1 => - _field.`type` match { - case TType.STRUCT => - ax = _root_.scala.Some(readAxValue(_iprot)) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'ax' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + ax = _root_.scala.Some(readAxValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'ax' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case 2 => - _field.`type` match { - case TType.STRUCT => - oce = _root_.scala.Some(readOceValue(_iprot)) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'oce' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + oce = _root_.scala.Some(readOceValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'oce' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() new Result( success, ax, oce, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() @@ -853,13 +830,12 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift def _2: _root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.AnotherException] = ax def _3: _root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException] = oce - def toTuple: _root_.scala.Tuple3[Option[Int], Option[com.twitter.scrooge.test.gold.thriftscala.AnotherException], Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] = { - ( + def toTuple: _root_.scala.Tuple3[Option[Int], Option[com.twitter.scrooge.test.gold.thriftscala.AnotherException], Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] = + _root_.scala.Tuple3[Option[Int], Option[com.twitter.scrooge.test.gold.thriftscala.AnotherException], Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]]( success, ax, oce ) - } def successField: Option[Int] = success def exceptionFields: Iterable[Option[com.twitter.scrooge.ThriftException]] = Seq(ax, oce) @@ -893,14 +869,13 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift override def canEqual(other: Any): Boolean = other.isInstanceOf[Result] - private def _equals(x: Result, y: Result): Boolean = - x.productArity == y.productArity && - x.productIterator.sameElements(y.productIterator) && - x._passthroughFields == y._passthroughFields + private[this] def _equals(other: Result): Boolean = + this.productArity == other.productArity && + this.productIterator.sameElements(other.productIterator) && + this._passthroughFields == other._passthroughFields override def equals(other: Any): Boolean = - canEqual(other) && - _equals(this, other.asInstanceOf[Result]) + canEqual(other) && _equals(other.asInstanceOf[Result]) override def hashCode: Int = { _root_.scala.runtime.ScalaRunTime._hashCode(this) @@ -908,16 +883,6 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift override def toString: String = _root_.scala.runtime.ScalaRunTime._toString(this) - - override def productArity: Int = 3 - - override def productElement(n: Int): Any = n match { - case 0 => this.success - case 1 => this.ax - case 2 => this.oce - case _ => throw new IndexOutOfBoundsException(n.toString) - } - override def productPrefix: String = "Result" def _codec: ValidatingThriftStructCodec3[Result] = Result @@ -928,23 +893,24 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift private[thriftscala] class ResultStructBuilder(instance: _root_.scala.Option[Result], fieldTypes: IndexedSeq[ClassTag[_]]) extends StructBuilder[Result](fieldTypes) { - def build(): Result = instance match { - case _root_.scala.Some(i) => + def build(): Result = { + val _fieldArray = fieldArray // shadow variable + if (instance.isDefined) { + val instanceValue = instance.get Result( - (if (fieldArray(0) == null) i.success else fieldArray(0)).asInstanceOf[_root_.scala.Option[Int]], - (if (fieldArray(1) == null) i.ax else fieldArray(1)).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.AnotherException]], - (if (fieldArray(2) == null) i.oce else fieldArray(2)).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] + if (_fieldArray(0) == null) instanceValue.success else _fieldArray(0).asInstanceOf[_root_.scala.Option[Int]], + if (_fieldArray(1) == null) instanceValue.ax else _fieldArray(1).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.AnotherException]], + if (_fieldArray(2) == null) instanceValue.oce else _fieldArray(2).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] + ) + } else { + if (genericArrayOps(_fieldArray).contains(null)) throw new InvalidFieldsException(structBuildError("Result")) + Result( + _fieldArray(0).asInstanceOf[_root_.scala.Option[Int]], + _fieldArray(1).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.AnotherException]], + _fieldArray(2).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] ) - case _root_.scala.None => - if (fieldArray.contains(null)) throw new InvalidFieldsException(structBuildError("Result")) - else { - Result( - fieldArray(0).asInstanceOf[_root_.scala.Option[Int]], - fieldArray(1).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.AnotherException]], - fieldArray(2).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]] - ) - } } + } } val annotations: immutable$Map[String, String] = immutable$Map.empty @@ -1023,7 +989,7 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift def moreCoolThings(request: com.twitter.scrooge.test.gold.thriftscala.Request): Future[Int] = { val requestCtx = _root_.com.twitter.finagle.context.Contexts.local.getOrElse(_root_.com.twitter.finagle.thrift.Headers.Request.Key, () => _root_.com.twitter.finagle.thrift.Headers.Request.newValues) val scroogeRequest = _root_.com.twitter.scrooge.Request(requestCtx.values, self.MoreCoolThings.Args(request)) - servicePerEndpoint.moreCoolThings(scroogeRequest).transform(_root_.com.twitter.finagle.thrift.service.ThriftReqRepServicePerEndpoint.transformResult(_)) + servicePerEndpoint.moreCoolThings(scroogeRequest).transform(_root_.com.twitter.finagle.thrift.service.ThriftReqRepServicePerEndpoint.transformResult) } override def asClosable: _root_.com.twitter.util.Closable = @@ -1145,7 +1111,7 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift oprot.writeMessageBegin(new TMessage(name, TMessageType.EXCEPTION, seqid)) x.write(oprot) oprot.writeMessageEnd() - oprot.getTransport().flush() + oprot.getTransport.flush() // make a copy of the array of bytes to construct a new buffer because memoryBuffer is reusable Buf.ByteArray.Shared(memoryBuffer.getArray(), 0, memoryBuffer.length()) @@ -1154,7 +1120,7 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift } } - private def reply(name: String, seqid: Int, result: ThriftStruct): Buf = { + private[this] def reply(name: String, seqid: Int, result: ThriftStruct): Buf = { val memoryBuffer = tlReusableBuffer.get() try { val oprot = protocolFactory.getProtocol(memoryBuffer) @@ -1163,7 +1129,7 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift result.write(oprot) oprot.writeMessageEnd() _root_.com.twitter.finagle.tracing.Trace.recordBinary("srv/response_serialization_ns", System.nanoTime - start) - oprot.getTransport().flush() + oprot.getTransport.flush() // make a copy of the array of bytes to construct a new buffer because memoryBuffer is reusable Buf.ByteArray.Shared(memoryBuffer.getArray(), 0, memoryBuffer.length()) @@ -1172,43 +1138,17 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift } } - private def missingResult(name: String): TApplicationException = { - new TApplicationException( - TApplicationException.MISSING_RESULT, - name + " failed: unknown result" - ) - } - - private def setServiceName(ex: Throwable): Throwable = - if (this.serviceName == "") ex - else { - ex match { - case se: _root_.com.twitter.finagle.SourcedException => - se.serviceName = this.serviceName - se - case _ => ex - } - } - - private def recordRequest(methodStats: _root_.com.twitter.finagle.thrift.ThriftMethodStats): Unit = { - methodStats.requestsCounter.incr() - } - - private def recordResponse(reqRep: ctfs.ReqRep, methodStats: _root_.com.twitter.finagle.thrift.ThriftMethodStats): Unit = { + private[this] def recordResponse(reqRep: ctfs.ReqRep, methodStats: _root_.com.twitter.finagle.thrift.ThriftMethodStats): Unit = { ServerToReqRep.setCtx(reqRep) - val responseClass = responseClassifier.applyOrElse(reqRep, ctfs.ResponseClassifier.Default) - responseClass match { - case ctfs.ResponseClass.Ignorable => // Do nothing. - case ctfs.ResponseClass.Successful(_) => - methodStats.successCounter.incr() - case ctfs.ResponseClass.Failed(_) => - methodStats.failuresCounter.incr() - reqRep.response match { - case Throw(ex) => - methodStats.failuresScope.counter(Throwables.mkString(ex): _*).incr() - case _ => - } - } + val classified = responseClassifier.applyOrElse(reqRep, ctfs.ResponseClassifier.Default) + if (classified.isInstanceOf[ctfs.ResponseClass.Successful]) { + methodStats.successCounter.incr() + } else if (classified.isInstanceOf[ctfs.ResponseClass.Failed]) { + methodStats.failuresCounter.incr() + if (reqRep.response.isThrow) { + methodStats.failuresScope.counter(Throwables.mkString(reqRep.response.throwable): _*).incr() + } + } // Last ResponseClass is Ignorable, which we do not need to record } final protected def perMethodStatsFilter( @@ -1225,25 +1165,30 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift req: (TProtocol, Int), service: finagle$Service[(TProtocol, Int), RichResponse[method.Args, method.Result]] ): Future[Array[Byte]] = { - recordRequest(methodStats) - service(req).transform { - case Return(value) => - value match { - case SuccessfulResponse(args, _, result) => - recordResponse(ctfs.ReqRep(args, _root_.com.twitter.util.Return(result.successField.get)), methodStats) - case ProtocolExceptionResponse(args, _, exp) => - recordResponse(ctfs.ReqRep(args, _root_.com.twitter.util.Throw(exp)), methodStats) - case ThriftExceptionResponse(args, _, ex) => - val rep = ex match { - case exp: ThriftException => setServiceName(exp) - case _ => missingResult(serviceName) - } - recordResponse(ctfs.ReqRep(args, _root_.com.twitter.util.Throw(rep)), methodStats) + methodStats.requestsCounter.incr() + service(req).transform { response => + if (response.isReturn) { + val value = response.apply() + if (value.isInstanceOf[SuccessfulResponse[method.Args, method.Result]]) { + val succResp = value.asInstanceOf[SuccessfulResponse[method.Args, method.Result]] + recordResponse(ctfs.ReqRep(succResp.input, _root_.com.twitter.util.Return(succResp.result.successField.get)), methodStats) + } else if (value.isInstanceOf[ProtocolExceptionResponse[method.Args, method.Result]]) { + val protExResp = value.asInstanceOf[ProtocolExceptionResponse[method.Args, method.Result]] + recordResponse(ctfs.ReqRep(protExResp.input, _root_.com.twitter.util.Throw(protExResp.exception)), methodStats) + } else if (value.isInstanceOf[ThriftExceptionResponse[method.Args, method.Result]]) { + val thriftExResp = value.asInstanceOf[ThriftExceptionResponse[method.Args, method.Result]] + val rep: Throwable = if (thriftExResp.ex.isInstanceOf[ThriftException]) { + _root_.com.twitter.finagle.SourcedException.setServiceName(thriftExResp.ex, serviceName) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.missingResult(serviceName) + } + recordResponse(ctfs.ReqRep(thriftExResp.input, _root_.com.twitter.util.Throw(rep)), methodStats) } Future.value(Buf.ByteArray.Owned.extract(value.response)) - case t @ Throw(_) => - recordResponse(ctfs.ReqRep(req, t), methodStats) - Future.const(t.cast[Array[Byte]]) + } else { // Throw[_] + recordResponse(ctfs.ReqRep(req, response), methodStats) + Future.const(response.asInstanceOf[Throw[Array[Byte]]]) + } } } } @@ -1261,17 +1206,19 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift val iprot = request._1 val seqid = request._2 val res = service(request) - res.transform { - case _root_.com.twitter.util.Throw(e: TProtocolException) => + res.transform(resTry => { + if (resTry.isThrow && resTry.throwable.isInstanceOf[TProtocolException]) { + val underlyingException = resTry.throwable iprot.readMessageEnd() Future.value( ProtocolExceptionResponse( null, - exception("moreCoolThings", seqid, TApplicationException.PROTOCOL_ERROR, e.getMessage), - new TApplicationException(TApplicationException.PROTOCOL_ERROR, e.getMessage))) - case _ => + exception("moreCoolThings", seqid, TApplicationException.PROTOCOL_ERROR, underlyingException.getMessage), + new TApplicationException(TApplicationException.PROTOCOL_ERROR, underlyingException.getMessage))) + } else { res - } + } + }) } } @@ -1286,39 +1233,38 @@ object PlatinumService extends _root_.com.twitter.finagle.thrift.GeneratedThrift val args = MoreCoolThings.Args.decode(iprot) iprot.readMessageEnd() _root_.com.twitter.finagle.tracing.Trace.recordBinary("srv/request_deserialization_ns", System.nanoTime - start) - val res = _root_.com.twitter.finagle.context.Contexts.local.let( + _root_.com.twitter.finagle.context.Contexts.local.let( _root_.com.twitter.finagle.thrift.MethodMetadata.Key, _root_.com.twitter.finagle.thrift.MethodMetadata(MoreCoolThings)) { service(args) - } - res.transform { - case _root_.com.twitter.util.Return(value) => - val methodResult = MoreCoolThings.Result(success = Some(value)) + }.transform(resTry => { + if (resTry.isReturn) { + val methodResult = MoreCoolThings.Result(success = Some(resTry.apply())) Future.value( SuccessfulResponse( args, reply("moreCoolThings", seqid, methodResult), methodResult)) - case _root_.com.twitter.util.Throw(e: com.twitter.scrooge.test.gold.thriftscala.AnotherException) => { - Future.value( - ThriftExceptionResponse( - args, - reply("moreCoolThings", seqid, MoreCoolThings.Result(ax = Some(e))), - e)) + } else { // Throw[_] + val underlyingException = resTry.throwable + if (underlyingException.isInstanceOf[com.twitter.scrooge.test.gold.thriftscala.AnotherException]) + Future.value( + ThriftExceptionResponse( + args, + reply("moreCoolThings", seqid, MoreCoolThings.Result(ax = Some(underlyingException.asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.AnotherException]))), + underlyingException.asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.AnotherException])) + else if (underlyingException.isInstanceOf[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]) + Future.value( + ThriftExceptionResponse( + args, + reply("moreCoolThings", seqid, MoreCoolThings.Result(oce = Some(underlyingException.asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException]))), + underlyingException.asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.OverCapacityException])) + else + Future.const(resTry.asInstanceOf[Throw[RichResponse[MoreCoolThings.Args, MoreCoolThings.Result]]]) } - case _root_.com.twitter.util.Throw(e: com.twitter.scrooge.test.gold.thriftscala.OverCapacityException) => { - Future.value( - ThriftExceptionResponse( - args, - reply("moreCoolThings", seqid, MoreCoolThings.Result(oce = Some(e))), - e)) - } - case t @ _root_.com.twitter.util.Throw(_) => - Future.const(t.cast[RichResponse[MoreCoolThings.Args, MoreCoolThings.Result]]) - } + }) } } - statsFilter.andThen(protocolExnFilter).andThen(serdeFilter) } } diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/Recursive.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/Recursive.scala index c04a9a1f4..536ba38ed 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/Recursive.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/Recursive.scala @@ -33,9 +33,9 @@ object Recursive extends ValidatingThriftStructCodec3[Recursive] with StructBuil val NoPassthroughFields: immutable$Map[Short, TFieldBlob] = immutable$Map.empty[Short, TFieldBlob] val Struct: TStruct = new TStruct("Recursive") val IdField: TField = new TField("id", TType.I64, 1) - val IdFieldManifest: Manifest[Long] = implicitly[Manifest[Long]] + val IdFieldManifest: Manifest[Long] = manifest[Long] val RecRequestField: TField = new TField("recRequest", TType.STRUCT, 2) - val RecRequestFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Request] = implicitly[Manifest[com.twitter.scrooge.test.gold.thriftscala.Request]] + val RecRequestFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Request] = manifest[com.twitter.scrooge.test.gold.thriftscala.Request] /** * Field information in declaration order. @@ -65,33 +65,32 @@ object Recursive extends ValidatingThriftStructCodec3[Recursive] with StructBuil ) ) - lazy val structAnnotations: immutable$Map[String, String] = + + val structAnnotations: immutable$Map[String, String] = immutable$Map.empty[String, String] - private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq( + private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq[ClassTag[_]]( classTag[Long].asInstanceOf[ClassTag[_]], classTag[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Request]].asInstanceOf[ClassTag[_]] ) - private[this] val structFields: Seq[ThriftStructField[Recursive]] = { - Seq( - new ThriftStructField[Recursive]( - IdField, - _root_.scala.Some(IdFieldManifest), - classOf[Recursive]) { - def getValue[R](struct: Recursive): R = struct.id.asInstanceOf[R] - }, - new ThriftStructField[Recursive]( - RecRequestField, - _root_.scala.Some(RecRequestFieldManifest), - classOf[Recursive]) { - def getValue[R](struct: Recursive): R = struct.recRequest.asInstanceOf[R] - } - ) - } + private[this] val structFields: Seq[ThriftStructField[Recursive]] = Seq[ThriftStructField[Recursive]]( + new ThriftStructField[Recursive]( + IdField, + _root_.scala.Some(IdFieldManifest), + classOf[Recursive]) { + def getValue[R](struct: Recursive): R = struct.id.asInstanceOf[R] + }, + new ThriftStructField[Recursive]( + RecRequestField, + _root_.scala.Some(RecRequestFieldManifest), + classOf[Recursive]) { + def getValue[R](struct: Recursive): R = struct.recRequest.asInstanceOf[R] + } + ) override lazy val metaData: ThriftStructMetaData[Recursive] = - new ThriftStructMetaData(this, structFields, fieldInfos, Seq(), structAnnotations) + new ThriftStructMetaData(this, structFields, fieldInfos, Nil, structAnnotations) /** * Checks that all required fields are non-null. @@ -113,11 +112,7 @@ object Recursive extends ValidatingThriftStructCodec3[Recursive] with StructBuil def withoutPassthroughFields(original: Recursive): Recursive = new Immutable( - id = - { - val field = original.id - field - }, + id = original.id, recRequest = { val field = original.recRequest @@ -147,7 +142,7 @@ object Recursive extends ValidatingThriftStructCodec3[Recursive] with StructBuil val adaptContext = _iprot.adaptContext val reloadRequired = adaptContext.shouldReloadDecoder synchronized { - if (adaptiveDecoder == null || reloadRequired) { + if ((adaptiveDecoder eq null) || reloadRequired) { adaptiveDecoder = adaptContext.buildDecoder(this, fallbackDecoder, accessRecordingDecoderBuilder) } } @@ -182,48 +177,41 @@ object Recursive extends ValidatingThriftStructCodec3[Recursive] with StructBuil val _start_offset = _iprot.offset _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 1 => - _field.`type` match { - case TType.I64 => - - id = readIdValue(_iprot) - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'id' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + id = readIdValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'id' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 2 => - _field.`type` match { - case TType.STRUCT => - - recRequest = Some(readRecRequestValue(_iprot)) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'recRequest' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + recRequest = Some(readRecRequestValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'recRequest' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() new LazyImmutable( @@ -233,19 +221,22 @@ object Recursive extends ValidatingThriftStructCodec3[Recursive] with StructBuil _iprot.offset, id, recRequest, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() ) } - override def decode(_iprot: TProtocol): Recursive = - _iprot match { - case i: AdaptTProtocol => adaptiveDecode(i) - case i: LazyTProtocol => lazyDecode(i) - case i => eagerDecode(i) + override def decode(_iprot: TProtocol): Recursive = { + if (_iprot.isInstanceOf[LazyTProtocol]) { + lazyDecode(_iprot.asInstanceOf[LazyTProtocol]) + } else if (_iprot.isInstanceOf[AdaptTProtocol]) { + adaptiveDecode(_iprot.asInstanceOf[AdaptTProtocol]) + } else { + eagerDecode(_iprot) } + } private[thriftscala] def eagerDecode(_iprot: TProtocol): Recursive = { var id: Long = 0L @@ -254,52 +245,47 @@ object Recursive extends ValidatingThriftStructCodec3[Recursive] with StructBuil var _done = false _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 1 => - _field.`type` match { - case TType.I64 => - id = readIdValue(_iprot) - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'id' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + id = readIdValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'id' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 2 => - _field.`type` match { - case TType.STRUCT => - recRequest = _root_.scala.Some(readRecRequestValue(_iprot)) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'recRequest' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + recRequest = _root_.scala.Some(readRecRequestValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'recRequest' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() new Immutable( id, recRequest, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() @@ -388,9 +374,10 @@ object Recursive extends ValidatingThriftStructCodec3[Recursive] with StructBuil extends Recursive { override def write(_oprot: TProtocol): Unit = { - _oprot match { - case i: LazyTProtocol => i.writeRaw(_buf, _start_offset, _end_offset - _start_offset) - case _ => super.write(_oprot) + if (_oprot.isInstanceOf[LazyTProtocol]) { + _oprot.asInstanceOf[LazyTProtocol].writeRaw(_buf, _start_offset, _end_offset - _start_offset) + } else { + super.write(_oprot) } } @@ -406,7 +393,7 @@ object Recursive extends ValidatingThriftStructCodec3[Recursive] with StructBuil * With the class private and the contract that we throw away our mutable references * having the hash code lazy here is safe. */ - override lazy val hashCode = super.hashCode + override lazy val hashCode: Int = super.hashCode } /** @@ -442,12 +429,11 @@ trait Recursive def _1: Long = id def _2: _root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Request] = recRequest - def toTuple: _root_.scala.Tuple2[Long, Option[com.twitter.scrooge.test.gold.thriftscala.Request]] = { - ( + def toTuple: _root_.scala.Tuple2[Long, Option[com.twitter.scrooge.test.gold.thriftscala.Request]] = + _root_.scala.Tuple2[Long, Option[com.twitter.scrooge.test.gold.thriftscala.Request]]( id, recRequest ) - } /** @@ -456,44 +442,40 @@ trait Recursive * is known and not optional and set to None, then the field is serialized and returned. */ def getFieldBlob(_fieldId: Short): _root_.scala.Option[TFieldBlob] = { - lazy val _buff = new TMemoryBuffer(32) - lazy val _oprot = new TCompactProtocol(_buff) - _passthroughFields.get(_fieldId) match { - case blob: _root_.scala.Some[TFieldBlob] => blob - case _root_.scala.None => { - val _fieldOpt: _root_.scala.Option[TField] = - _fieldId match { - case 1 => - if (true) { - writeIdValue(id, _oprot) - _root_.scala.Some(Recursive.IdField) - } else { - _root_.scala.None - } - case 2 => - if (recRequest.isDefined) { - writeRecRequestValue(recRequest.get, _oprot) - _root_.scala.Some(Recursive.RecRequestField) - } else { - _root_.scala.None - } - case _ => _root_.scala.None - } - _fieldOpt match { - case _root_.scala.Some(_field) => - _root_.scala.Some(TFieldBlob(_field, Buf.ByteArray.Owned(_buff.getArray()))) - case _root_.scala.None => + val passedthroughValue = _passthroughFields.get(_fieldId) + if (passedthroughValue.isDefined) { + passedthroughValue + } else { + val _buff = new TMemoryBuffer(32) + val _oprot = new TCompactProtocol(_buff) + + val _fieldOpt: _root_.scala.Option[TField] = _fieldId match { + case 1 => + writeIdValue(id, _oprot) + _root_.scala.Some(Recursive.IdField) + case 2 => + if (recRequest.isDefined) { + writeRecRequestValue(recRequest.get, _oprot) + _root_.scala.Some(Recursive.RecRequestField) + } else { _root_.scala.None - } + } + case _ => _root_.scala.None + } + if (_fieldOpt.isDefined) { + _root_.scala.Some(TFieldBlob(_fieldOpt.get, Buf.ByteArray.Owned(_buff.getArray))) + } else { + _root_.scala.None } } } + /** * Collects TCompactProtocol-encoded field values according to `getFieldBlob` into a map. */ def getFieldBlobs(ids: TraversableOnce[Short]): immutable$Map[Short, TFieldBlob] = - (ids flatMap { id => getFieldBlob(id) map { id -> _ } }).toMap + (ids.flatMap { id => getFieldBlob(id).map { fieldBlob => (id, fieldBlob) } }).toMap /** * Sets a field using a TCompactProtocol-encoded binary blob. If the field is a known @@ -510,7 +492,7 @@ trait Recursive id = readIdValue(_blob.read) case 2 => recRequest = _root_.scala.Some(readRecRequestValue(_blob.read)) - case _ => _passthroughFields += (_blob.id -> _blob) + case _ => _passthroughFields += _root_.scala.Tuple2(_blob.id, _blob) } new Immutable( id, @@ -577,14 +559,13 @@ trait Recursive override def canEqual(other: Any): Boolean = other.isInstanceOf[Recursive] - private def _equals(x: Recursive, y: Recursive): Boolean = - x.productArity == y.productArity && - x.productIterator.sameElements(y.productIterator) && - x._passthroughFields == y._passthroughFields + private[this] def _equals(other: Recursive): Boolean = + this.productArity == other.productArity && + this.productIterator.sameElements(other.productIterator) && + this._passthroughFields == other._passthroughFields override def equals(other: Any): Boolean = - canEqual(other) && - _equals(this, other.asInstanceOf[Recursive]) + canEqual(other) && _equals(other.asInstanceOf[Recursive]) override def hashCode: Int = { _root_.scala.runtime.ScalaRunTime._hashCode(this) @@ -592,15 +573,6 @@ trait Recursive override def toString: String = _root_.scala.runtime.ScalaRunTime._toString(this) - - override def productArity: Int = 2 - - override def productElement(n: Int): Any = n match { - case 0 => this.id - case 1 => this.recRequest - case _ => throw new IndexOutOfBoundsException(n.toString) - } - override def productPrefix: String = "Recursive" def _codec: ValidatingThriftStructCodec3[Recursive] = Recursive @@ -611,21 +583,22 @@ trait Recursive private[thriftscala] class RecursiveStructBuilder(instance: _root_.scala.Option[Recursive], fieldTypes: IndexedSeq[ClassTag[_]]) extends StructBuilder[Recursive](fieldTypes) { - def build(): Recursive = instance match { - case _root_.scala.Some(i) => + def build(): Recursive = { + val _fieldArray = fieldArray // shadow variable + if (instance.isDefined) { + val instanceValue = instance.get Recursive( - (if (fieldArray(0) == null) i.id else fieldArray(0)).asInstanceOf[Long], - (if (fieldArray(1) == null) i.recRequest else fieldArray(1)).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Request]] + if (_fieldArray(0) == null) instanceValue.id else _fieldArray(0).asInstanceOf[Long], + if (_fieldArray(1) == null) instanceValue.recRequest else _fieldArray(1).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Request]] + ) + } else { + if (genericArrayOps(_fieldArray).contains(null)) throw new InvalidFieldsException(structBuildError("Recursive")) + Recursive( + _fieldArray(0).asInstanceOf[Long], + _fieldArray(1).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Request]] ) - case _root_.scala.None => - if (fieldArray.contains(null)) throw new InvalidFieldsException(structBuildError("Recursive")) - else { - Recursive( - fieldArray(0).asInstanceOf[Long], - fieldArray(1).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Request]] - ) - } } + } } private class Recursive__AdaptDecoder { @@ -651,59 +624,63 @@ private class Recursive__AdaptDecoder { AdaptTProtocol.usedEndMarker(2) _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() + val _fieldType = _field.`type` if (_field.`type` == TType.STOP) { _done = true } else { _field.id match { case 1 => { - _field.`type` match { - case TType.I64 => - AdaptTProtocol.usedStartMarker(1) - id = Recursive.readIdValue(_iprot) - AdaptTProtocol.usedEndMarker(1) - AdaptTProtocol.unusedStartMarker(1) - _iprot.offsetSkipI64() - AdaptTProtocol.unusedEndMarker(1) - case _actualType => - val _expectedType = TType.I64 - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "id") + if (_fieldType == TType.I64) { + AdaptTProtocol.usedStartMarker(1) + id = Recursive.readIdValue(_iprot) + AdaptTProtocol.usedEndMarker(1) + AdaptTProtocol.unusedStartMarker(1) + _iprot.offsetSkipI64() + AdaptTProtocol.unusedEndMarker(1) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.I64, + _fieldType, + "id" + ) } AdaptTProtocol.usedStartMarker(1) adapt.set_id(id) AdaptTProtocol.usedEndMarker(1) } case 2 => { - _field.`type` match { - case TType.STRUCT => - AdaptTProtocol.usedStartMarker(2) - recRequest = _root_.scala.Some(Recursive.readRecRequestValue(_iprot)) - AdaptTProtocol.usedEndMarker(2) - AdaptTProtocol.unusedStartMarker(2) - _iprot.offsetSkipStruct() - AdaptTProtocol.unusedEndMarker(2) - case _actualType => - val _expectedType = TType.STRUCT - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "recRequest") + if (_fieldType == TType.STRUCT) { + AdaptTProtocol.usedStartMarker(2) + recRequest = _root_.scala.Some(Recursive.readRecRequestValue(_iprot)) + AdaptTProtocol.usedEndMarker(2) + AdaptTProtocol.unusedStartMarker(2) + _iprot.offsetSkipStruct() + AdaptTProtocol.unusedEndMarker(2) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.STRUCT, + _fieldType, + "recRequest" + ) } AdaptTProtocol.usedStartMarker(2) adapt.set_recRequest(recRequest) AdaptTProtocol.usedEndMarker(2) } - case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() adapt.set__endOffset(_iprot.offset) - if (_passthroughFields != null) { + if (_passthroughFields ne null) { adapt.set__passthroughFields(_passthroughFields.result()) } adapt @@ -744,7 +721,7 @@ private class Recursive__Adapt( private[this] var _end_offset: Int = _ - def set__endOffset(offset: Int) = _end_offset = offset + def set__endOffset(offset: Int): Unit = _end_offset = offset private[this] var __passthroughFields: immutable$Map[Short, TFieldBlob] = Recursive.NoPassthroughFields def set__passthroughFields(passthroughFields: immutable$Map[Short, TFieldBlob]): Unit = @@ -766,9 +743,10 @@ private class Recursive__Adapt( override lazy val hashCode: Int = super.hashCode override def write(_oprot: TProtocol): Unit = { - _oprot match { - case i: AdaptTProtocol => i.writeRaw(_buf, _start_offset, _end_offset - _start_offset) - case _ => super.write(_oprot) + if (_oprot.isInstanceOf[AdaptTProtocol]) { + _oprot.asInstanceOf[AdaptTProtocol].writeRaw(_buf, _start_offset, _end_offset - _start_offset) + } else { + super.write(_oprot) } } } diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/Request.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/Request.scala index a30d6737d..355452af3 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/Request.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/Request.scala @@ -35,35 +35,35 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF val NoPassthroughFields: immutable$Map[Short, TFieldBlob] = immutable$Map.empty[Short, TFieldBlob] val Struct: TStruct = new TStruct("Request") val AListField: TField = new TField("aList", TType.LIST, 1) - val AListFieldManifest: Manifest[_root_.scala.collection.Seq[String]] = implicitly[Manifest[_root_.scala.collection.Seq[String]]] + val AListFieldManifest: Manifest[_root_.scala.collection.Seq[String]] = manifest[_root_.scala.collection.Seq[String]] val ASetField: TField = new TField("aSet", TType.SET, 2) - val ASetFieldManifest: Manifest[_root_.scala.collection.Set[Int]] = implicitly[Manifest[_root_.scala.collection.Set[Int]]] + val ASetFieldManifest: Manifest[_root_.scala.collection.Set[Int]] = manifest[_root_.scala.collection.Set[Int]] val AMapField: TField = new TField("aMap", TType.MAP, 3) - val AMapFieldManifest: Manifest[_root_.scala.collection.Map[Long, Long]] = implicitly[Manifest[_root_.scala.collection.Map[Long, Long]]] + val AMapFieldManifest: Manifest[_root_.scala.collection.Map[Long, Long]] = manifest[_root_.scala.collection.Map[Long, Long]] val ARequestField: TField = new TField("aRequest", TType.STRUCT, 4) - val ARequestFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Request] = implicitly[Manifest[com.twitter.scrooge.test.gold.thriftscala.Request]] + val ARequestFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Request] = manifest[com.twitter.scrooge.test.gold.thriftscala.Request] val SubRequestsField: TField = new TField("subRequests", TType.LIST, 5) - val SubRequestsFieldManifest: Manifest[_root_.scala.collection.Seq[com.twitter.scrooge.test.gold.thriftscala.Request]] = implicitly[Manifest[_root_.scala.collection.Seq[com.twitter.scrooge.test.gold.thriftscala.Request]]] + val SubRequestsFieldManifest: Manifest[_root_.scala.collection.Seq[com.twitter.scrooge.test.gold.thriftscala.Request]] = manifest[_root_.scala.collection.Seq[com.twitter.scrooge.test.gold.thriftscala.Request]] val HasDefaultField: TField = new TField("hasDefault", TType.STRING, 6) - val HasDefaultFieldManifest: Manifest[String] = implicitly[Manifest[String]] + val HasDefaultFieldManifest: Manifest[String] = manifest[String] val NoCommentField: TField = new TField("noComment", TType.I64, 7) - val NoCommentFieldManifest: Manifest[Long] = implicitly[Manifest[Long]] + val NoCommentFieldManifest: Manifest[Long] = manifest[Long] val DoubleSlashCommentField: TField = new TField("doubleSlashComment", TType.I64, 8) - val DoubleSlashCommentFieldManifest: Manifest[Long] = implicitly[Manifest[Long]] + val DoubleSlashCommentFieldManifest: Manifest[Long] = manifest[Long] val HashtagCommentField: TField = new TField("hashtagComment", TType.I64, 9) - val HashtagCommentFieldManifest: Manifest[Long] = implicitly[Manifest[Long]] + val HashtagCommentFieldManifest: Manifest[Long] = manifest[Long] val SingleAsteriskCommentField: TField = new TField("singleAsteriskComment", TType.I64, 10) - val SingleAsteriskCommentFieldManifest: Manifest[Long] = implicitly[Manifest[Long]] + val SingleAsteriskCommentFieldManifest: Manifest[Long] = manifest[Long] val DocStringCommentField: TField = new TField("docStringComment", TType.I64, 11) - val DocStringCommentFieldManifest: Manifest[Long] = implicitly[Manifest[Long]] + val DocStringCommentFieldManifest: Manifest[Long] = manifest[Long] val RecRequestField: TField = new TField("recRequest", TType.STRUCT, 12) - val RecRequestFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Recursive] = implicitly[Manifest[com.twitter.scrooge.test.gold.thriftscala.Recursive]] + val RecRequestFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.Recursive] = manifest[com.twitter.scrooge.test.gold.thriftscala.Recursive] val RequiredFieldField: TField = new TField("requiredField", TType.STRING, 13) - val RequiredFieldFieldManifest: Manifest[String] = implicitly[Manifest[String]] + val RequiredFieldFieldManifest: Manifest[String] = manifest[String] val ConstructionRequiredFieldField: TField = new TField("constructionRequiredField", TType.I64, 14) - val ConstructionRequiredFieldFieldManifest: Manifest[Long] = implicitly[Manifest[Long]] + val ConstructionRequiredFieldFieldManifest: Manifest[Long] = manifest[Long] val AnInt8Field: TField = new TField("anInt8", TType.BYTE, 15) - val AnInt8FieldManifest: Manifest[Byte] = implicitly[Manifest[Byte]] + val AnInt8FieldManifest: Manifest[Byte] = manifest[Byte] /** * Field information in declaration order. @@ -75,7 +75,7 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF false, AListFieldManifest, _root_.scala.None, - _root_.scala.Some(implicitly[Manifest[String]]), + _root_.scala.Some(manifest[String]), immutable$Map.empty[String, String], immutable$Map.empty[String, String], None @@ -86,7 +86,7 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF false, ASetFieldManifest, _root_.scala.None, - _root_.scala.Some(implicitly[Manifest[Int]]), + _root_.scala.Some(manifest[Int]), immutable$Map.empty[String, String], immutable$Map.empty[String, String], None @@ -96,8 +96,8 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF false, false, AMapFieldManifest, - _root_.scala.Some(implicitly[Manifest[Long]]), - _root_.scala.Some(implicitly[Manifest[Long]]), + _root_.scala.Some(manifest[Long]), + _root_.scala.Some(manifest[Long]), immutable$Map.empty[String, String], immutable$Map.empty[String, String], None @@ -119,7 +119,7 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF false, SubRequestsFieldManifest, _root_.scala.None, - _root_.scala.Some(implicitly[Manifest[com.twitter.scrooge.test.gold.thriftscala.Request]]), + _root_.scala.Some(manifest[com.twitter.scrooge.test.gold.thriftscala.Request]), immutable$Map.empty[String, String], immutable$Map.empty[String, String], None @@ -165,8 +165,8 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF _root_.scala.None, _root_.scala.None, immutable$Map.empty[String, String], - immutable$Map( - "a.b.c" -> "ignored" + immutable$Map.apply[String, String]( + ("a.b.c", "ignored") ), None ), @@ -178,9 +178,9 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF _root_.scala.None, _root_.scala.None, immutable$Map.empty[String, String], - immutable$Map( - "s.field.annotation.one" -> "a", - "two" -> "b" + immutable$Map.apply[String, String]( + ("s.field.annotation.one", "a"), + ("two", "b") ), None ), @@ -225,8 +225,8 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF _root_.scala.None, _root_.scala.None, immutable$Map.empty[String, String], - immutable$Map( - "construction_required" -> "true" + immutable$Map.apply[String, String]( + ("construction_required", "true") ), None ), @@ -243,13 +243,14 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF ) ) + lazy val structAnnotations: immutable$Map[String, String] = immutable$Map[String, String]( - "s.annotation.one" -> "something", - "s.annotation.two" -> "other" + ("s.annotation.one", "something"), + ("s.annotation.two", "other") ) - private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq( + private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq[ClassTag[_]]( classTag[_root_.scala.collection.Seq[String]].asInstanceOf[ClassTag[_]], classTag[_root_.scala.collection.Set[Int]].asInstanceOf[ClassTag[_]], classTag[_root_.scala.collection.Map[Long, Long]].asInstanceOf[ClassTag[_]], @@ -267,109 +268,107 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF classTag[_root_.scala.Option[Byte]].asInstanceOf[ClassTag[_]] ) - private[this] val structFields: Seq[ThriftStructField[Request]] = { - Seq( - new ThriftStructField[Request]( - AListField, - _root_.scala.Some(AListFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.aList.asInstanceOf[R] - }, - new ThriftStructField[Request]( - ASetField, - _root_.scala.Some(ASetFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.aSet.asInstanceOf[R] - }, - new ThriftStructField[Request]( - AMapField, - _root_.scala.Some(AMapFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.aMap.asInstanceOf[R] - }, - new ThriftStructField[Request]( - ARequestField, - _root_.scala.Some(ARequestFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.aRequest.asInstanceOf[R] - }, - new ThriftStructField[Request]( - SubRequestsField, - _root_.scala.Some(SubRequestsFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.subRequests.asInstanceOf[R] - }, - new ThriftStructField[Request]( - HasDefaultField, - _root_.scala.Some(HasDefaultFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.hasDefault.asInstanceOf[R] - }, - new ThriftStructField[Request]( - NoCommentField, - _root_.scala.Some(NoCommentFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.noComment.asInstanceOf[R] - }, - new ThriftStructField[Request]( - DoubleSlashCommentField, - _root_.scala.Some(DoubleSlashCommentFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.doubleSlashComment.asInstanceOf[R] - }, - new ThriftStructField[Request]( - HashtagCommentField, - _root_.scala.Some(HashtagCommentFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.hashtagComment.asInstanceOf[R] - }, - new ThriftStructField[Request]( - SingleAsteriskCommentField, - _root_.scala.Some(SingleAsteriskCommentFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.singleAsteriskComment.asInstanceOf[R] - }, - new ThriftStructField[Request]( - DocStringCommentField, - _root_.scala.Some(DocStringCommentFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.docStringComment.asInstanceOf[R] - }, - new ThriftStructField[Request]( - RecRequestField, - _root_.scala.Some(RecRequestFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.recRequest.asInstanceOf[R] - }, - new ThriftStructField[Request]( - RequiredFieldField, - _root_.scala.Some(RequiredFieldFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.requiredField.asInstanceOf[R] - }, - new ThriftStructField[Request]( - ConstructionRequiredFieldField, - _root_.scala.Some(ConstructionRequiredFieldFieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.constructionRequiredField.asInstanceOf[R] - }, - new ThriftStructField[Request]( - AnInt8Field, - _root_.scala.Some(AnInt8FieldManifest), - classOf[Request]) { - def getValue[R](struct: Request): R = struct.anInt8.asInstanceOf[R] - } - ) - } + private[this] val structFields: Seq[ThriftStructField[Request]] = Seq[ThriftStructField[Request]]( + new ThriftStructField[Request]( + AListField, + _root_.scala.Some(AListFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.aList.asInstanceOf[R] + }, + new ThriftStructField[Request]( + ASetField, + _root_.scala.Some(ASetFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.aSet.asInstanceOf[R] + }, + new ThriftStructField[Request]( + AMapField, + _root_.scala.Some(AMapFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.aMap.asInstanceOf[R] + }, + new ThriftStructField[Request]( + ARequestField, + _root_.scala.Some(ARequestFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.aRequest.asInstanceOf[R] + }, + new ThriftStructField[Request]( + SubRequestsField, + _root_.scala.Some(SubRequestsFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.subRequests.asInstanceOf[R] + }, + new ThriftStructField[Request]( + HasDefaultField, + _root_.scala.Some(HasDefaultFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.hasDefault.asInstanceOf[R] + }, + new ThriftStructField[Request]( + NoCommentField, + _root_.scala.Some(NoCommentFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.noComment.asInstanceOf[R] + }, + new ThriftStructField[Request]( + DoubleSlashCommentField, + _root_.scala.Some(DoubleSlashCommentFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.doubleSlashComment.asInstanceOf[R] + }, + new ThriftStructField[Request]( + HashtagCommentField, + _root_.scala.Some(HashtagCommentFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.hashtagComment.asInstanceOf[R] + }, + new ThriftStructField[Request]( + SingleAsteriskCommentField, + _root_.scala.Some(SingleAsteriskCommentFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.singleAsteriskComment.asInstanceOf[R] + }, + new ThriftStructField[Request]( + DocStringCommentField, + _root_.scala.Some(DocStringCommentFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.docStringComment.asInstanceOf[R] + }, + new ThriftStructField[Request]( + RecRequestField, + _root_.scala.Some(RecRequestFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.recRequest.asInstanceOf[R] + }, + new ThriftStructField[Request]( + RequiredFieldField, + _root_.scala.Some(RequiredFieldFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.requiredField.asInstanceOf[R] + }, + new ThriftStructField[Request]( + ConstructionRequiredFieldField, + _root_.scala.Some(ConstructionRequiredFieldFieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.constructionRequiredField.asInstanceOf[R] + }, + new ThriftStructField[Request]( + AnInt8Field, + _root_.scala.Some(AnInt8FieldManifest), + classOf[Request]) { + def getValue[R](struct: Request): R = struct.anInt8.asInstanceOf[R] + } + ) override lazy val metaData: ThriftStructMetaData[Request] = - new ThriftStructMetaData(this, structFields, fieldInfos, Seq(), structAnnotations) + new ThriftStructMetaData(this, structFields, fieldInfos, Nil, structAnnotations) /** * Checks that all required fields are non-null. */ def validate(_item: Request): Unit = { - if (_item.requiredField == null) throw new TProtocolException("Required field requiredField cannot be null") + if (_item.requiredField eq null) throw new TProtocolException("Required field requiredField cannot be null") } /** @@ -391,7 +390,7 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF buf ++= validateField(item.singleAsteriskComment) buf ++= validateField(item.docStringComment) buf ++= validateField(item.recRequest) - if (item.requiredField == null) + if (item.requiredField eq null) buf += com.twitter.scrooge.validation.MissingRequiredField(fieldInfos.apply(12)) buf ++= validateField(item.requiredField) if (item.constructionRequiredField.isEmpty) @@ -405,39 +404,9 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF def withoutPassthroughFields(original: Request): Request = new Immutable( - aList = - { - val field = original.aList - field.map { field => - field - } - }, - aSet = - { - val field = original.aSet - field.map { field => - field - } - }, - aMap = - { - val field = original.aMap - field.map { case (key, value) => - val newKey = { - val field = key - field - } - - - val newValue = { - val field = value - field - } - - - newKey -> newValue - } - }, + aList = original.aList, + aSet = original.aSet, + aMap = original.aMap, aRequest = { val field = original.aRequest @@ -452,46 +421,12 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF com.twitter.scrooge.test.gold.thriftscala.Request.withoutPassthroughFields(field) } }, - hasDefault = - { - val field = original.hasDefault - field - }, - noComment = - { - val field = original.noComment - field.map { field => - field - } - }, - doubleSlashComment = - { - val field = original.doubleSlashComment - field.map { field => - field - } - }, - hashtagComment = - { - val field = original.hashtagComment - field.map { field => - field - } - }, - singleAsteriskComment = - { - val field = original.singleAsteriskComment - field.map { field => - field - } - }, - docStringComment = - { - val field = original.docStringComment - field.map { field => - field - } - }, + hasDefault = original.hasDefault, + noComment = original.noComment, + doubleSlashComment = original.doubleSlashComment, + hashtagComment = original.hashtagComment, + singleAsteriskComment = original.singleAsteriskComment, + docStringComment = original.docStringComment, recRequest = { val field = original.recRequest @@ -499,25 +434,9 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF com.twitter.scrooge.test.gold.thriftscala.Recursive.withoutPassthroughFields(field) } }, - requiredField = - { - val field = original.requiredField - field - }, - constructionRequiredField = - { - val field = original.constructionRequiredField - field.map { field => - field - } - }, - anInt8 = - { - val field = original.anInt8 - field.map { field => - field - } - } + requiredField = original.requiredField, + constructionRequiredField = original.constructionRequiredField, + anInt8 = original.anInt8 ) def newBuilder(): StructBuilder[Request] = new RequestStructBuilder(_root_.scala.None, fieldTypes) @@ -540,7 +459,7 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF val adaptContext = _iprot.adaptContext val reloadRequired = adaptContext.shouldReloadDecoder synchronized { - if (adaptiveDecoder == null || reloadRequired) { + if ((adaptiveDecoder eq null) || reloadRequired) { adaptiveDecoder = adaptContext.buildDecoder(this, fallbackDecoder, accessRecordingDecoderBuilder) } } @@ -641,231 +560,172 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF val _start_offset = _iprot.offset _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 1 => - _field.`type` match { - case TType.LIST => - - aList = readAListValue(_iprot) - case _actualType => - val _expectedType = TType.LIST - throw new TProtocolException( - "Received wrong type for field 'aList' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.LIST) { + aList = readAListValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'aList' (expected=%s, actual=%s).", + TType.LIST, + _fieldType + ) } case 2 => - _field.`type` match { - case TType.SET => - - aSet = readASetValue(_iprot) - case _actualType => - val _expectedType = TType.SET - throw new TProtocolException( - "Received wrong type for field 'aSet' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.SET) { + aSet = readASetValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'aSet' (expected=%s, actual=%s).", + TType.SET, + _fieldType + ) } case 3 => - _field.`type` match { - case TType.MAP => - - aMap = readAMapValue(_iprot) - case _actualType => - val _expectedType = TType.MAP - throw new TProtocolException( - "Received wrong type for field 'aMap' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.MAP) { + aMap = readAMapValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'aMap' (expected=%s, actual=%s).", + TType.MAP, + _fieldType + ) } case 4 => - _field.`type` match { - case TType.STRUCT => - - aRequest = Some(readARequestValue(_iprot)) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'aRequest' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + aRequest = Some(readARequestValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'aRequest' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case 5 => - _field.`type` match { - case TType.LIST => - - subRequests = readSubRequestsValue(_iprot) - case _actualType => - val _expectedType = TType.LIST - throw new TProtocolException( - "Received wrong type for field 'subRequests' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.LIST) { + subRequests = readSubRequestsValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'subRequests' (expected=%s, actual=%s).", + TType.LIST, + _fieldType + ) } case 6 => - _field.`type` match { - case TType.STRING => - hasDefaultOffset = _iprot.offsetSkipString - - case _actualType => - val _expectedType = TType.STRING - throw new TProtocolException( - "Received wrong type for field 'hasDefault' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRING) { + hasDefaultOffset = _iprot.offsetSkipString() + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'hasDefault' (expected=%s, actual=%s).", + TType.STRING, + _fieldType + ) } case 7 => - _field.`type` match { - case TType.I64 => - noCommentOffset = _iprot.offsetSkipI64 - - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'noComment' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + noCommentOffset = _iprot.offsetSkipI64() + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'noComment' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 8 => - _field.`type` match { - case TType.I64 => - doubleSlashCommentOffset = _iprot.offsetSkipI64 - - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'doubleSlashComment' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + doubleSlashCommentOffset = _iprot.offsetSkipI64() + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'doubleSlashComment' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 9 => - _field.`type` match { - case TType.I64 => - hashtagCommentOffset = _iprot.offsetSkipI64 - - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'hashtagComment' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + hashtagCommentOffset = _iprot.offsetSkipI64() + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'hashtagComment' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 10 => - _field.`type` match { - case TType.I64 => - singleAsteriskCommentOffset = _iprot.offsetSkipI64 - - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'singleAsteriskComment' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + singleAsteriskCommentOffset = _iprot.offsetSkipI64() + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'singleAsteriskComment' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 11 => - _field.`type` match { - case TType.I64 => - docStringCommentOffset = _iprot.offsetSkipI64 - - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'docStringComment' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + docStringCommentOffset = _iprot.offsetSkipI64() + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'docStringComment' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 12 => - _field.`type` match { - case TType.STRUCT => - - recRequest = Some(readRecRequestValue(_iprot)) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'recRequest' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + recRequest = Some(readRecRequestValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'recRequest' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case 13 => - _field.`type` match { - case TType.STRING => - requiredFieldOffset = _iprot.offsetSkipString - - _got_requiredField = true - case _actualType => - val _expectedType = TType.STRING - throw new TProtocolException( - "Received wrong type for field 'requiredField' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRING) { + requiredFieldOffset = _iprot.offsetSkipString() + _got_requiredField = true + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'requiredField' (expected=%s, actual=%s).", + TType.STRING, + _fieldType + ) } case 14 => - _field.`type` match { - case TType.I64 => - constructionRequiredFieldOffset = _iprot.offsetSkipI64 - - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'constructionRequiredField' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + constructionRequiredFieldOffset = _iprot.offsetSkipI64() + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'constructionRequiredField' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 15 => - _field.`type` match { - case TType.BYTE => - anInt8Offset = _iprot.offsetSkipByte - - case _actualType => - val _expectedType = TType.BYTE - throw new TProtocolException( - "Received wrong type for field 'anInt8' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.BYTE) { + anInt8Offset = _iprot.offsetSkipByte() + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'anInt8' (expected=%s, actual=%s).", + TType.BYTE, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() if (!_got_requiredField) throw new TProtocolException("Required field 'requiredField' was not found in serialized data for struct Request") @@ -889,19 +749,22 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF requiredFieldOffset, constructionRequiredFieldOffset, anInt8Offset, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() ) } - override def decode(_iprot: TProtocol): Request = - _iprot match { - case i: AdaptTProtocol => adaptiveDecode(i) - case i: LazyTProtocol => lazyDecode(i) - case i => eagerDecode(i) + override def decode(_iprot: TProtocol): Request = { + if (_iprot.isInstanceOf[LazyTProtocol]) { + lazyDecode(_iprot.asInstanceOf[LazyTProtocol]) + } else if (_iprot.isInstanceOf[AdaptTProtocol]) { + adaptiveDecode(_iprot.asInstanceOf[AdaptTProtocol]) + } else { + eagerDecode(_iprot) } + } private[thriftscala] def eagerDecode(_iprot: TProtocol): Request = { var aList: _root_.scala.collection.Seq[String] = _root_.scala.collection.immutable.Nil @@ -924,216 +787,172 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF var _done = false _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 1 => - _field.`type` match { - case TType.LIST => - aList = readAListValue(_iprot) - case _actualType => - val _expectedType = TType.LIST - throw new TProtocolException( - "Received wrong type for field 'aList' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.LIST) { + aList = readAListValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'aList' (expected=%s, actual=%s).", + TType.LIST, + _fieldType + ) } case 2 => - _field.`type` match { - case TType.SET => - aSet = readASetValue(_iprot) - case _actualType => - val _expectedType = TType.SET - throw new TProtocolException( - "Received wrong type for field 'aSet' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.SET) { + aSet = readASetValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'aSet' (expected=%s, actual=%s).", + TType.SET, + _fieldType + ) } case 3 => - _field.`type` match { - case TType.MAP => - aMap = readAMapValue(_iprot) - case _actualType => - val _expectedType = TType.MAP - throw new TProtocolException( - "Received wrong type for field 'aMap' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.MAP) { + aMap = readAMapValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'aMap' (expected=%s, actual=%s).", + TType.MAP, + _fieldType + ) } case 4 => - _field.`type` match { - case TType.STRUCT => - aRequest = _root_.scala.Some(readARequestValue(_iprot)) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'aRequest' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + aRequest = _root_.scala.Some(readARequestValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'aRequest' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case 5 => - _field.`type` match { - case TType.LIST => - subRequests = readSubRequestsValue(_iprot) - case _actualType => - val _expectedType = TType.LIST - throw new TProtocolException( - "Received wrong type for field 'subRequests' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.LIST) { + subRequests = readSubRequestsValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'subRequests' (expected=%s, actual=%s).", + TType.LIST, + _fieldType + ) } case 6 => - _field.`type` match { - case TType.STRING => - hasDefault = readHasDefaultValue(_iprot) - case _actualType => - val _expectedType = TType.STRING - throw new TProtocolException( - "Received wrong type for field 'hasDefault' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRING) { + hasDefault = readHasDefaultValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'hasDefault' (expected=%s, actual=%s).", + TType.STRING, + _fieldType + ) } case 7 => - _field.`type` match { - case TType.I64 => - noComment = _root_.scala.Some(readNoCommentValue(_iprot)) - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'noComment' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + noComment = _root_.scala.Some(readNoCommentValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'noComment' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 8 => - _field.`type` match { - case TType.I64 => - doubleSlashComment = _root_.scala.Some(readDoubleSlashCommentValue(_iprot)) - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'doubleSlashComment' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + doubleSlashComment = _root_.scala.Some(readDoubleSlashCommentValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'doubleSlashComment' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 9 => - _field.`type` match { - case TType.I64 => - hashtagComment = _root_.scala.Some(readHashtagCommentValue(_iprot)) - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'hashtagComment' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + hashtagComment = _root_.scala.Some(readHashtagCommentValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'hashtagComment' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 10 => - _field.`type` match { - case TType.I64 => - singleAsteriskComment = _root_.scala.Some(readSingleAsteriskCommentValue(_iprot)) - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'singleAsteriskComment' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + singleAsteriskComment = _root_.scala.Some(readSingleAsteriskCommentValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'singleAsteriskComment' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 11 => - _field.`type` match { - case TType.I64 => - docStringComment = _root_.scala.Some(readDocStringCommentValue(_iprot)) - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'docStringComment' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + docStringComment = _root_.scala.Some(readDocStringCommentValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'docStringComment' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 12 => - _field.`type` match { - case TType.STRUCT => - recRequest = _root_.scala.Some(readRecRequestValue(_iprot)) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'recRequest' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + recRequest = _root_.scala.Some(readRecRequestValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'recRequest' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case 13 => - _field.`type` match { - case TType.STRING => - requiredField = readRequiredFieldValue(_iprot) - _got_requiredField = true - case _actualType => - val _expectedType = TType.STRING - throw new TProtocolException( - "Received wrong type for field 'requiredField' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRING) { + requiredField = readRequiredFieldValue(_iprot) + _got_requiredField = true + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'requiredField' (expected=%s, actual=%s).", + TType.STRING, + _fieldType + ) } case 14 => - _field.`type` match { - case TType.I64 => - constructionRequiredField = _root_.scala.Some(readConstructionRequiredFieldValue(_iprot)) - case _actualType => - val _expectedType = TType.I64 - throw new TProtocolException( - "Received wrong type for field 'constructionRequiredField' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I64) { + constructionRequiredField = _root_.scala.Some(readConstructionRequiredFieldValue(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'constructionRequiredField' (expected=%s, actual=%s).", + TType.I64, + _fieldType + ) } case 15 => - _field.`type` match { - case TType.BYTE => - anInt8 = _root_.scala.Some(readAnInt8Value(_iprot)) - case _actualType => - val _expectedType = TType.BYTE - throw new TProtocolException( - "Received wrong type for field 'anInt8' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.BYTE) { + anInt8 = _root_.scala.Some(readAnInt8Value(_iprot)) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'anInt8' (expected=%s, actual=%s).", + TType.BYTE, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() if (!_got_requiredField) throw new TProtocolException("Required field 'requiredField' was not found in serialized data for struct Request") @@ -1153,7 +972,7 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF requiredField, constructionRequiredField, anInt8, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() @@ -1206,12 +1025,12 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF } else { val _rv = new _root_.scala.collection.mutable.ArrayBuffer[String](_list.size) var _i = 0 - while (_i < _list.size) { + do { _rv += { _iprot.readString() } _i += 1 - } + } while (_i < _list.size) _iprot.readListEnd() _rv } @@ -1225,19 +1044,18 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF @inline private def writeAListValue(aList_item: _root_.scala.collection.Seq[String], _oprot: TProtocol): Unit = { _oprot.writeListBegin(new TList(TType.STRING, aList_item.size)) - aList_item match { - case _: IndexedSeq[_] => - var _i = 0 - val _size = aList_item.size - while (_i < _size) { - val aList_item_element = aList_item(_i) - _oprot.writeString(aList_item_element) - _i += 1 - } - case _ => - aList_item.foreach { aList_item_element => - _oprot.writeString(aList_item_element) - } + if (aList_item.isInstanceOf[IndexedSeq[_]]) { + var _i = 0 + val _size = aList_item.size + while (_i < _size) { + val aList_item_element = aList_item(_i) + _oprot.writeString(aList_item_element) + _i += 1 + } + } else { + aList_item.foreach { aList_item_element => + _oprot.writeString(aList_item_element) + } } _oprot.writeListEnd() } @@ -1250,12 +1068,12 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF } else { val _rv = new _root_.scala.collection.mutable.HashSet[Int] var _i = 0 - while (_i < _set.size) { + do { _rv += { _iprot.readI32() } _i += 1 - } + } while (_i < _set.size) _iprot.readSetEnd() _rv } @@ -1283,7 +1101,7 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF } else { val _rv = new _root_.scala.collection.mutable.HashMap[Long, Long] var _i = 0 - while (_i < _map.size) { + do { val _key = { _iprot.readI64() } @@ -1292,7 +1110,7 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF } _rv(_key) = _value _i += 1 - } + } while (_i < _map.size) _iprot.readMapEnd() _rv } @@ -1335,12 +1153,12 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF } else { val _rv = new _root_.scala.collection.mutable.ArrayBuffer[com.twitter.scrooge.test.gold.thriftscala.Request](_list.size) var _i = 0 - while (_i < _list.size) { + do { _rv += { com.twitter.scrooge.test.gold.thriftscala.Request.decode(_iprot) } _i += 1 - } + } while (_i < _list.size) _iprot.readListEnd() _rv } @@ -1354,19 +1172,18 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF @inline private def writeSubRequestsValue(subRequests_item: _root_.scala.collection.Seq[com.twitter.scrooge.test.gold.thriftscala.Request], _oprot: TProtocol): Unit = { _oprot.writeListBegin(new TList(TType.STRUCT, subRequests_item.size)) - subRequests_item match { - case _: IndexedSeq[_] => - var _i = 0 - val _size = subRequests_item.size - while (_i < _size) { - val subRequests_item_element = subRequests_item(_i) - subRequests_item_element.write(_oprot) - _i += 1 - } - case _ => - subRequests_item.foreach { subRequests_item_element => - subRequests_item_element.write(_oprot) - } + if (subRequests_item.isInstanceOf[IndexedSeq[_]]) { + var _i = 0 + val _size = subRequests_item.size + while (_i < _size) { + val subRequests_item_element = subRequests_item(_i) + subRequests_item_element.write(_oprot) + _i += 1 + } + } else { + subRequests_item.foreach { subRequests_item_element => + subRequests_item_element.write(_oprot) + } } _oprot.writeListEnd() } @@ -1674,9 +1491,10 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF extends Request { override def write(_oprot: TProtocol): Unit = { - _oprot match { - case i: LazyTProtocol => i.writeRaw(_buf, _start_offset, _end_offset - _start_offset) - case _ => super.write(_oprot) + if (_oprot.isInstanceOf[LazyTProtocol]) { + _oprot.asInstanceOf[LazyTProtocol].writeRaw(_buf, _start_offset, _end_offset - _start_offset) + } else { + super.write(_oprot) } } @@ -1746,7 +1564,7 @@ object Request extends ValidatingThriftStructCodec3[Request] with StructBuilderF * With the class private and the contract that we throw away our mutable references * having the hash code lazy here is safe. */ - override lazy val hashCode = super.hashCode + override lazy val hashCode: Int = super.hashCode } /** @@ -1827,8 +1645,8 @@ trait Request def _14: _root_.scala.Option[Long] = constructionRequiredField def _15: _root_.scala.Option[Byte] = anInt8 - def toTuple: _root_.scala.Tuple15[_root_.scala.collection.Seq[String], _root_.scala.collection.Set[Int], _root_.scala.collection.Map[Long, Long], Option[com.twitter.scrooge.test.gold.thriftscala.Request], _root_.scala.collection.Seq[com.twitter.scrooge.test.gold.thriftscala.Request], String, Option[Long], Option[Long], Option[Long], Option[Long], Option[Long], Option[com.twitter.scrooge.test.gold.thriftscala.Recursive], String, Option[Long], Option[Byte]] = { - ( + def toTuple: _root_.scala.Tuple15[_root_.scala.collection.Seq[String], _root_.scala.collection.Set[Int], _root_.scala.collection.Map[Long, Long], Option[com.twitter.scrooge.test.gold.thriftscala.Request], _root_.scala.collection.Seq[com.twitter.scrooge.test.gold.thriftscala.Request], String, Option[Long], Option[Long], Option[Long], Option[Long], Option[Long], Option[com.twitter.scrooge.test.gold.thriftscala.Recursive], String, Option[Long], Option[Byte]] = + _root_.scala.Tuple15[_root_.scala.collection.Seq[String], _root_.scala.collection.Set[Int], _root_.scala.collection.Map[Long, Long], Option[com.twitter.scrooge.test.gold.thriftscala.Request], _root_.scala.collection.Seq[com.twitter.scrooge.test.gold.thriftscala.Request], String, Option[Long], Option[Long], Option[Long], Option[Long], Option[Long], Option[com.twitter.scrooge.test.gold.thriftscala.Recursive], String, Option[Long], Option[Byte]]( aList, aSet, aMap, @@ -1845,7 +1663,6 @@ trait Request constructionRequiredField, anInt8 ) - } /** @@ -1854,135 +1671,135 @@ trait Request * is known and not optional and set to None, then the field is serialized and returned. */ def getFieldBlob(_fieldId: Short): _root_.scala.Option[TFieldBlob] = { - lazy val _buff = new TMemoryBuffer(32) - lazy val _oprot = new TCompactProtocol(_buff) - _passthroughFields.get(_fieldId) match { - case blob: _root_.scala.Some[TFieldBlob] => blob - case _root_.scala.None => { - val _fieldOpt: _root_.scala.Option[TField] = - _fieldId match { - case 1 => - if (aList ne null) { - writeAListValue(aList, _oprot) - _root_.scala.Some(Request.AListField) - } else { - _root_.scala.None - } - case 2 => - if (aSet ne null) { - writeASetValue(aSet, _oprot) - _root_.scala.Some(Request.ASetField) - } else { - _root_.scala.None - } - case 3 => - if (aMap ne null) { - writeAMapValue(aMap, _oprot) - _root_.scala.Some(Request.AMapField) - } else { - _root_.scala.None - } - case 4 => - if (aRequest.isDefined) { - writeARequestValue(aRequest.get, _oprot) - _root_.scala.Some(Request.ARequestField) - } else { - _root_.scala.None - } - case 5 => - if (subRequests ne null) { - writeSubRequestsValue(subRequests, _oprot) - _root_.scala.Some(Request.SubRequestsField) - } else { - _root_.scala.None - } - case 6 => - if (hasDefault ne null) { - writeHasDefaultValue(hasDefault, _oprot) - _root_.scala.Some(Request.HasDefaultField) - } else { - _root_.scala.None - } - case 7 => - if (noComment.isDefined) { - writeNoCommentValue(noComment.get, _oprot) - _root_.scala.Some(Request.NoCommentField) - } else { - _root_.scala.None - } - case 8 => - if (doubleSlashComment.isDefined) { - writeDoubleSlashCommentValue(doubleSlashComment.get, _oprot) - _root_.scala.Some(Request.DoubleSlashCommentField) - } else { - _root_.scala.None - } - case 9 => - if (hashtagComment.isDefined) { - writeHashtagCommentValue(hashtagComment.get, _oprot) - _root_.scala.Some(Request.HashtagCommentField) - } else { - _root_.scala.None - } - case 10 => - if (singleAsteriskComment.isDefined) { - writeSingleAsteriskCommentValue(singleAsteriskComment.get, _oprot) - _root_.scala.Some(Request.SingleAsteriskCommentField) - } else { - _root_.scala.None - } - case 11 => - if (docStringComment.isDefined) { - writeDocStringCommentValue(docStringComment.get, _oprot) - _root_.scala.Some(Request.DocStringCommentField) - } else { - _root_.scala.None - } - case 12 => - if (recRequest.isDefined) { - writeRecRequestValue(recRequest.get, _oprot) - _root_.scala.Some(Request.RecRequestField) - } else { - _root_.scala.None - } - case 13 => - if (requiredField ne null) { - writeRequiredFieldValue(requiredField, _oprot) - _root_.scala.Some(Request.RequiredFieldField) - } else { - _root_.scala.None - } - case 14 => - if (constructionRequiredField.isDefined) { - writeConstructionRequiredFieldValue(constructionRequiredField.get, _oprot) - _root_.scala.Some(Request.ConstructionRequiredFieldField) - } else { - _root_.scala.None - } - case 15 => - if (anInt8.isDefined) { - writeAnInt8Value(anInt8.get, _oprot) - _root_.scala.Some(Request.AnInt8Field) - } else { - _root_.scala.None - } - case _ => _root_.scala.None + val passedthroughValue = _passthroughFields.get(_fieldId) + if (passedthroughValue.isDefined) { + passedthroughValue + } else { + val _buff = new TMemoryBuffer(32) + val _oprot = new TCompactProtocol(_buff) + + val _fieldOpt: _root_.scala.Option[TField] = _fieldId match { + case 1 => + if (aList ne null) { + writeAListValue(aList, _oprot) + _root_.scala.Some(Request.AListField) + } else { + _root_.scala.None } - _fieldOpt match { - case _root_.scala.Some(_field) => - _root_.scala.Some(TFieldBlob(_field, Buf.ByteArray.Owned(_buff.getArray()))) - case _root_.scala.None => + case 2 => + if (aSet ne null) { + writeASetValue(aSet, _oprot) + _root_.scala.Some(Request.ASetField) + } else { _root_.scala.None - } + } + case 3 => + if (aMap ne null) { + writeAMapValue(aMap, _oprot) + _root_.scala.Some(Request.AMapField) + } else { + _root_.scala.None + } + case 4 => + if (aRequest.isDefined) { + writeARequestValue(aRequest.get, _oprot) + _root_.scala.Some(Request.ARequestField) + } else { + _root_.scala.None + } + case 5 => + if (subRequests ne null) { + writeSubRequestsValue(subRequests, _oprot) + _root_.scala.Some(Request.SubRequestsField) + } else { + _root_.scala.None + } + case 6 => + if (hasDefault ne null) { + writeHasDefaultValue(hasDefault, _oprot) + _root_.scala.Some(Request.HasDefaultField) + } else { + _root_.scala.None + } + case 7 => + if (noComment.isDefined) { + writeNoCommentValue(noComment.get, _oprot) + _root_.scala.Some(Request.NoCommentField) + } else { + _root_.scala.None + } + case 8 => + if (doubleSlashComment.isDefined) { + writeDoubleSlashCommentValue(doubleSlashComment.get, _oprot) + _root_.scala.Some(Request.DoubleSlashCommentField) + } else { + _root_.scala.None + } + case 9 => + if (hashtagComment.isDefined) { + writeHashtagCommentValue(hashtagComment.get, _oprot) + _root_.scala.Some(Request.HashtagCommentField) + } else { + _root_.scala.None + } + case 10 => + if (singleAsteriskComment.isDefined) { + writeSingleAsteriskCommentValue(singleAsteriskComment.get, _oprot) + _root_.scala.Some(Request.SingleAsteriskCommentField) + } else { + _root_.scala.None + } + case 11 => + if (docStringComment.isDefined) { + writeDocStringCommentValue(docStringComment.get, _oprot) + _root_.scala.Some(Request.DocStringCommentField) + } else { + _root_.scala.None + } + case 12 => + if (recRequest.isDefined) { + writeRecRequestValue(recRequest.get, _oprot) + _root_.scala.Some(Request.RecRequestField) + } else { + _root_.scala.None + } + case 13 => + if (requiredField ne null) { + writeRequiredFieldValue(requiredField, _oprot) + _root_.scala.Some(Request.RequiredFieldField) + } else { + _root_.scala.None + } + case 14 => + if (constructionRequiredField.isDefined) { + writeConstructionRequiredFieldValue(constructionRequiredField.get, _oprot) + _root_.scala.Some(Request.ConstructionRequiredFieldField) + } else { + _root_.scala.None + } + case 15 => + if (anInt8.isDefined) { + writeAnInt8Value(anInt8.get, _oprot) + _root_.scala.Some(Request.AnInt8Field) + } else { + _root_.scala.None + } + case _ => _root_.scala.None + } + if (_fieldOpt.isDefined) { + _root_.scala.Some(TFieldBlob(_fieldOpt.get, Buf.ByteArray.Owned(_buff.getArray))) + } else { + _root_.scala.None } } } + /** * Collects TCompactProtocol-encoded field values according to `getFieldBlob` into a map. */ def getFieldBlobs(ids: TraversableOnce[Short]): immutable$Map[Short, TFieldBlob] = - (ids flatMap { id => getFieldBlob(id) map { id -> _ } }).toMap + (ids.flatMap { id => getFieldBlob(id).map { fieldBlob => (id, fieldBlob) } }).toMap /** * Sets a field using a TCompactProtocol-encoded binary blob. If the field is a known @@ -2038,7 +1855,7 @@ trait Request constructionRequiredField = _root_.scala.Some(readConstructionRequiredFieldValue(_blob.read)) case 15 => anInt8 = _root_.scala.Some(readAnInt8Value(_blob.read)) - case _ => _passthroughFields += (_blob.id -> _blob) + case _ => _passthroughFields += _root_.scala.Tuple2(_blob.id, _blob) } new Immutable( aList, @@ -2262,14 +2079,13 @@ trait Request override def canEqual(other: Any): Boolean = other.isInstanceOf[Request] - private def _equals(x: Request, y: Request): Boolean = - x.productArity == y.productArity && - x.productIterator.sameElements(y.productIterator) && - x._passthroughFields == y._passthroughFields + private[this] def _equals(other: Request): Boolean = + this.productArity == other.productArity && + this.productIterator.sameElements(other.productIterator) && + this._passthroughFields == other._passthroughFields override def equals(other: Any): Boolean = - canEqual(other) && - _equals(this, other.asInstanceOf[Request]) + canEqual(other) && _equals(other.asInstanceOf[Request]) override def hashCode: Int = { _root_.scala.runtime.ScalaRunTime._hashCode(this) @@ -2277,28 +2093,6 @@ trait Request override def toString: String = _root_.scala.runtime.ScalaRunTime._toString(this) - - override def productArity: Int = 15 - - override def productElement(n: Int): Any = n match { - case 0 => this.aList - case 1 => this.aSet - case 2 => this.aMap - case 3 => this.aRequest - case 4 => this.subRequests - case 5 => this.hasDefault - case 6 => this.noComment - case 7 => this.doubleSlashComment - case 8 => this.hashtagComment - case 9 => this.singleAsteriskComment - case 10 => this.docStringComment - case 11 => this.recRequest - case 12 => this.requiredField - case 13 => this.constructionRequiredField - case 14 => this.anInt8 - case _ => throw new IndexOutOfBoundsException(n.toString) - } - override def productPrefix: String = "Request" def _codec: ValidatingThriftStructCodec3[Request] = Request @@ -2309,47 +2103,48 @@ trait Request private[thriftscala] class RequestStructBuilder(instance: _root_.scala.Option[Request], fieldTypes: IndexedSeq[ClassTag[_]]) extends StructBuilder[Request](fieldTypes) { - def build(): Request = instance match { - case _root_.scala.Some(i) => + def build(): Request = { + val _fieldArray = fieldArray // shadow variable + if (instance.isDefined) { + val instanceValue = instance.get Request( - (if (fieldArray(0) == null) i.aList else fieldArray(0)).asInstanceOf[_root_.scala.collection.Seq[String]], - (if (fieldArray(1) == null) i.aSet else fieldArray(1)).asInstanceOf[_root_.scala.collection.Set[Int]], - (if (fieldArray(2) == null) i.aMap else fieldArray(2)).asInstanceOf[_root_.scala.collection.Map[Long, Long]], - (if (fieldArray(3) == null) i.aRequest else fieldArray(3)).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Request]], - (if (fieldArray(4) == null) i.subRequests else fieldArray(4)).asInstanceOf[_root_.scala.collection.Seq[com.twitter.scrooge.test.gold.thriftscala.Request]], - (if (fieldArray(5) == null) i.hasDefault else fieldArray(5)).asInstanceOf[String], - (if (fieldArray(6) == null) i.noComment else fieldArray(6)).asInstanceOf[_root_.scala.Option[Long]], - (if (fieldArray(7) == null) i.doubleSlashComment else fieldArray(7)).asInstanceOf[_root_.scala.Option[Long]], - (if (fieldArray(8) == null) i.hashtagComment else fieldArray(8)).asInstanceOf[_root_.scala.Option[Long]], - (if (fieldArray(9) == null) i.singleAsteriskComment else fieldArray(9)).asInstanceOf[_root_.scala.Option[Long]], - (if (fieldArray(10) == null) i.docStringComment else fieldArray(10)).asInstanceOf[_root_.scala.Option[Long]], - (if (fieldArray(11) == null) i.recRequest else fieldArray(11)).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Recursive]], - (if (fieldArray(12) == null) i.requiredField else fieldArray(12)).asInstanceOf[String], - (if (fieldArray(13) == null) i.constructionRequiredField.get else fieldArray(13)).asInstanceOf[Long], - (if (fieldArray(14) == null) i.anInt8 else fieldArray(14)).asInstanceOf[_root_.scala.Option[Byte]] + if (_fieldArray(0) == null) instanceValue.aList else _fieldArray(0).asInstanceOf[_root_.scala.collection.Seq[String]], + if (_fieldArray(1) == null) instanceValue.aSet else _fieldArray(1).asInstanceOf[_root_.scala.collection.Set[Int]], + if (_fieldArray(2) == null) instanceValue.aMap else _fieldArray(2).asInstanceOf[_root_.scala.collection.Map[Long, Long]], + if (_fieldArray(3) == null) instanceValue.aRequest else _fieldArray(3).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Request]], + if (_fieldArray(4) == null) instanceValue.subRequests else _fieldArray(4).asInstanceOf[_root_.scala.collection.Seq[com.twitter.scrooge.test.gold.thriftscala.Request]], + if (_fieldArray(5) == null) instanceValue.hasDefault else _fieldArray(5).asInstanceOf[String], + if (_fieldArray(6) == null) instanceValue.noComment else _fieldArray(6).asInstanceOf[_root_.scala.Option[Long]], + if (_fieldArray(7) == null) instanceValue.doubleSlashComment else _fieldArray(7).asInstanceOf[_root_.scala.Option[Long]], + if (_fieldArray(8) == null) instanceValue.hashtagComment else _fieldArray(8).asInstanceOf[_root_.scala.Option[Long]], + if (_fieldArray(9) == null) instanceValue.singleAsteriskComment else _fieldArray(9).asInstanceOf[_root_.scala.Option[Long]], + if (_fieldArray(10) == null) instanceValue.docStringComment else _fieldArray(10).asInstanceOf[_root_.scala.Option[Long]], + if (_fieldArray(11) == null) instanceValue.recRequest else _fieldArray(11).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Recursive]], + if (_fieldArray(12) == null) instanceValue.requiredField else _fieldArray(12).asInstanceOf[String], + if (_fieldArray(13) == null) instanceValue.constructionRequiredField.get else _fieldArray(13).asInstanceOf[Long], + if (_fieldArray(14) == null) instanceValue.anInt8 else _fieldArray(14).asInstanceOf[_root_.scala.Option[Byte]] + ) + } else { + if (genericArrayOps(_fieldArray).contains(null)) throw new InvalidFieldsException(structBuildError("Request")) + Request( + _fieldArray(0).asInstanceOf[_root_.scala.collection.Seq[String]], + _fieldArray(1).asInstanceOf[_root_.scala.collection.Set[Int]], + _fieldArray(2).asInstanceOf[_root_.scala.collection.Map[Long, Long]], + _fieldArray(3).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Request]], + _fieldArray(4).asInstanceOf[_root_.scala.collection.Seq[com.twitter.scrooge.test.gold.thriftscala.Request]], + _fieldArray(5).asInstanceOf[String], + _fieldArray(6).asInstanceOf[_root_.scala.Option[Long]], + _fieldArray(7).asInstanceOf[_root_.scala.Option[Long]], + _fieldArray(8).asInstanceOf[_root_.scala.Option[Long]], + _fieldArray(9).asInstanceOf[_root_.scala.Option[Long]], + _fieldArray(10).asInstanceOf[_root_.scala.Option[Long]], + _fieldArray(11).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Recursive]], + _fieldArray(12).asInstanceOf[String], + _fieldArray(13).asInstanceOf[Long], + _fieldArray(14).asInstanceOf[_root_.scala.Option[Byte]] ) - case _root_.scala.None => - if (fieldArray.contains(null)) throw new InvalidFieldsException(structBuildError("Request")) - else { - Request( - fieldArray(0).asInstanceOf[_root_.scala.collection.Seq[String]], - fieldArray(1).asInstanceOf[_root_.scala.collection.Set[Int]], - fieldArray(2).asInstanceOf[_root_.scala.collection.Map[Long, Long]], - fieldArray(3).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Request]], - fieldArray(4).asInstanceOf[_root_.scala.collection.Seq[com.twitter.scrooge.test.gold.thriftscala.Request]], - fieldArray(5).asInstanceOf[String], - fieldArray(6).asInstanceOf[_root_.scala.Option[Long]], - fieldArray(7).asInstanceOf[_root_.scala.Option[Long]], - fieldArray(8).asInstanceOf[_root_.scala.Option[Long]], - fieldArray(9).asInstanceOf[_root_.scala.Option[Long]], - fieldArray(10).asInstanceOf[_root_.scala.Option[Long]], - fieldArray(11).asInstanceOf[_root_.scala.Option[com.twitter.scrooge.test.gold.thriftscala.Recursive]], - fieldArray(12).asInstanceOf[String], - fieldArray(13).asInstanceOf[Long], - fieldArray(14).asInstanceOf[_root_.scala.Option[Byte]] - ) - } } + } } private class Request__AdaptDecoder { @@ -2454,282 +2249,312 @@ private class Request__AdaptDecoder { AdaptTProtocol.usedEndMarker(15) _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() + val _fieldType = _field.`type` if (_field.`type` == TType.STOP) { _done = true } else { _field.id match { case 1 => { - _field.`type` match { - case TType.LIST => - AdaptTProtocol.usedStartMarker(1) - aList = Request.readAListValue(_iprot) - AdaptTProtocol.usedEndMarker(1) - AdaptTProtocol.unusedStartMarker(1) - _iprot.offsetSkipList() - AdaptTProtocol.unusedEndMarker(1) - case _actualType => - val _expectedType = TType.LIST - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "aList") + if (_fieldType == TType.LIST) { + AdaptTProtocol.usedStartMarker(1) + aList = Request.readAListValue(_iprot) + AdaptTProtocol.usedEndMarker(1) + AdaptTProtocol.unusedStartMarker(1) + _iprot.offsetSkipList() + AdaptTProtocol.unusedEndMarker(1) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.LIST, + _fieldType, + "aList" + ) } AdaptTProtocol.usedStartMarker(1) adapt.set_aList(aList) AdaptTProtocol.usedEndMarker(1) } case 2 => { - _field.`type` match { - case TType.SET => - AdaptTProtocol.usedStartMarker(2) - aSet = Request.readASetValue(_iprot) - AdaptTProtocol.usedEndMarker(2) - AdaptTProtocol.unusedStartMarker(2) - _iprot.offsetSkipSet() - AdaptTProtocol.unusedEndMarker(2) - case _actualType => - val _expectedType = TType.SET - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "aSet") + if (_fieldType == TType.SET) { + AdaptTProtocol.usedStartMarker(2) + aSet = Request.readASetValue(_iprot) + AdaptTProtocol.usedEndMarker(2) + AdaptTProtocol.unusedStartMarker(2) + _iprot.offsetSkipSet() + AdaptTProtocol.unusedEndMarker(2) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.SET, + _fieldType, + "aSet" + ) } AdaptTProtocol.usedStartMarker(2) adapt.set_aSet(aSet) AdaptTProtocol.usedEndMarker(2) } case 3 => { - _field.`type` match { - case TType.MAP => - AdaptTProtocol.usedStartMarker(3) - aMap = Request.readAMapValue(_iprot) - AdaptTProtocol.usedEndMarker(3) - AdaptTProtocol.unusedStartMarker(3) - _iprot.offsetSkipMap() - AdaptTProtocol.unusedEndMarker(3) - case _actualType => - val _expectedType = TType.MAP - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "aMap") + if (_fieldType == TType.MAP) { + AdaptTProtocol.usedStartMarker(3) + aMap = Request.readAMapValue(_iprot) + AdaptTProtocol.usedEndMarker(3) + AdaptTProtocol.unusedStartMarker(3) + _iprot.offsetSkipMap() + AdaptTProtocol.unusedEndMarker(3) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.MAP, + _fieldType, + "aMap" + ) } AdaptTProtocol.usedStartMarker(3) adapt.set_aMap(aMap) AdaptTProtocol.usedEndMarker(3) } case 4 => { - _field.`type` match { - case TType.STRUCT => - AdaptTProtocol.usedStartMarker(4) - aRequest = _root_.scala.Some(Request.readARequestValue(_iprot)) - AdaptTProtocol.usedEndMarker(4) - AdaptTProtocol.unusedStartMarker(4) - _iprot.offsetSkipStruct() - AdaptTProtocol.unusedEndMarker(4) - case _actualType => - val _expectedType = TType.STRUCT - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "aRequest") + if (_fieldType == TType.STRUCT) { + AdaptTProtocol.usedStartMarker(4) + aRequest = _root_.scala.Some(Request.readARequestValue(_iprot)) + AdaptTProtocol.usedEndMarker(4) + AdaptTProtocol.unusedStartMarker(4) + _iprot.offsetSkipStruct() + AdaptTProtocol.unusedEndMarker(4) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.STRUCT, + _fieldType, + "aRequest" + ) } AdaptTProtocol.usedStartMarker(4) adapt.set_aRequest(aRequest) AdaptTProtocol.usedEndMarker(4) } case 5 => { - _field.`type` match { - case TType.LIST => - AdaptTProtocol.usedStartMarker(5) - subRequests = Request.readSubRequestsValue(_iprot) - AdaptTProtocol.usedEndMarker(5) - AdaptTProtocol.unusedStartMarker(5) - _iprot.offsetSkipList() - AdaptTProtocol.unusedEndMarker(5) - case _actualType => - val _expectedType = TType.LIST - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "subRequests") + if (_fieldType == TType.LIST) { + AdaptTProtocol.usedStartMarker(5) + subRequests = Request.readSubRequestsValue(_iprot) + AdaptTProtocol.usedEndMarker(5) + AdaptTProtocol.unusedStartMarker(5) + _iprot.offsetSkipList() + AdaptTProtocol.unusedEndMarker(5) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.LIST, + _fieldType, + "subRequests" + ) } AdaptTProtocol.usedStartMarker(5) adapt.set_subRequests(subRequests) AdaptTProtocol.usedEndMarker(5) } case 6 => { - _field.`type` match { - case TType.STRING => - AdaptTProtocol.usedStartMarker(6) - hasDefault = Request.readHasDefaultValue(_iprot) - AdaptTProtocol.usedEndMarker(6) - AdaptTProtocol.unusedStartMarker(6) - _iprot.offsetSkipString() - AdaptTProtocol.unusedEndMarker(6) - case _actualType => - val _expectedType = TType.STRING - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "hasDefault") + if (_fieldType == TType.STRING) { + AdaptTProtocol.usedStartMarker(6) + hasDefault = Request.readHasDefaultValue(_iprot) + AdaptTProtocol.usedEndMarker(6) + AdaptTProtocol.unusedStartMarker(6) + _iprot.offsetSkipString() + AdaptTProtocol.unusedEndMarker(6) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.STRING, + _fieldType, + "hasDefault" + ) } AdaptTProtocol.usedStartMarker(6) adapt.set_hasDefault(hasDefault) AdaptTProtocol.usedEndMarker(6) } case 7 => { - _field.`type` match { - case TType.I64 => - AdaptTProtocol.usedStartMarker(7) - noComment = _root_.scala.Some(Request.readNoCommentValue(_iprot)) - AdaptTProtocol.usedEndMarker(7) - AdaptTProtocol.unusedStartMarker(7) - _iprot.offsetSkipI64() - AdaptTProtocol.unusedEndMarker(7) - case _actualType => - val _expectedType = TType.I64 - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "noComment") + if (_fieldType == TType.I64) { + AdaptTProtocol.usedStartMarker(7) + noComment = _root_.scala.Some(Request.readNoCommentValue(_iprot)) + AdaptTProtocol.usedEndMarker(7) + AdaptTProtocol.unusedStartMarker(7) + _iprot.offsetSkipI64() + AdaptTProtocol.unusedEndMarker(7) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.I64, + _fieldType, + "noComment" + ) } AdaptTProtocol.usedStartMarker(7) adapt.set_noComment(noComment) AdaptTProtocol.usedEndMarker(7) } case 8 => { - _field.`type` match { - case TType.I64 => - AdaptTProtocol.usedStartMarker(8) - doubleSlashComment = _root_.scala.Some(Request.readDoubleSlashCommentValue(_iprot)) - AdaptTProtocol.usedEndMarker(8) - AdaptTProtocol.unusedStartMarker(8) - _iprot.offsetSkipI64() - AdaptTProtocol.unusedEndMarker(8) - case _actualType => - val _expectedType = TType.I64 - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "doubleSlashComment") + if (_fieldType == TType.I64) { + AdaptTProtocol.usedStartMarker(8) + doubleSlashComment = _root_.scala.Some(Request.readDoubleSlashCommentValue(_iprot)) + AdaptTProtocol.usedEndMarker(8) + AdaptTProtocol.unusedStartMarker(8) + _iprot.offsetSkipI64() + AdaptTProtocol.unusedEndMarker(8) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.I64, + _fieldType, + "doubleSlashComment" + ) } AdaptTProtocol.usedStartMarker(8) adapt.set_doubleSlashComment(doubleSlashComment) AdaptTProtocol.usedEndMarker(8) } case 9 => { - _field.`type` match { - case TType.I64 => - AdaptTProtocol.usedStartMarker(9) - hashtagComment = _root_.scala.Some(Request.readHashtagCommentValue(_iprot)) - AdaptTProtocol.usedEndMarker(9) - AdaptTProtocol.unusedStartMarker(9) - _iprot.offsetSkipI64() - AdaptTProtocol.unusedEndMarker(9) - case _actualType => - val _expectedType = TType.I64 - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "hashtagComment") + if (_fieldType == TType.I64) { + AdaptTProtocol.usedStartMarker(9) + hashtagComment = _root_.scala.Some(Request.readHashtagCommentValue(_iprot)) + AdaptTProtocol.usedEndMarker(9) + AdaptTProtocol.unusedStartMarker(9) + _iprot.offsetSkipI64() + AdaptTProtocol.unusedEndMarker(9) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.I64, + _fieldType, + "hashtagComment" + ) } AdaptTProtocol.usedStartMarker(9) adapt.set_hashtagComment(hashtagComment) AdaptTProtocol.usedEndMarker(9) } case 10 => { - _field.`type` match { - case TType.I64 => - AdaptTProtocol.usedStartMarker(10) - singleAsteriskComment = _root_.scala.Some(Request.readSingleAsteriskCommentValue(_iprot)) - AdaptTProtocol.usedEndMarker(10) - AdaptTProtocol.unusedStartMarker(10) - _iprot.offsetSkipI64() - AdaptTProtocol.unusedEndMarker(10) - case _actualType => - val _expectedType = TType.I64 - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "singleAsteriskComment") + if (_fieldType == TType.I64) { + AdaptTProtocol.usedStartMarker(10) + singleAsteriskComment = _root_.scala.Some(Request.readSingleAsteriskCommentValue(_iprot)) + AdaptTProtocol.usedEndMarker(10) + AdaptTProtocol.unusedStartMarker(10) + _iprot.offsetSkipI64() + AdaptTProtocol.unusedEndMarker(10) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.I64, + _fieldType, + "singleAsteriskComment" + ) } AdaptTProtocol.usedStartMarker(10) adapt.set_singleAsteriskComment(singleAsteriskComment) AdaptTProtocol.usedEndMarker(10) } case 11 => { - _field.`type` match { - case TType.I64 => - AdaptTProtocol.usedStartMarker(11) - docStringComment = _root_.scala.Some(Request.readDocStringCommentValue(_iprot)) - AdaptTProtocol.usedEndMarker(11) - AdaptTProtocol.unusedStartMarker(11) - _iprot.offsetSkipI64() - AdaptTProtocol.unusedEndMarker(11) - case _actualType => - val _expectedType = TType.I64 - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "docStringComment") + if (_fieldType == TType.I64) { + AdaptTProtocol.usedStartMarker(11) + docStringComment = _root_.scala.Some(Request.readDocStringCommentValue(_iprot)) + AdaptTProtocol.usedEndMarker(11) + AdaptTProtocol.unusedStartMarker(11) + _iprot.offsetSkipI64() + AdaptTProtocol.unusedEndMarker(11) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.I64, + _fieldType, + "docStringComment" + ) } AdaptTProtocol.usedStartMarker(11) adapt.set_docStringComment(docStringComment) AdaptTProtocol.usedEndMarker(11) } case 12 => { - _field.`type` match { - case TType.STRUCT => - AdaptTProtocol.usedStartMarker(12) - recRequest = _root_.scala.Some(Request.readRecRequestValue(_iprot)) - AdaptTProtocol.usedEndMarker(12) - AdaptTProtocol.unusedStartMarker(12) - _iprot.offsetSkipStruct() - AdaptTProtocol.unusedEndMarker(12) - case _actualType => - val _expectedType = TType.STRUCT - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "recRequest") + if (_fieldType == TType.STRUCT) { + AdaptTProtocol.usedStartMarker(12) + recRequest = _root_.scala.Some(Request.readRecRequestValue(_iprot)) + AdaptTProtocol.usedEndMarker(12) + AdaptTProtocol.unusedStartMarker(12) + _iprot.offsetSkipStruct() + AdaptTProtocol.unusedEndMarker(12) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.STRUCT, + _fieldType, + "recRequest" + ) } AdaptTProtocol.usedStartMarker(12) adapt.set_recRequest(recRequest) AdaptTProtocol.usedEndMarker(12) } case 13 => { - _field.`type` match { - case TType.STRING => - AdaptTProtocol.usedStartMarker(13) - requiredField = Request.readRequiredFieldValue(_iprot) - AdaptTProtocol.usedEndMarker(13) - AdaptTProtocol.unusedStartMarker(13) - _iprot.offsetSkipString() - AdaptTProtocol.unusedEndMarker(13) - _got_requiredField = true - case _actualType => - val _expectedType = TType.STRING - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "requiredField") + if (_fieldType == TType.STRING) { + AdaptTProtocol.usedStartMarker(13) + requiredField = Request.readRequiredFieldValue(_iprot) + AdaptTProtocol.usedEndMarker(13) + AdaptTProtocol.unusedStartMarker(13) + _iprot.offsetSkipString() + AdaptTProtocol.unusedEndMarker(13) + _got_requiredField = true + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.STRING, + _fieldType, + "requiredField" + ) } AdaptTProtocol.usedStartMarker(13) adapt.set_requiredField(requiredField) AdaptTProtocol.usedEndMarker(13) } case 14 => { - _field.`type` match { - case TType.I64 => - AdaptTProtocol.usedStartMarker(14) - constructionRequiredField = _root_.scala.Some(Request.readConstructionRequiredFieldValue(_iprot)) - AdaptTProtocol.usedEndMarker(14) - AdaptTProtocol.unusedStartMarker(14) - _iprot.offsetSkipI64() - AdaptTProtocol.unusedEndMarker(14) - case _actualType => - val _expectedType = TType.I64 - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "constructionRequiredField") + if (_fieldType == TType.I64) { + AdaptTProtocol.usedStartMarker(14) + constructionRequiredField = _root_.scala.Some(Request.readConstructionRequiredFieldValue(_iprot)) + AdaptTProtocol.usedEndMarker(14) + AdaptTProtocol.unusedStartMarker(14) + _iprot.offsetSkipI64() + AdaptTProtocol.unusedEndMarker(14) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.I64, + _fieldType, + "constructionRequiredField" + ) } AdaptTProtocol.usedStartMarker(14) adapt.set_constructionRequiredField(constructionRequiredField) AdaptTProtocol.usedEndMarker(14) } case 15 => { - _field.`type` match { - case TType.BYTE => - AdaptTProtocol.usedStartMarker(15) - anInt8 = _root_.scala.Some(Request.readAnInt8Value(_iprot)) - AdaptTProtocol.usedEndMarker(15) - AdaptTProtocol.unusedStartMarker(15) - _iprot.offsetSkipBool() - AdaptTProtocol.unusedEndMarker(15) - case _actualType => - val _expectedType = TType.BYTE - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "anInt8") + if (_fieldType == TType.BYTE) { + AdaptTProtocol.usedStartMarker(15) + anInt8 = _root_.scala.Some(Request.readAnInt8Value(_iprot)) + AdaptTProtocol.usedEndMarker(15) + AdaptTProtocol.unusedStartMarker(15) + _iprot.offsetSkipBool() + AdaptTProtocol.unusedEndMarker(15) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.BYTE, + _fieldType, + "anInt8" + ) } AdaptTProtocol.usedStartMarker(15) adapt.set_anInt8(anInt8) AdaptTProtocol.usedEndMarker(15) } - case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() if (!_got_requiredField) throw new TProtocolException("Required field 'requiredField' was not found in serialized data for struct Request") adapt.set__endOffset(_iprot.offset) - if (_passthroughFields != null) { + if (_passthroughFields ne null) { adapt.set__passthroughFields(_passthroughFields.result()) } adapt @@ -2861,7 +2686,7 @@ private class Request__Adapt( private[this] var _end_offset: Int = _ - def set__endOffset(offset: Int) = _end_offset = offset + def set__endOffset(offset: Int): Unit = _end_offset = offset private[this] var __passthroughFields: immutable$Map[Short, TFieldBlob] = Request.NoPassthroughFields def set__passthroughFields(passthroughFields: immutable$Map[Short, TFieldBlob]): Unit = @@ -2883,9 +2708,10 @@ private class Request__Adapt( override lazy val hashCode: Int = super.hashCode override def write(_oprot: TProtocol): Unit = { - _oprot match { - case i: AdaptTProtocol => i.writeRaw(_buf, _start_offset, _end_offset - _start_offset) - case _ => super.write(_oprot) + if (_oprot.isInstanceOf[AdaptTProtocol]) { + _oprot.asInstanceOf[AdaptTProtocol].writeRaw(_buf, _start_offset, _end_offset - _start_offset) + } else { + super.write(_oprot) } } } diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/RequestType.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/RequestType.scala index 170b9bddf..c90230cbe 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/RequestType.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/RequestType.scala @@ -11,10 +11,10 @@ import scala.collection.immutable.{Map => immutable$Map} @javax.annotation.Generated(value = Array("com.twitter.scrooge.Compiler")) -case object RequestType extends _root_.com.twitter.scrooge.ThriftEnumObject[RequestType] { +object RequestType extends _root_.com.twitter.scrooge.ThriftEnumObject[RequestType] { val annotations: immutable$Map[String, String] = immutable$Map( - "enum.annotation" -> "false" + ("enum.annotation", "false") ) @@ -23,11 +23,11 @@ case object RequestType extends _root_.com.twitter.scrooge.ThriftEnumObject[Requ val name: String = "Create" val originalName: String = "Create" val annotations: immutable$Map[String, String] = immutable$Map( - "some.annotation" -> "true" + ("some.annotation", "true") ) } - private[this] val _SomeCreate = _root_.scala.Some(com.twitter.scrooge.test.gold.thriftscala.RequestType.Create) + private[this] val _SomeCreate: _root_.scala.Some[com.twitter.scrooge.test.gold.thriftscala.RequestType] = _root_.scala.Some(com.twitter.scrooge.test.gold.thriftscala.RequestType.Create) case object Read extends com.twitter.scrooge.test.gold.thriftscala.RequestType { val value: Int = 2 @@ -36,7 +36,7 @@ case object RequestType extends _root_.com.twitter.scrooge.ThriftEnumObject[Requ val annotations: immutable$Map[String, String] = immutable$Map.empty } - private[this] val _SomeRead = _root_.scala.Some(com.twitter.scrooge.test.gold.thriftscala.RequestType.Read) + private[this] val _SomeRead: _root_.scala.Some[com.twitter.scrooge.test.gold.thriftscala.RequestType] = _root_.scala.Some(com.twitter.scrooge.test.gold.thriftscala.RequestType.Read) case class EnumUnknownRequestType(value: Int) extends com.twitter.scrooge.test.gold.thriftscala.RequestType with _root_.com.twitter.scrooge.EnumItemUnknown @@ -44,19 +44,21 @@ case object RequestType extends _root_.com.twitter.scrooge.ThriftEnumObject[Requ val name: String = "EnumUnknownRequestType" + value def originalName: String = name val annotations: immutable$Map[String, String] = immutable$Map( - "enum.annotation" -> "false" + ("enum.annotation", "false") ) } /** * Find the enum by its integer value, as defined in the Thrift IDL. */ - def apply(value: Int): com.twitter.scrooge.test.gold.thriftscala.RequestType = - value match { - case 1 => com.twitter.scrooge.test.gold.thriftscala.RequestType.Create - case 2 => com.twitter.scrooge.test.gold.thriftscala.RequestType.Read - case _ => throw new NoSuchElementException(value.toString) + def apply(value: Int): com.twitter.scrooge.test.gold.thriftscala.RequestType = { + val enumOpt = get(value) + if (enumOpt.isDefined) { + enumOpt.get + } else { + throw new NoSuchElementException(_root_.java.lang.Integer.toString(value)) } + } /** * Find the enum by its integer value, as defined in the Thrift IDL. @@ -64,11 +66,14 @@ case object RequestType extends _root_.com.twitter.scrooge.ThriftEnumObject[Requ * In particular this allows ignoring new values added to an enum * in the IDL on the producer side when the consumer was not updated. */ - def getOrUnknown(value: Int): com.twitter.scrooge.test.gold.thriftscala.RequestType = - get(value) match { - case _root_.scala.Some(e) => e - case _root_.scala.None => EnumUnknownRequestType(value) + def getOrUnknown(value: Int): com.twitter.scrooge.test.gold.thriftscala.RequestType = { + val enumOpt = get(value) + if (enumOpt.isDefined) { + enumOpt.get + } else { + EnumUnknownRequestType(value) } + } /** * Find the enum by its integer value, as defined in the Thrift IDL. diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/Response.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/Response.scala index 8d6d62a44..2c2856fd3 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/Response.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/Response.scala @@ -33,9 +33,9 @@ object Response extends ValidatingThriftStructCodec3[Response] with StructBuilde val NoPassthroughFields: immutable$Map[Short, TFieldBlob] = immutable$Map.empty[Short, TFieldBlob] val Struct: TStruct = new TStruct("Response") val StatusCodeField: TField = new TField("statusCode", TType.I32, 1) - val StatusCodeFieldManifest: Manifest[Int] = implicitly[Manifest[Int]] + val StatusCodeFieldManifest: Manifest[Int] = manifest[Int] val ResponseUnionField: TField = new TField("responseUnion", TType.STRUCT, 2) - val ResponseUnionFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.ResponseUnion] = implicitly[Manifest[com.twitter.scrooge.test.gold.thriftscala.ResponseUnion]] + val ResponseUnionFieldManifest: Manifest[com.twitter.scrooge.test.gold.thriftscala.ResponseUnion] = manifest[com.twitter.scrooge.test.gold.thriftscala.ResponseUnion] /** * Field information in declaration order. @@ -65,33 +65,32 @@ object Response extends ValidatingThriftStructCodec3[Response] with StructBuilde ) ) - lazy val structAnnotations: immutable$Map[String, String] = + + val structAnnotations: immutable$Map[String, String] = immutable$Map.empty[String, String] - private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq( + private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq[ClassTag[_]]( classTag[Int].asInstanceOf[ClassTag[_]], classTag[com.twitter.scrooge.test.gold.thriftscala.ResponseUnion].asInstanceOf[ClassTag[_]] ) - private[this] val structFields: Seq[ThriftStructField[Response]] = { - Seq( - new ThriftStructField[Response]( - StatusCodeField, - _root_.scala.Some(StatusCodeFieldManifest), - classOf[Response]) { - def getValue[R](struct: Response): R = struct.statusCode.asInstanceOf[R] - }, - new ThriftStructField[Response]( - ResponseUnionField, - _root_.scala.Some(ResponseUnionFieldManifest), - classOf[Response]) { - def getValue[R](struct: Response): R = struct.responseUnion.asInstanceOf[R] - } - ) - } + private[this] val structFields: Seq[ThriftStructField[Response]] = Seq[ThriftStructField[Response]]( + new ThriftStructField[Response]( + StatusCodeField, + _root_.scala.Some(StatusCodeFieldManifest), + classOf[Response]) { + def getValue[R](struct: Response): R = struct.statusCode.asInstanceOf[R] + }, + new ThriftStructField[Response]( + ResponseUnionField, + _root_.scala.Some(ResponseUnionFieldManifest), + classOf[Response]) { + def getValue[R](struct: Response): R = struct.responseUnion.asInstanceOf[R] + } + ) override lazy val metaData: ThriftStructMetaData[Response] = - new ThriftStructMetaData(this, structFields, fieldInfos, Seq(), structAnnotations) + new ThriftStructMetaData(this, structFields, fieldInfos, Nil, structAnnotations) /** * Checks that all required fields are non-null. @@ -113,11 +112,7 @@ object Response extends ValidatingThriftStructCodec3[Response] with StructBuilde def withoutPassthroughFields(original: Response): Response = new Immutable( - statusCode = - { - val field = original.statusCode - field - }, + statusCode = original.statusCode, responseUnion = { val field = original.responseUnion @@ -145,7 +140,7 @@ object Response extends ValidatingThriftStructCodec3[Response] with StructBuilde val adaptContext = _iprot.adaptContext val reloadRequired = adaptContext.shouldReloadDecoder synchronized { - if (adaptiveDecoder == null || reloadRequired) { + if ((adaptiveDecoder eq null) || reloadRequired) { adaptiveDecoder = adaptContext.buildDecoder(this, fallbackDecoder, accessRecordingDecoderBuilder) } } @@ -180,48 +175,41 @@ object Response extends ValidatingThriftStructCodec3[Response] with StructBuilde val _start_offset = _iprot.offset _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 1 => - _field.`type` match { - case TType.I32 => - - statusCode = readStatusCodeValue(_iprot) - case _actualType => - val _expectedType = TType.I32 - throw new TProtocolException( - "Received wrong type for field 'statusCode' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I32) { + statusCode = readStatusCodeValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'statusCode' (expected=%s, actual=%s).", + TType.I32, + _fieldType + ) } case 2 => - _field.`type` match { - case TType.STRUCT => - - responseUnion = readResponseUnionValue(_iprot) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'responseUnion' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + responseUnion = readResponseUnionValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'responseUnion' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() new LazyImmutable( @@ -231,19 +219,22 @@ object Response extends ValidatingThriftStructCodec3[Response] with StructBuilde _iprot.offset, statusCode, responseUnion, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() ) } - override def decode(_iprot: TProtocol): Response = - _iprot match { - case i: AdaptTProtocol => adaptiveDecode(i) - case i: LazyTProtocol => lazyDecode(i) - case i => eagerDecode(i) + override def decode(_iprot: TProtocol): Response = { + if (_iprot.isInstanceOf[LazyTProtocol]) { + lazyDecode(_iprot.asInstanceOf[LazyTProtocol]) + } else if (_iprot.isInstanceOf[AdaptTProtocol]) { + adaptiveDecode(_iprot.asInstanceOf[AdaptTProtocol]) + } else { + eagerDecode(_iprot) } + } private[thriftscala] def eagerDecode(_iprot: TProtocol): Response = { var statusCode: Int = 0 @@ -252,52 +243,47 @@ object Response extends ValidatingThriftStructCodec3[Response] with StructBuilde var _done = false _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { case 1 => - _field.`type` match { - case TType.I32 => - statusCode = readStatusCodeValue(_iprot) - case _actualType => - val _expectedType = TType.I32 - throw new TProtocolException( - "Received wrong type for field 'statusCode' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.I32) { + statusCode = readStatusCodeValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'statusCode' (expected=%s, actual=%s).", + TType.I32, + _fieldType + ) } case 2 => - _field.`type` match { - case TType.STRUCT => - responseUnion = readResponseUnionValue(_iprot) - case _actualType => - val _expectedType = TType.STRUCT - throw new TProtocolException( - "Received wrong type for field 'responseUnion' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) + if (_fieldType == TType.STRUCT) { + responseUnion = readResponseUnionValue(_iprot) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field 'responseUnion' (expected=%s, actual=%s).", + TType.STRUCT, + _fieldType + ) } case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() new Immutable( statusCode, responseUnion, - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() @@ -386,9 +372,10 @@ object Response extends ValidatingThriftStructCodec3[Response] with StructBuilde extends Response { override def write(_oprot: TProtocol): Unit = { - _oprot match { - case i: LazyTProtocol => i.writeRaw(_buf, _start_offset, _end_offset - _start_offset) - case _ => super.write(_oprot) + if (_oprot.isInstanceOf[LazyTProtocol]) { + _oprot.asInstanceOf[LazyTProtocol].writeRaw(_buf, _start_offset, _end_offset - _start_offset) + } else { + super.write(_oprot) } } @@ -404,7 +391,7 @@ object Response extends ValidatingThriftStructCodec3[Response] with StructBuilde * With the class private and the contract that we throw away our mutable references * having the hash code lazy here is safe. */ - override lazy val hashCode = super.hashCode + override lazy val hashCode: Int = super.hashCode } /** @@ -440,12 +427,11 @@ trait Response def _1: Int = statusCode def _2: com.twitter.scrooge.test.gold.thriftscala.ResponseUnion = responseUnion - def toTuple: _root_.scala.Tuple2[Int, com.twitter.scrooge.test.gold.thriftscala.ResponseUnion] = { - ( + def toTuple: _root_.scala.Tuple2[Int, com.twitter.scrooge.test.gold.thriftscala.ResponseUnion] = + _root_.scala.Tuple2[Int, com.twitter.scrooge.test.gold.thriftscala.ResponseUnion]( statusCode, responseUnion ) - } /** @@ -454,44 +440,40 @@ trait Response * is known and not optional and set to None, then the field is serialized and returned. */ def getFieldBlob(_fieldId: Short): _root_.scala.Option[TFieldBlob] = { - lazy val _buff = new TMemoryBuffer(32) - lazy val _oprot = new TCompactProtocol(_buff) - _passthroughFields.get(_fieldId) match { - case blob: _root_.scala.Some[TFieldBlob] => blob - case _root_.scala.None => { - val _fieldOpt: _root_.scala.Option[TField] = - _fieldId match { - case 1 => - if (true) { - writeStatusCodeValue(statusCode, _oprot) - _root_.scala.Some(Response.StatusCodeField) - } else { - _root_.scala.None - } - case 2 => - if (responseUnion ne null) { - writeResponseUnionValue(responseUnion, _oprot) - _root_.scala.Some(Response.ResponseUnionField) - } else { - _root_.scala.None - } - case _ => _root_.scala.None - } - _fieldOpt match { - case _root_.scala.Some(_field) => - _root_.scala.Some(TFieldBlob(_field, Buf.ByteArray.Owned(_buff.getArray()))) - case _root_.scala.None => + val passedthroughValue = _passthroughFields.get(_fieldId) + if (passedthroughValue.isDefined) { + passedthroughValue + } else { + val _buff = new TMemoryBuffer(32) + val _oprot = new TCompactProtocol(_buff) + + val _fieldOpt: _root_.scala.Option[TField] = _fieldId match { + case 1 => + writeStatusCodeValue(statusCode, _oprot) + _root_.scala.Some(Response.StatusCodeField) + case 2 => + if (responseUnion ne null) { + writeResponseUnionValue(responseUnion, _oprot) + _root_.scala.Some(Response.ResponseUnionField) + } else { _root_.scala.None - } + } + case _ => _root_.scala.None + } + if (_fieldOpt.isDefined) { + _root_.scala.Some(TFieldBlob(_fieldOpt.get, Buf.ByteArray.Owned(_buff.getArray))) + } else { + _root_.scala.None } } } + /** * Collects TCompactProtocol-encoded field values according to `getFieldBlob` into a map. */ def getFieldBlobs(ids: TraversableOnce[Short]): immutable$Map[Short, TFieldBlob] = - (ids flatMap { id => getFieldBlob(id) map { id -> _ } }).toMap + (ids.flatMap { id => getFieldBlob(id).map { fieldBlob => (id, fieldBlob) } }).toMap /** * Sets a field using a TCompactProtocol-encoded binary blob. If the field is a known @@ -508,7 +490,7 @@ trait Response statusCode = readStatusCodeValue(_blob.read) case 2 => responseUnion = readResponseUnionValue(_blob.read) - case _ => _passthroughFields += (_blob.id -> _blob) + case _ => _passthroughFields += _root_.scala.Tuple2(_blob.id, _blob) } new Immutable( statusCode, @@ -575,14 +557,13 @@ trait Response override def canEqual(other: Any): Boolean = other.isInstanceOf[Response] - private def _equals(x: Response, y: Response): Boolean = - x.productArity == y.productArity && - x.productIterator.sameElements(y.productIterator) && - x._passthroughFields == y._passthroughFields + private[this] def _equals(other: Response): Boolean = + this.productArity == other.productArity && + this.productIterator.sameElements(other.productIterator) && + this._passthroughFields == other._passthroughFields override def equals(other: Any): Boolean = - canEqual(other) && - _equals(this, other.asInstanceOf[Response]) + canEqual(other) && _equals(other.asInstanceOf[Response]) override def hashCode: Int = { _root_.scala.runtime.ScalaRunTime._hashCode(this) @@ -590,15 +571,6 @@ trait Response override def toString: String = _root_.scala.runtime.ScalaRunTime._toString(this) - - override def productArity: Int = 2 - - override def productElement(n: Int): Any = n match { - case 0 => this.statusCode - case 1 => this.responseUnion - case _ => throw new IndexOutOfBoundsException(n.toString) - } - override def productPrefix: String = "Response" def _codec: ValidatingThriftStructCodec3[Response] = Response @@ -609,21 +581,22 @@ trait Response private[thriftscala] class ResponseStructBuilder(instance: _root_.scala.Option[Response], fieldTypes: IndexedSeq[ClassTag[_]]) extends StructBuilder[Response](fieldTypes) { - def build(): Response = instance match { - case _root_.scala.Some(i) => + def build(): Response = { + val _fieldArray = fieldArray // shadow variable + if (instance.isDefined) { + val instanceValue = instance.get Response( - (if (fieldArray(0) == null) i.statusCode else fieldArray(0)).asInstanceOf[Int], - (if (fieldArray(1) == null) i.responseUnion else fieldArray(1)).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.ResponseUnion] + if (_fieldArray(0) == null) instanceValue.statusCode else _fieldArray(0).asInstanceOf[Int], + if (_fieldArray(1) == null) instanceValue.responseUnion else _fieldArray(1).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.ResponseUnion] + ) + } else { + if (genericArrayOps(_fieldArray).contains(null)) throw new InvalidFieldsException(structBuildError("Response")) + Response( + _fieldArray(0).asInstanceOf[Int], + _fieldArray(1).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.ResponseUnion] ) - case _root_.scala.None => - if (fieldArray.contains(null)) throw new InvalidFieldsException(structBuildError("Response")) - else { - Response( - fieldArray(0).asInstanceOf[Int], - fieldArray(1).asInstanceOf[com.twitter.scrooge.test.gold.thriftscala.ResponseUnion] - ) - } } + } } private class Response__AdaptDecoder { @@ -647,59 +620,63 @@ private class Response__AdaptDecoder { AdaptTProtocol.usedEndMarker(2) _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() + val _fieldType = _field.`type` if (_field.`type` == TType.STOP) { _done = true } else { _field.id match { case 1 => { - _field.`type` match { - case TType.I32 => - AdaptTProtocol.usedStartMarker(1) - statusCode = Response.readStatusCodeValue(_iprot) - AdaptTProtocol.usedEndMarker(1) - AdaptTProtocol.unusedStartMarker(1) - _iprot.offsetSkipI32() - AdaptTProtocol.unusedEndMarker(1) - case _actualType => - val _expectedType = TType.I32 - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "statusCode") + if (_fieldType == TType.I32) { + AdaptTProtocol.usedStartMarker(1) + statusCode = Response.readStatusCodeValue(_iprot) + AdaptTProtocol.usedEndMarker(1) + AdaptTProtocol.unusedStartMarker(1) + _iprot.offsetSkipI32() + AdaptTProtocol.unusedEndMarker(1) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.I32, + _fieldType, + "statusCode" + ) } AdaptTProtocol.usedStartMarker(1) adapt.set_statusCode(statusCode) AdaptTProtocol.usedEndMarker(1) } case 2 => { - _field.`type` match { - case TType.STRUCT => - AdaptTProtocol.usedStartMarker(2) - responseUnion = Response.readResponseUnionValue(_iprot) - AdaptTProtocol.usedEndMarker(2) - AdaptTProtocol.unusedStartMarker(2) - _iprot.offsetSkipStruct() - AdaptTProtocol.unusedEndMarker(2) - case _actualType => - val _expectedType = TType.STRUCT - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "responseUnion") + if (_fieldType == TType.STRUCT) { + AdaptTProtocol.usedStartMarker(2) + responseUnion = Response.readResponseUnionValue(_iprot) + AdaptTProtocol.usedEndMarker(2) + AdaptTProtocol.unusedStartMarker(2) + _iprot.offsetSkipStruct() + AdaptTProtocol.unusedEndMarker(2) + } else { + throw AdaptTProtocol.unexpectedTypeException( + TType.STRUCT, + _fieldType, + "responseUnion" + ) } AdaptTProtocol.usedStartMarker(2) adapt.set_responseUnion(responseUnion) AdaptTProtocol.usedEndMarker(2) } - case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() adapt.set__endOffset(_iprot.offset) - if (_passthroughFields != null) { + if (_passthroughFields ne null) { adapt.set__passthroughFields(_passthroughFields.result()) } adapt @@ -740,7 +717,7 @@ private class Response__Adapt( private[this] var _end_offset: Int = _ - def set__endOffset(offset: Int) = _end_offset = offset + def set__endOffset(offset: Int): Unit = _end_offset = offset private[this] var __passthroughFields: immutable$Map[Short, TFieldBlob] = Response.NoPassthroughFields def set__passthroughFields(passthroughFields: immutable$Map[Short, TFieldBlob]): Unit = @@ -762,9 +739,10 @@ private class Response__Adapt( override lazy val hashCode: Int = super.hashCode override def write(_oprot: TProtocol): Unit = { - _oprot match { - case i: AdaptTProtocol => i.writeRaw(_buf, _start_offset, _end_offset - _start_offset) - case _ => super.write(_oprot) + if (_oprot.isInstanceOf[AdaptTProtocol]) { + _oprot.asInstanceOf[AdaptTProtocol].writeRaw(_buf, _start_offset, _end_offset - _start_offset) + } else { + super.write(_oprot) } } } diff --git a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/ResponseUnion.scala b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/ResponseUnion.scala index f2407361d..dff034b72 100644 --- a/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/ResponseUnion.scala +++ b/scrooge-generator-tests/src/test/resources/gold_file_output_scala/com/twitter/scrooge/test/gold/thriftscala/ResponseUnion.scala @@ -32,51 +32,48 @@ private object ResponseUnionDecoder { var _result: ResponseUnion = null _iprot.readStructBegin() val _field = _iprot.readFieldBegin() + val _fieldType = _field.`type` _field.id match { case 1 => // id - _field.`type` match { - case TType.I64 => - _result = ResponseUnion.Id({ - _iprot.readI64() - }) - case _ => TProtocolUtil.skip(_iprot, _field.`type`) - } + if (_fieldType == TType.I64) { + _result = ResponseUnion.Id({ + _iprot.readI64() + }) + } else TProtocolUtil.skip(_iprot, _fieldType) case 2 => // details - _field.`type` match { - case TType.STRING => - _result = ResponseUnion.Details({ - _iprot.readString() - }) - case _ => TProtocolUtil.skip(_iprot, _field.`type`) - } + if (_fieldType == TType.STRING) { + _result = ResponseUnion.Details({ + _iprot.readString() + }) + } else TProtocolUtil.skip(_iprot, _fieldType) case _ => - if (_field.`type` != TType.STOP) { + if (_fieldType != TType.STOP) { _result = newUnknown(TFieldBlob.read(_field, _iprot)) } else { - TProtocolUtil.skip(_iprot, _field.`type`) + TProtocolUtil.skip(_iprot, _fieldType) } } - if (_field.`type` != TType.STOP) { + if (_fieldType != TType.STOP) { _iprot.readFieldEnd() var _done = false var _moreThanOne = false - while (!_done) { - val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) + do { + val _newField = _iprot.readFieldBegin() + if (_newField.`type` == TType.STOP) _done = true else { _moreThanOne = true - TProtocolUtil.skip(_iprot, _field.`type`) + TProtocolUtil.skip(_iprot, _newField.`type`) _iprot.readFieldEnd() } - } + } while (!_done) if (_moreThanOne) { _iprot.readStructEnd() throw new TProtocolException("Cannot read a TUnion with more than one set value!") } } _iprot.readStructEnd() - if (_result == null) + if (_result eq null) throw new TProtocolException("Cannot read a TUnion with no set value!") _result } @@ -87,10 +84,7 @@ object ResponseUnionAliases { type IdAlias = Long def withoutPassthroughFields_Id(obj: ResponseUnion.Id): ResponseUnion.Id = { - val field = obj.id - ResponseUnion.Id( - field - ) + ResponseUnion.Id(obj.id) } val IdKeyTypeManifest: _root_.scala.Option[Manifest[_]] = _root_.scala.None @@ -100,10 +94,7 @@ object ResponseUnionAliases { type DetailsAlias = String def withoutPassthroughFields_Details(obj: ResponseUnion.Details): ResponseUnion.Details = { - val field = obj.details - ResponseUnion.Details( - field - ) + ResponseUnion.Details(obj.details) } val DetailsKeyTypeManifest: _root_.scala.Option[Manifest[_]] = _root_.scala.None @@ -116,13 +107,13 @@ object ResponseUnionAliases { object ResponseUnion extends ValidatingThriftStructCodec3[ResponseUnion] { val Union: TStruct = new TStruct("ResponseUnion") val IdField: TField = new TField("id", TType.I64, 1) - val IdFieldManifest: Manifest[Id] = implicitly[Manifest[Id]] + val IdFieldManifest: Manifest[Id] = manifest[Id] val DetailsField: TField = new TField("details", TType.STRING, 2) - val DetailsFieldManifest: Manifest[Details] = implicitly[Manifest[Details]] + val DetailsFieldManifest: Manifest[Details] = manifest[Details] lazy val structAnnotations: immutable$Map[java.lang.String, java.lang.String] = immutable$Map[java.lang.String, java.lang.String]( - "u.annotation" -> "y" + ("u.annotation", "y") ) /** @@ -141,8 +132,8 @@ object ResponseUnion extends ValidatingThriftStructCodec3[ResponseUnion] { override lazy val metaData = new ThriftStructMetaData( this, - Seq(), - Seq(), + Nil, + Nil, fieldInfos.asInstanceOf[Seq[ThriftUnionFieldInfo[_root_.com.twitter.scrooge.ThriftUnion with _root_.com.twitter.scrooge.ThriftStruct, _]]], structAnnotations) @@ -150,18 +141,16 @@ object ResponseUnion extends ValidatingThriftStructCodec3[ResponseUnion] { _item.write(_oprot) override def decode(_iprot: TProtocol): ResponseUnion = - ResponseUnionDecoder(_iprot, UnknownUnionField(_)) + ResponseUnionDecoder(_iprot, UnknownUnionField.apply) def apply(_iprot: TProtocol): ResponseUnion = decode(_iprot) import ResponseUnionAliases._ def withoutPassthroughFields(struct: ResponseUnion): ResponseUnion = { - struct match { - case obj: Id => withoutPassthroughFields_Id(obj) - case obj: Details => withoutPassthroughFields_Details(obj) - case unknown: UnknownUnionField => unknown // by definition pass-through - } + if (struct.isInstanceOf[Id]) withoutPassthroughFields_Id(struct.asInstanceOf[Id]) + else if (struct.isInstanceOf[Details]) withoutPassthroughFields_Details(struct.asInstanceOf[Details]) + else struct //This is an UnknownUnionField, by definition passthrough } object Id extends (IdAlias => Id) { @@ -194,12 +183,10 @@ object ResponseUnion extends ValidatingThriftStructCodec3[ResponseUnion] { override def write(_oprot: TProtocol): Unit = { _oprot.writeStructBegin(Union) - if (true) { val id_item = id _oprot.writeFieldBegin(IdField) _oprot.writeI64(id_item) _oprot.writeFieldEnd() - } _oprot.writeFieldStop() _oprot.writeStructEnd() } @@ -219,7 +206,7 @@ object ResponseUnion extends ValidatingThriftStructCodec3[ResponseUnion] { DetailsValueTypeManifest, immutable$Map.empty[java.lang.String, java.lang.String], immutable$Map( - "u.field.annotation" -> "x" + ("u.field.annotation", "x") ) ) } @@ -236,7 +223,7 @@ object ResponseUnion extends ValidatingThriftStructCodec3[ResponseUnion] { _root_.scala.Some(Details.fieldInfo) override def write(_oprot: TProtocol): Unit = { - if (details == null) + if (details eq null) throw new TProtocolException("Cannot write a TUnion with no set value!") _oprot.writeStructBegin(Union) if (details ne null) { diff --git a/scrooge-generator/src/main/resources/scalagen/enum.mustache b/scrooge-generator/src/main/resources/scalagen/enum.mustache index c126b24cf..7b1dbd228 100644 --- a/scrooge-generator/src/main/resources/scalagen/enum.mustache +++ b/scrooge-generator/src/main/resources/scalagen/enum.mustache @@ -5,12 +5,12 @@ import scala.collection.immutable.{Map => immutable$Map} {{docstring}} @javax.annotation.Generated(value = Array("com.twitter.scrooge.Compiler")) -case object {{EnumName}} extends _root_.com.twitter.scrooge.ThriftEnumObject[{{EnumName}}] { +object {{EnumName}} extends _root_.com.twitter.scrooge.ThriftEnumObject[{{EnumName}}] { {{#annotations}} val annotations: immutable$Map[String, String] = immutable$Map( {{#pairs}} - "{{key}}" -> "{{value}}" + ("{{key}}", "{{value}}") {{/pairs|,}} ) {{/annotations}} @@ -27,7 +27,7 @@ case object {{EnumName}} extends _root_.com.twitter.scrooge.ThriftEnumObject[{{E {{#annotations}} val annotations: immutable$Map[String, String] = immutable$Map( {{#pairs}} - "{{key}}" -> "{{value}}" + ("{{key}}", "{{value}}") {{/pairs|,}} ) {{/annotations}} @@ -36,7 +36,7 @@ case object {{EnumName}} extends _root_.com.twitter.scrooge.ThriftEnumObject[{{E {{/annotations}} } - private[this] val _Some{{name}} = _root_.scala.Some({{package}}.{{EnumName}}.{{name}}) + private[this] val _Some{{name}}: _root_.scala.Some[{{package}}.{{EnumName}}] = _root_.scala.Some({{package}}.{{EnumName}}.{{name}}) {{/values}} case class EnumUnknown{{EnumName}}(value: Int) @@ -47,7 +47,7 @@ case object {{EnumName}} extends _root_.com.twitter.scrooge.ThriftEnumObject[{{E {{#annotations}} val annotations: immutable$Map[String, String] = immutable$Map( {{#pairs}} - "{{key}}" -> "{{value}}" + ("{{key}}", "{{value}}") {{/pairs|,}} ) {{/annotations}} {{^annotations}} @@ -58,13 +58,14 @@ case object {{EnumName}} extends _root_.com.twitter.scrooge.ThriftEnumObject[{{E /** * Find the enum by its integer value, as defined in the Thrift IDL. */ - def apply(value: Int): {{package}}.{{EnumName}} = - value match { -{{#values}} - case {{value}} => {{package}}.{{EnumName}}.{{name}} -{{/values}} - case _ => throw new NoSuchElementException(value.toString) + def apply(value: Int): {{package}}.{{EnumName}} = { + val enumOpt = get(value) + if (enumOpt.isDefined) { + enumOpt.get + } else { + throw new NoSuchElementException(_root_.java.lang.Integer.toString(value)) } + } /** * Find the enum by its integer value, as defined in the Thrift IDL. @@ -72,11 +73,14 @@ case object {{EnumName}} extends _root_.com.twitter.scrooge.ThriftEnumObject[{{E * In particular this allows ignoring new values added to an enum * in the IDL on the producer side when the consumer was not updated. */ - def getOrUnknown(value: Int): {{package}}.{{EnumName}} = - get(value) match { - case _root_.scala.Some(e) => e - case _root_.scala.None => EnumUnknown{{EnumName}}(value) + def getOrUnknown(value: Int): {{package}}.{{EnumName}} = { + val enumOpt = get(value) + if (enumOpt.isDefined) { + enumOpt.get + } else { + EnumUnknown{{EnumName}}(value) } + } /** * Find the enum by its integer value, as defined in the Thrift IDL. @@ -108,4 +112,4 @@ case object {{EnumName}} extends _root_.com.twitter.scrooge.ThriftEnumObject[{{E {{docstring}} @javax.annotation.Generated(value = Array("com.twitter.scrooge.Compiler")) -sealed trait {{EnumName}} extends ThriftEnum with Serializable \ No newline at end of file +sealed trait {{EnumName}} extends ThriftEnum with Serializable diff --git a/scrooge-generator/src/main/resources/scalagen/finagleClient.mustache b/scrooge-generator/src/main/resources/scalagen/finagleClient.mustache index a9224f877..99bbef26d 100644 --- a/scrooge-generator/src/main/resources/scalagen/finagleClient.mustache +++ b/scrooge-generator/src/main/resources/scalagen/finagleClient.mustache @@ -57,7 +57,7 @@ class {{ServiceName}}$FinagleClient( oprot.writeMessageBegin(new TMessage(name, TMessageType.CALL, 0)) args.write(oprot) oprot.writeMessageEnd() - oprot.getTransport().flush() + oprot.getTransport.flush() val bytes = _root_.java.util.Arrays.copyOfRange( memoryBuffer.getArray(), 0, @@ -79,12 +79,8 @@ class {{ServiceName}}$FinagleClient( val msg = iprot.readMessageBegin() try { if (msg.`type` == TMessageType.EXCEPTION) { - val exception = TApplicationException.readFrom(iprot) match { - case sourced: _root_.com.twitter.finagle.SourcedException => - if (serviceName != "") sourced.serviceName = serviceName - sourced - case e => e - } + val exception = TApplicationException.readFrom(iprot) + setServiceName(exception) throw exception } else { codec.decode(iprot) @@ -94,24 +90,10 @@ class {{ServiceName}}$FinagleClient( } } - protected def missingResult(name: String): TApplicationException = { - new TApplicationException( - TApplicationException.MISSING_RESULT, - name + " failed: unknown result" - ) + protected def setServiceName(ex: Throwable): Throwable = { + _root_.com.twitter.finagle.SourcedException.setServiceName(ex, serviceName) } - protected def setServiceName(ex: Throwable): Throwable = - if (this.serviceName == "") ex - else { - ex match { - case se: _root_.com.twitter.finagle.SourcedException => - se.serviceName = this.serviceName - se - case _ => ex - } - } - // ----- end boilerplate. {{/hasParent}} diff --git a/scrooge-generator/src/main/resources/scalagen/finagleClientFunction.mustache b/scrooge-generator/src/main/resources/scalagen/finagleClientFunction.mustache index 1133270c1..b42363446 100644 --- a/scrooge-generator/src/main/resources/scalagen/finagleClientFunction.mustache +++ b/scrooge-generator/src/main/resources/scalagen/finagleClientFunction.mustache @@ -1,20 +1,20 @@ private[this] object {{__stats_name}} { - val RequestsCounter = scopedStats.scope("{{clientFuncNameForWire}}").counter("requests") - val SuccessCounter = scopedStats.scope("{{clientFuncNameForWire}}").counter("success") - val FailuresCounter = scopedStats.scope("{{clientFuncNameForWire}}").counter("failures") - val FailuresScope = scopedStats.scope("{{clientFuncNameForWire}}").scope("failures") + val RequestsCounter: _root_.com.twitter.finagle.stats.Counter = scopedStats.scope("{{clientFuncNameForWire}}").counter("requests") + val SuccessCounter: _root_.com.twitter.finagle.stats.Counter = scopedStats.scope("{{clientFuncNameForWire}}").counter("success") + val FailuresCounter: _root_.com.twitter.finagle.stats.Counter = scopedStats.scope("{{clientFuncNameForWire}}").counter("failures") + val FailuresScope: StatsReceiver = scopedStats.scope("{{clientFuncNameForWire}}").scope("failures") } {{#functionInfo}} val {{clientFuncNameForWire}}{{ServiceName}}ReplyDeserializer: Array[Byte] => _root_.com.twitter.util.Try[{{typeName}}] = { response: Array[Byte] => { - val result = decodeResponse(response, {{funcObjectName}}.Result) - - result.firstException() match { - case Some(exception) => _root_.com.twitter.util.Throw(setServiceName(exception)) - case _ => result.successField match { - case Some(success) => _root_.com.twitter.util.Return(success) - case _ => _root_.com.twitter.util.Throw(missingResult("{{clientFuncNameForWire}}")) - } + val result: {{funcObjectName}}.Result = decodeResponse(response, {{funcObjectName}}.Result) + val firstException = result.firstException() + if (firstException.isDefined) { + _root_.com.twitter.util.Throw(setServiceName(firstException.get)) + } else if (result.successField.isDefined) { + _root_.com.twitter.util.Return(result.successField.get) + } else { + _root_.com.twitter.util.Throw(_root_.com.twitter.scrooge.internal.ApplicationExceptions.missingResult("{{clientFuncNameForWire}}")) } } } @@ -36,23 +36,19 @@ val {{clientFuncNameForWire}}{{ServiceName}}ReplyDeserializer: Array[Byte] => _r this.service(serialized).flatMap { response => Future.const(serdeCtx.deserialize(response)) }.respond { response => - val responseClass = responseClassifier.applyOrElse( + val classified = responseClassifier.applyOrElse( ctfs.ReqRep(inputArgs, response), ctfs.ResponseClassifier.Default) - responseClass match { - case ctfs.ResponseClass.Ignorable => // Do nothing. - case ctfs.ResponseClass.Successful(_) => - {{__stats_name}}.SuccessCounter.incr() - case ctfs.ResponseClass.Failed(_) => - {{__stats_name}}.FailuresCounter.incr() - response match { - case _root_.com.twitter.util.Throw(ex) => - setServiceName(ex) - {{__stats_name}}.FailuresScope.counter( - _root_.com.twitter.util.Throwables.mkString(ex): _*).incr() - case _ => - } - } + if (classified.isInstanceOf[ctfs.ResponseClass.Successful]) { + {{__stats_name}}.SuccessCounter.incr() + } else if (classified.isInstanceOf[ctfs.ResponseClass.Failed]) { + {{__stats_name}}.FailuresCounter.incr() + if (response.isThrow) { + setServiceName(response.throwable) + {{__stats_name}}.FailuresScope.counter( + _root_.com.twitter.util.Throwables.mkString(response.throwable): _*).incr() + } + } // Last ResponseClass is Ignorable, which we do not need to record } } } diff --git a/scrooge-generator/src/main/resources/scalagen/finagleService.mustache b/scrooge-generator/src/main/resources/scalagen/finagleService.mustache index 268c35c73..8c1d895ab 100644 --- a/scrooge-generator/src/main/resources/scalagen/finagleService.mustache +++ b/scrooge-generator/src/main/resources/scalagen/finagleService.mustache @@ -57,11 +57,11 @@ class {{ServiceName}}$FinagleService( {{#hasParent}}override {{/hasParent}}def serviceName: String = serverParam.serviceName {{#hasMethodServices}} - private[this] val filters = new Filter(serverParam) + private[this] val filters: Filter = new Filter(serverParam) {{/hasMethodServices}} {{^hasMethodServices}} {{^hasParent}} - private[this] val filters = new Filter(serverParam) + private[this] val filters: Filter = new Filter(serverParam) {{/hasParent}} {{/hasMethodServices}} @@ -76,25 +76,27 @@ class {{ServiceName}}$FinagleService( } final def apply(request: Array[Byte]): Future[Array[Byte]] = { - val inputTransport = new TMemoryInputTransport(request) - val iprot = protocolFactory.getProtocol(inputTransport) + val iprot = protocolFactory.getProtocol(new TMemoryInputTransport(request)) try { val msg = iprot.readMessageBegin() - val service = serviceMap.get(msg.name) - service match { - case _root_.scala.Some(svc) => - svc((iprot, msg.seqid)) - case _ => - TProtocolUtil.skip(iprot, TType.STRUCT) - Future.value(Buf.ByteArray.Owned.extract( - filters.exception(msg.name, msg.seqid, TApplicationException.UNKNOWN_METHOD, - "Invalid method name: '" + msg.name + "'"))) + val svcOpt = serviceMap.get(msg.name) + if (svcOpt.isDefined) { + svcOpt.get.apply((iprot, msg.seqid)) + } else { + TProtocolUtil.skip(iprot, TType.STRUCT) + invalidMethodNameFuture(msg) } } catch { case e: Exception => Future.exception(e) } } + + private[this] def invalidMethodNameFuture(msg: TMessage): Future[Array[Byte]] = { + Future.value(Buf.ByteArray.Owned.extract( + filters.exception(msg.name, msg.seqid, TApplicationException.UNKNOWN_METHOD, + "Invalid method name: '" + msg.name + "'"))) + } {{/hasParent}} // ---- end boilerplate. diff --git a/scrooge-generator/src/main/resources/scalagen/methodFilter.mustache b/scrooge-generator/src/main/resources/scalagen/methodFilter.mustache index 3355e62e5..0e0e06be4 100644 --- a/scrooge-generator/src/main/resources/scalagen/methodFilter.mustache +++ b/scrooge-generator/src/main/resources/scalagen/methodFilter.mustache @@ -9,17 +9,19 @@ val {{methodSvcNameForCompile}}: finagle$Filter[(TProtocol, Int), Array[Byte], { val iprot = request._1 val seqid = request._2 val res = service(request) - res.transform { - case _root_.com.twitter.util.Throw(e: TProtocolException) => + res.transform(resTry => { + if (resTry.isThrow && resTry.throwable.isInstanceOf[TProtocolException]) { + val underlyingException = resTry.throwable iprot.readMessageEnd() Future.value( ProtocolExceptionResponse( null, - exception("{{methodSvcNameForWire}}", seqid, TApplicationException.PROTOCOL_ERROR, e.getMessage), - new TApplicationException(TApplicationException.PROTOCOL_ERROR, e.getMessage))) - case _ => + exception("{{methodSvcNameForWire}}", seqid, TApplicationException.PROTOCOL_ERROR, underlyingException.getMessage), + new TApplicationException(TApplicationException.PROTOCOL_ERROR, underlyingException.getMessage))) + } else { res - } + } + }) } } @@ -34,33 +36,35 @@ val {{methodSvcNameForCompile}}: finagle$Filter[(TProtocol, Int), Array[Byte], { val args = {{funcObjectName}}.Args.decode(iprot) iprot.readMessageEnd() _root_.com.twitter.finagle.tracing.Trace.recordBinary("srv/request_deserialization_ns", System.nanoTime - start) - val res = _root_.com.twitter.finagle.context.Contexts.local.let( + _root_.com.twitter.finagle.context.Contexts.local.let( _root_.com.twitter.finagle.thrift.MethodMetadata.Key, _root_.com.twitter.finagle.thrift.MethodMetadata({{funcObjectName}})) { service(args) - } - res.transform { - case _root_.com.twitter.util.Return(value) => + }.transform(resTry => { + if (resTry.isReturn) { val methodResult = {{funcObjectName}}.Result({{resultNamedArg}}) Future.value( SuccessfulResponse( args, reply("{{methodSvcNameForWire}}", seqid, methodResult), methodResult)) + } else { // Throw[_] +{{#hasExceptions}} + val underlyingException = resTry.throwable {{#exceptions}} - case _root_.com.twitter.util.Throw(e: {{exceptionType}}) => { - Future.value( - ThriftExceptionResponse( - args, - reply("{{methodSvcNameForWire}}", seqid, {{funcObjectName}}.Result({{fieldName}} = Some(e))), - e)) - } + {{^first}}else {{/first}}if (underlyingException.isInstanceOf[{{exceptionType}}]) + Future.value( + ThriftExceptionResponse( + args, + reply("{{methodSvcNameForWire}}", seqid, {{funcObjectName}}.Result({{fieldName}} = Some(underlyingException.asInstanceOf[{{exceptionType}}]))), + underlyingException.asInstanceOf[{{exceptionType}}])) {{/exceptions}} - case t @ _root_.com.twitter.util.Throw(_) => - Future.const(t.cast[RichResponse[{{funcObjectName}}.Args, {{funcObjectName}}.Result]]) - } + else +{{/hasExceptions}} + Future.const(resTry.asInstanceOf[Throw[RichResponse[{{funcObjectName}}.Args, {{funcObjectName}}.Result]]]) + } + }) } } - statsFilter.andThen(protocolExnFilter).andThen(serdeFilter) } diff --git a/scrooge-generator/src/main/resources/scalagen/readAdaptField.mustache b/scrooge-generator/src/main/resources/scalagen/readAdaptField.mustache index e3da6a21c..e0161bc97 100644 --- a/scrooge-generator/src/main/resources/scalagen/readAdaptField.mustache +++ b/scrooge-generator/src/main/resources/scalagen/readAdaptField.mustache @@ -1,24 +1,26 @@ -_field.`type` match { {{#isEnum}} - case TType.I32 | TType.ENUM => +if (_fieldType == TType.I32 || _fieldType == TType.ENUM) { {{/isEnum}} {{^isEnum}} - case TType.{{constType}} => +if (_fieldType == TType.{{constType}}) { {{/isEnum}} - AdaptTProtocol.usedStartMarker({{id}}) - {{fieldName}} = {{#optional}}_root_.scala.Some({{/optional}}{{StructName}}.{{readFieldValueName}}(_iprot){{#optional}}){{/optional}} - AdaptTProtocol.usedEndMarker({{id}}) - AdaptTProtocol.unusedStartMarker({{id}}) + AdaptTProtocol.usedStartMarker({{id}}) + {{fieldName}} = {{#optional}}_root_.scala.Some({{/optional}}{{StructName}}.{{readFieldValueName}}(_iprot){{#optional}}){{/optional}} + AdaptTProtocol.usedEndMarker({{id}}) + AdaptTProtocol.unusedStartMarker({{id}}) {{#readWriteInfo}} - {{>skipValue}} + {{>skipValue}} {{/readWriteInfo}} - AdaptTProtocol.unusedEndMarker({{id}}) + AdaptTProtocol.unusedEndMarker({{id}}) {{#required}} - {{gotName}} = true + {{gotName}} = true {{/required}} - case _actualType => - val _expectedType = TType.{{#isEnum}}ENUM{{/isEnum}}{{^isEnum}}{{constType}}{{/isEnum}} - throw AdaptTProtocol.unexpectedTypeException(_expectedType, _actualType, "{{fieldName}}") +} else { + throw AdaptTProtocol.unexpectedTypeException( + TType.{{#isEnum}}ENUM{{/isEnum}}{{^isEnum}}{{constType}}{{/isEnum}}, + _fieldType, + "{{fieldName}}" + ) } AdaptTProtocol.usedStartMarker({{id}}) adapt.{{setName}}({{fieldName}}) diff --git a/scrooge-generator/src/main/resources/scalagen/readField.mustache b/scrooge-generator/src/main/resources/scalagen/readField.mustache index 5819ebdd6..782ad5e8d 100644 --- a/scrooge-generator/src/main/resources/scalagen/readField.mustache +++ b/scrooge-generator/src/main/resources/scalagen/readField.mustache @@ -1,20 +1,17 @@ -_field.`type` match { {{#isEnum}} - case TType.I32 | TType.ENUM => +if (_fieldType == TType.I32 || _fieldType == TType.ENUM) { {{/isEnum}} {{^isEnum}} - case TType.{{constType}} => +if (_fieldType == TType.{{constType}}) { {{/isEnum}} - {{fieldName}} = {{#optional}}_root_.scala.Some({{/optional}}{{readFieldValueName}}(_iprot){{#optional}}){{/optional}} + {{fieldName}} = {{#optional}}_root_.scala.Some({{/optional}}{{readFieldValueName}}(_iprot){{#optional}}){{/optional}} {{#required}} - {{gotName}} = true + {{gotName}} = true {{/required}} - case _actualType => - val _expectedType = TType.{{#isEnum}}ENUM{{/isEnum}}{{^isEnum}}{{constType}}{{/isEnum}} - throw new TProtocolException( - "Received wrong type for field '{{fieldName}}' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) +} else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field '{{fieldName}}' (expected=%s, actual=%s).", + TType.{{#isEnum}}ENUM{{/isEnum}}{{^isEnum}}{{constType}}{{/isEnum}}, + _fieldType + ) } diff --git a/scrooge-generator/src/main/resources/scalagen/readLazyField.mustache b/scrooge-generator/src/main/resources/scalagen/readLazyField.mustache index 4b490e70d..204e10ad0 100644 --- a/scrooge-generator/src/main/resources/scalagen/readLazyField.mustache +++ b/scrooge-generator/src/main/resources/scalagen/readLazyField.mustache @@ -1,21 +1,22 @@ -_field.`type` match { {{#isEnum}} - case TType.I32 | TType.ENUM => +if (_fieldType == TType.I32 || _fieldType == TType.ENUM) { {{/isEnum}} {{^isEnum}} - case TType.{{constType}} => +if (_fieldType == TType.{{constType}}) { {{/isEnum}} - {{#isLazyReadEnabled}}{{fieldNameForWire}}Offset = _iprot.{{offsetSkipProtocol}}{{/isLazyReadEnabled}} - {{^isLazyReadEnabled}}{{fieldName}} = {{#optional}}Some({{/optional}}{{readFieldValueName}}(_iprot){{#optional}}){{/optional}}{{/isLazyReadEnabled}} +{{#isLazyReadEnabled}} + {{fieldNameForWire}}Offset = _iprot.{{offsetSkipProtocol}}() +{{/isLazyReadEnabled}} +{{^isLazyReadEnabled}} + {{fieldName}} = {{#optional}}Some({{/optional}}{{readFieldValueName}}(_iprot){{#optional}}){{/optional}} +{{/isLazyReadEnabled}} {{#required}} - {{gotName}} = true + {{gotName}} = true {{/required}} - case _actualType => - val _expectedType = TType.{{#isEnum}}ENUM{{/isEnum}}{{^isEnum}}{{constType}}{{/isEnum}} - throw new TProtocolException( - "Received wrong type for field '{{fieldName}}' (expected=%s, actual=%s).".format( - ttypeToString(_expectedType), - ttypeToString(_actualType) - ) - ) +} else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.throwWrongFieldTypeException( + "Received wrong type for field '{{fieldName}}' (expected=%s, actual=%s).", + TType.{{#isEnum}}ENUM{{/isEnum}}{{^isEnum}}{{constType}}{{/isEnum}}, + _fieldType + ) } diff --git a/scrooge-generator/src/main/resources/scalagen/readList.mustache b/scrooge-generator/src/main/resources/scalagen/readList.mustache index 898814080..04f879a2a 100644 --- a/scrooge-generator/src/main/resources/scalagen/readList.mustache +++ b/scrooge-generator/src/main/resources/scalagen/readList.mustache @@ -5,14 +5,14 @@ if (_list.size == 0) { } else { val _rv = new _root_.scala.collection.mutable.ArrayBuffer[{{eltType}}](_list.size) var _i = 0 - while (_i < _list.size) { + do { _rv += { {{#eltReadWriteInfo}} {{>readValue}} {{/eltReadWriteInfo}} } _i += 1 - } + } while (_i < _list.size) _iprot.readListEnd() _rv } diff --git a/scrooge-generator/src/main/resources/scalagen/readMap.mustache b/scrooge-generator/src/main/resources/scalagen/readMap.mustache index 2dbf79ed2..576cfb4b0 100644 --- a/scrooge-generator/src/main/resources/scalagen/readMap.mustache +++ b/scrooge-generator/src/main/resources/scalagen/readMap.mustache @@ -5,7 +5,7 @@ if (_map.size == 0) { } else { val _rv = new _root_.scala.collection.mutable.HashMap[{{keyType}}, {{valueType}}] var _i = 0 - while (_i < _map.size) { + do { val _key = { {{#keyReadWriteInfo}} {{>readValue}} @@ -18,7 +18,7 @@ if (_map.size == 0) { } _rv(_key) = _value _i += 1 - } + } while (_i < _map.size) _iprot.readMapEnd() _rv } diff --git a/scrooge-generator/src/main/resources/scalagen/readSet.mustache b/scrooge-generator/src/main/resources/scalagen/readSet.mustache index 00367445c..499c47b80 100644 --- a/scrooge-generator/src/main/resources/scalagen/readSet.mustache +++ b/scrooge-generator/src/main/resources/scalagen/readSet.mustache @@ -5,14 +5,14 @@ if (_set.size == 0) { } else { val _rv = new _root_.scala.collection.mutable.HashSet[{{eltType}}] var _i = 0 - while (_i < _set.size) { + do { _rv += { {{#eltReadWriteInfo}} {{>readValue}} {{/eltReadWriteInfo}} } _i += 1 - } + } while (_i < _set.size) _iprot.readSetEnd() _rv -} \ No newline at end of file +} diff --git a/scrooge-generator/src/main/resources/scalagen/readUnionField.mustache b/scrooge-generator/src/main/resources/scalagen/readUnionField.mustache index 4dd5f920c..377285960 100644 --- a/scrooge-generator/src/main/resources/scalagen/readUnionField.mustache +++ b/scrooge-generator/src/main/resources/scalagen/readUnionField.mustache @@ -1,14 +1,12 @@ case {{id}} => // {{fieldName}} - _field.`type` match { {{#isEnum}} - case TType.I32 | TType.ENUM => + if (_fieldType == TType.I32 || _fieldType == TType.ENUM) { {{/isEnum}} {{^isEnum}} - case TType.{{constType}} => + if (_fieldType == TType.{{constType}}) { {{/isEnum}} - _result = {{StructName}}.{{FieldName}}({ - {{>readValue}} - }) - case _ => TProtocolUtil.skip(_iprot, _field.`type`) - } + _result = {{StructName}}.{{FieldName}}({ + {{>readValue}} + }) + } else TProtocolUtil.skip(_iprot, _fieldType) diff --git a/scrooge-generator/src/main/resources/scalagen/service.mustache b/scrooge-generator/src/main/resources/scalagen/service.mustache index 339431f16..b04acd993 100644 --- a/scrooge-generator/src/main/resources/scalagen/service.mustache +++ b/scrooge-generator/src/main/resources/scalagen/service.mustache @@ -56,7 +56,7 @@ object {{ServiceName}} {{#withFinagle}}extends _root_.com.twitter.finagle.thrift {{#annotations}} val annotations: immutable$Map[String, String] = immutable$Map( {{#pairs}} - "{{key}}" -> "{{value}}" + ("{{key}}", "{{value}}") {{/pairs|,}} ) {{/annotations}} @@ -236,9 +236,10 @@ object {{ServiceName}} {{#withFinagle}}extends _root_.com.twitter.finagle.thrift def unsafeBuildFromMethods(methods: immutable$Map[ThriftMethod, _root_.com.twitter.finagle.Service[_root_.com.twitter.scrooge.Request[_], _root_.com.twitter.scrooge.Response[_]]]): ReqRepServicePerEndpoint = { {{#inheritedFunctions}} - val {{dedupedFuncName}} = methods.get({{ParentServiceName}}.{{funcObjectName}}) match { - case Some(impl) => impl.asInstanceOf[{{ParentServiceName}}.{{funcObjectName}}.ReqRepServicePerEndpointServiceType] - case _ => throw new IllegalArgumentException(s"No implementation found for method {{funcObjectName}} in ${methods.keySet}") + val {{dedupedFuncName}} = { + val {{dedupedFuncName}}Opt = methods.get({{ParentServiceName}}.{{funcObjectName}}) + if ({{dedupedFuncName}}Opt.isEmpty) throw new IllegalArgumentException(_root_.java.lang.String.format("No implementation found for method {{funcObjectName}} in %s", methods.keySet)) + {{dedupedFuncName}}Opt.get.asInstanceOf[{{ParentServiceName}}.{{funcObjectName}}.ReqRepServicePerEndpointServiceType] } {{/inheritedFunctions}} @@ -442,7 +443,7 @@ object {{ServiceName}} {{#withFinagle}}extends _root_.com.twitter.finagle.thrift def {{funcName}}({{fieldParams}}): Future[{{typeName}}] = { val requestCtx = _root_.com.twitter.finagle.context.Contexts.local.getOrElse(_root_.com.twitter.finagle.thrift.Headers.Request.Key, () => _root_.com.twitter.finagle.thrift.Headers.Request.newValues) val scroogeRequest = _root_.com.twitter.scrooge.Request(requestCtx.values, self.{{funcObjectName}}.Args({{argNames}})) - servicePerEndpoint.{{dedupedFuncName}}(scroogeRequest).transform(_root_.com.twitter.finagle.thrift.service.ThriftReqRepServicePerEndpoint.transformResult(_)){{^isVoid}}{{/isVoid}}{{#isVoid}}.unit{{/isVoid}} + servicePerEndpoint.{{dedupedFuncName}}(scroogeRequest).transform(_root_.com.twitter.finagle.thrift.service.ThriftReqRepServicePerEndpoint.transformResult){{^isVoid}}{{/isVoid}}{{#isVoid}}.unit{{/isVoid}} } {{/ownFunctions}} @@ -571,7 +572,7 @@ object {{ServiceName}} {{#withFinagle}}extends _root_.com.twitter.finagle.thrift oprot.writeMessageBegin(new TMessage(name, TMessageType.EXCEPTION, seqid)) x.write(oprot) oprot.writeMessageEnd() - oprot.getTransport().flush() + oprot.getTransport.flush() // make a copy of the array of bytes to construct a new buffer because memoryBuffer is reusable Buf.ByteArray.Shared(memoryBuffer.getArray(), 0, memoryBuffer.length()) @@ -581,7 +582,7 @@ object {{ServiceName}} {{#withFinagle}}extends _root_.com.twitter.finagle.thrift } {{#hasThriftFunctions}} - private def reply(name: String, seqid: Int, result: ThriftStruct): Buf = { + private[this] def reply(name: String, seqid: Int, result: ThriftStruct): Buf = { val memoryBuffer = tlReusableBuffer.get() try { val oprot = protocolFactory.getProtocol(memoryBuffer) @@ -590,7 +591,7 @@ object {{ServiceName}} {{#withFinagle}}extends _root_.com.twitter.finagle.thrift result.write(oprot) oprot.writeMessageEnd() _root_.com.twitter.finagle.tracing.Trace.recordBinary("srv/response_serialization_ns", System.nanoTime - start) - oprot.getTransport().flush() + oprot.getTransport.flush() // make a copy of the array of bytes to construct a new buffer because memoryBuffer is reusable Buf.ByteArray.Shared(memoryBuffer.getArray(), 0, memoryBuffer.length()) @@ -600,43 +601,17 @@ object {{ServiceName}} {{#withFinagle}}extends _root_.com.twitter.finagle.thrift } {{/hasThriftFunctions}} - private def missingResult(name: String): TApplicationException = { - new TApplicationException( - TApplicationException.MISSING_RESULT, - name + " failed: unknown result" - ) - } - - private def setServiceName(ex: Throwable): Throwable = - if (this.serviceName == "") ex - else { - ex match { - case se: _root_.com.twitter.finagle.SourcedException => - se.serviceName = this.serviceName - se - case _ => ex - } - } - - private def recordRequest(methodStats: _root_.com.twitter.finagle.thrift.ThriftMethodStats): Unit = { - methodStats.requestsCounter.incr() - } - - private def recordResponse(reqRep: ctfs.ReqRep, methodStats: _root_.com.twitter.finagle.thrift.ThriftMethodStats): Unit = { + private[this] def recordResponse(reqRep: ctfs.ReqRep, methodStats: _root_.com.twitter.finagle.thrift.ThriftMethodStats): Unit = { ServerToReqRep.setCtx(reqRep) - val responseClass = responseClassifier.applyOrElse(reqRep, ctfs.ResponseClassifier.Default) - responseClass match { - case ctfs.ResponseClass.Ignorable => // Do nothing. - case ctfs.ResponseClass.Successful(_) => - methodStats.successCounter.incr() - case ctfs.ResponseClass.Failed(_) => - methodStats.failuresCounter.incr() - reqRep.response match { - case Throw(ex) => - methodStats.failuresScope.counter(Throwables.mkString(ex): _*).incr() - case _ => - } - } + val classified = responseClassifier.applyOrElse(reqRep, ctfs.ResponseClassifier.Default) + if (classified.isInstanceOf[ctfs.ResponseClass.Successful]) { + methodStats.successCounter.incr() + } else if (classified.isInstanceOf[ctfs.ResponseClass.Failed]) { + methodStats.failuresCounter.incr() + if (reqRep.response.isThrow) { + methodStats.failuresScope.counter(Throwables.mkString(reqRep.response.throwable): _*).incr() + } + } // Last ResponseClass is Ignorable, which we do not need to record } final protected def perMethodStatsFilter( @@ -653,25 +628,30 @@ object {{ServiceName}} {{#withFinagle}}extends _root_.com.twitter.finagle.thrift req: (TProtocol, Int), service: finagle$Service[(TProtocol, Int), RichResponse[method.Args, method.Result]] ): Future[Array[Byte]] = { - recordRequest(methodStats) - service(req).transform { - case Return(value) => - value match { - case SuccessfulResponse(args, _, result) => - recordResponse(ctfs.ReqRep(args, _root_.com.twitter.util.Return(result.successField.get)), methodStats) - case ProtocolExceptionResponse(args, _, exp) => - recordResponse(ctfs.ReqRep(args, _root_.com.twitter.util.Throw(exp)), methodStats) - case ThriftExceptionResponse(args, _, ex) => - val rep = ex match { - case exp: ThriftException => setServiceName(exp) - case _ => missingResult(serviceName) - } - recordResponse(ctfs.ReqRep(args, _root_.com.twitter.util.Throw(rep)), methodStats) + methodStats.requestsCounter.incr() + service(req).transform { response => + if (response.isReturn) { + val value = response.apply() + if (value.isInstanceOf[SuccessfulResponse[method.Args, method.Result]]) { + val succResp = value.asInstanceOf[SuccessfulResponse[method.Args, method.Result]] + recordResponse(ctfs.ReqRep(succResp.input, _root_.com.twitter.util.Return(succResp.result.successField.get)), methodStats) + } else if (value.isInstanceOf[ProtocolExceptionResponse[method.Args, method.Result]]) { + val protExResp = value.asInstanceOf[ProtocolExceptionResponse[method.Args, method.Result]] + recordResponse(ctfs.ReqRep(protExResp.input, _root_.com.twitter.util.Throw(protExResp.exception)), methodStats) + } else if (value.isInstanceOf[ThriftExceptionResponse[method.Args, method.Result]]) { + val thriftExResp = value.asInstanceOf[ThriftExceptionResponse[method.Args, method.Result]] + val rep: Throwable = if (thriftExResp.ex.isInstanceOf[ThriftException]) { + _root_.com.twitter.finagle.SourcedException.setServiceName(thriftExResp.ex, serviceName) + } else { + _root_.com.twitter.scrooge.internal.ApplicationExceptions.missingResult(serviceName) + } + recordResponse(ctfs.ReqRep(thriftExResp.input, _root_.com.twitter.util.Throw(rep)), methodStats) } Future.value(Buf.ByteArray.Owned.extract(value.response)) - case t @ Throw(_) => - recordResponse(ctfs.ReqRep(req, t), methodStats) - Future.const(t.cast[Array[Byte]]) + } else { // Throw[_] + recordResponse(ctfs.ReqRep(req, response), methodStats) + Future.const(response.asInstanceOf[Throw[Array[Byte]]]) + } } } } diff --git a/scrooge-generator/src/main/resources/scalagen/struct.mustache b/scrooge-generator/src/main/resources/scalagen/struct.mustache index 7bb7e2fe0..35d938d97 100644 --- a/scrooge-generator/src/main/resources/scalagen/struct.mustache +++ b/scrooge-generator/src/main/resources/scalagen/struct.mustache @@ -39,13 +39,13 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with {{#isEnum}} val {{fieldConst}}I32: TField = new TField("{{fieldNameForWire}}", TType.I32, {{id}}) {{/isEnum}} - val {{fieldConst}}Manifest: Manifest[{{fieldType}}] = implicitly[Manifest[{{fieldType}}]] + val {{fieldConst}}Manifest: Manifest[{{fieldType}}] = manifest[{{fieldType}}] {{/fields}} /** * Field information in declaration order. */ - lazy val fieldInfos: scala.List[ThriftStructFieldInfo] = scala.List[ThriftStructFieldInfo]( + {{#hasFields}}lazy {{/hasFields}}val fieldInfos: scala.List[ThriftStructFieldInfo] = {{^hasFields}}Nil{{/hasFields}}{{#hasFields}}scala.List[ThriftStructFieldInfo]( {{#fields}} new ThriftStructFieldInfo( {{fieldConst}}, @@ -53,13 +53,13 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with {{required}}, {{fieldConst}}Manifest, {{#fieldKeyType}} - _root_.scala.Some(implicitly[Manifest[{{fieldKeyType}}]]), + _root_.scala.Some(manifest[{{fieldKeyType}}]), {{/fieldKeyType}} {{^fieldKeyType}} _root_.scala.None, {{/fieldKeyType}} {{#fieldValueType}} - _root_.scala.Some(implicitly[Manifest[{{fieldValueType}}]]), + _root_.scala.Some(manifest[{{fieldValueType}}]), {{/fieldValueType}} {{^fieldValueType}} _root_.scala.None, @@ -67,7 +67,7 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with {{#fieldTypeAnnotations}} immutable$Map( {{#pairs}} - "{{key}}" -> "{{value}}" + ("{{key}}", "{{value}}") {{/pairs|,}} ), {{/fieldTypeAnnotations}} @@ -75,9 +75,9 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with immutable$Map.empty[String, String], {{/fieldTypeAnnotations}} {{#fieldFieldAnnotations}} - immutable$Map( + immutable$Map.apply[String, String]( {{#pairs}} - "{{key}}" -> "{{value}}" + ("{{key}}", "{{value}}") {{/pairs|,}} ), {{/fieldFieldAnnotations}} @@ -93,12 +93,13 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with ) {{/fields|,}} ) +{{/hasFields}} - lazy val structAnnotations: immutable$Map[String, String] = + {{#structAnnotations}}lazy {{/structAnnotations}}val structAnnotations: immutable$Map[String, String] = {{#structAnnotations}} immutable$Map[String, String]( {{#pairs}} - "{{key}}" -> "{{value}}" + ("{{key}}", "{{value}}") {{/pairs|,}} ) {{/structAnnotations}} @@ -106,27 +107,25 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with immutable$Map.empty[String, String] {{/structAnnotations}} - private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq( + private val fieldTypes: IndexedSeq[ClassTag[_]] = IndexedSeq[ClassTag[_]]( {{#fields}} classTag[{{>constructionOptionalType}}].asInstanceOf[ClassTag[_]] {{/fields|,}} ) - private[this] val structFields: Seq[ThriftStructField[{{StructName}}]] = { - Seq( + private[this] val structFields: Seq[ThriftStructField[{{StructName}}]] = Seq[ThriftStructField[{{StructName}}]]( {{#fields}} - new ThriftStructField[{{StructName}}]( - {{fieldConst}}, - _root_.scala.Some({{fieldConst}}Manifest), - classOf[{{StructName}}]) { - def getValue[R](struct: {{StructName}}): R = struct.{{fieldName}}.asInstanceOf[R] - } + new ThriftStructField[{{StructName}}]( + {{fieldConst}}, + _root_.scala.Some({{fieldConst}}Manifest), + classOf[{{StructName}}]) { + def getValue[R](struct: {{StructName}}): R = struct.{{fieldName}}.asInstanceOf[R] + } {{/fields|,}} - ) - } + ) override lazy val metaData: ThriftStructMetaData[{{StructName}}] = - new ThriftStructMetaData(this, structFields, fieldInfos, Seq(), structAnnotations) + new ThriftStructMetaData(this, structFields, fieldInfos, Nil, structAnnotations) /** * Checks that all required fields are non-null. @@ -135,7 +134,7 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with {{#fields}} {{#required}} {{#nullable}} - if (_item.{{fieldName}} == null) throw new TProtocolException("Required field {{fieldName}} cannot be null") + if (_item.{{fieldName}} eq null) throw new TProtocolException("Required field {{fieldName}} cannot be null") {{/nullable}} {{/required}} {{/fields}} @@ -157,7 +156,7 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with {{/constructionRequired}} {{#required}} {{#nullable}} - if (item.{{fieldName}} == null) + if (item.{{fieldName}} eq null) buf += com.twitter.scrooge.validation.MissingRequiredField(fieldInfos.apply({{index}})) {{/nullable}} {{/required}} @@ -169,11 +168,16 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with def withoutPassthroughFields(original: {{StructName}}): {{StructName}} = new {{InstanceClassName}}( {{#fields}} +{{#hasPassthroughFields}} {{fieldName}} = { val field = original.{{fieldName}} {{#passthroughFields}}{{>withoutPassthrough}}{{/passthroughFields}} } +{{/hasPassthroughFields}} +{{^hasPassthroughFields}} + {{fieldName}} = original.{{fieldName}} +{{/hasPassthroughFields}} {{/fields|,}} ) @@ -199,7 +203,7 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with val adaptContext = _iprot.adaptContext val reloadRequired = adaptContext.shouldReloadDecoder synchronized { - if (adaptiveDecoder == null || reloadRequired) { + if ((adaptiveDecoder eq null) || reloadRequired) { adaptiveDecoder = adaptContext.buildDecoder(this, fallbackDecoder, accessRecordingDecoderBuilder) } } @@ -249,9 +253,10 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with val _start_offset = _iprot.offset _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { _field.id match { @@ -260,13 +265,13 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with {{>readLazyField}} {{/fields}} case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() {{#fields}} @@ -282,21 +287,24 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with {{#fields}} {{#isLazyReadEnabled}}{{fieldNameForWire}}Offset{{/isLazyReadEnabled}}{{^isLazyReadEnabled}}{{fieldName}}{{/isLazyReadEnabled}}, {{/fields}} - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() ) } - override def decode(_iprot: TProtocol): {{StructName}} = - _iprot match { + override def decode(_iprot: TProtocol): {{StructName}} = { + if (_iprot.isInstanceOf[LazyTProtocol]) { + lazyDecode(_iprot.asInstanceOf[LazyTProtocol]) {{#adapt}} - case i: AdaptTProtocol => adaptiveDecode(i) + } else if (_iprot.isInstanceOf[AdaptTProtocol]) { + adaptiveDecode(_iprot.asInstanceOf[AdaptTProtocol]) {{/adapt}} - case i: LazyTProtocol => lazyDecode(i) - case i => eagerDecode(i) + } else { + eagerDecode(_iprot) } + } private[{{packageName}}] def eagerDecode(_iprot: TProtocol): {{StructName}} = { {{/withTrait}} @@ -318,24 +326,29 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with var _done = false _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) { + val _fieldType = _field.`type` + if (_fieldType == TType.STOP) { _done = true } else { +{{#hasFields}} _field.id match { {{#fields}} case {{id}} => {{>readField}} {{/fields}} case _ => - if (_passthroughFields == null) +{{/hasFields}} + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) +{{#hasFields}} } +{{/hasFields}} _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() {{#fields}} @@ -347,7 +360,7 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with {{#fields}} {{fieldName}}, {{/fields}} - if (_passthroughFields == null) + if (_passthroughFields eq null) NoPassthroughFields else _passthroughFields.result() @@ -478,9 +491,10 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with extends {{StructName}} { override def write(_oprot: TProtocol): Unit = { - _oprot match { - case i: LazyTProtocol => i.writeRaw(_buf, _start_offset, _end_offset - _start_offset) - case _ => super.write(_oprot) + if (_oprot.isInstanceOf[LazyTProtocol]) { + _oprot.asInstanceOf[LazyTProtocol].writeRaw(_buf, _start_offset, _end_offset - _start_offset) + } else { + super.write(_oprot) } } @@ -515,7 +529,7 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] with * With the class private and the contract that we throw away our mutable references * having the hash code lazy here is safe. */ - override lazy val hashCode = super.hashCode + override lazy val hashCode: Int = super.hashCode } /** @@ -614,13 +628,12 @@ class {{StructName}}( {{/fields}} {{#arityN}} - def toTuple: {{tuple}} = { - ( + def toTuple: {{tuple}} = + {{tuple}}( {{#fields}} {{fieldName}} {{/fields|,}} ) - } {{/arityN}} {{#isResponse}} @@ -635,53 +648,62 @@ class {{StructName}}( * is known and not optional and set to None, then the field is serialized and returned. */ def getFieldBlob(_fieldId: Short): _root_.scala.Option[TFieldBlob] = { - lazy val _buff = new TMemoryBuffer(32) + val passedthroughValue = _passthroughFields.get(_fieldId) + if (passedthroughValue.isDefined) { + passedthroughValue + } else { {{#hasFields}} - lazy val _oprot = new TCompactProtocol(_buff) -{{/hasFields}} - _passthroughFields.get(_fieldId) match { - case blob: _root_.scala.Some[TFieldBlob] => blob - case _root_.scala.None => { - val _fieldOpt: _root_.scala.Option[TField] = - _fieldId match { + val _buff = new TMemoryBuffer(32) + val _oprot = new TCompactProtocol(_buff) + + val _fieldOpt: _root_.scala.Option[TField] = _fieldId match { {{#fields}} - case {{id}} => + case {{id}} => {{#readWriteInfo}} {{#optional}} - if ({{fieldName}}.isDefined) { + if ({{fieldName}}.isDefined) { {{/optional}} {{^optional}} {{#nullable}} - if ({{fieldName}} ne null) { + if ({{fieldName}} ne null) { {{/nullable}} -{{^nullable}} - if (true) { +{{/optional}} + {{writeFieldValueName}}({{fieldName}}{{#optional}}.get{{/optional}}, _oprot) + _root_.scala.Some({{StructName}}.{{fieldConst}}) +{{#optional}} + } else { + _root_.scala.None + } +{{/optional}} +{{^optional}} +{{#nullable}} + } else { + _root_.scala.None + } {{/nullable}} {{/optional}} - {{writeFieldValueName}}({{fieldName}}{{#optional}}.get{{/optional}}, _oprot) - _root_.scala.Some({{StructName}}.{{fieldConst}}) - } else { - _root_.scala.None - } {{/readWriteInfo}} {{/fields}} - case _ => _root_.scala.None - } - _fieldOpt match { - case _root_.scala.Some(_field) => - _root_.scala.Some(TFieldBlob(_field, Buf.ByteArray.Owned(_buff.getArray()))) - case _root_.scala.None => - _root_.scala.None - } + case _ => _root_.scala.None + } + if (_fieldOpt.isDefined) { + _root_.scala.Some(TFieldBlob(_fieldOpt.get, Buf.ByteArray.Owned(_buff.getArray))) + } else { + _root_.scala.None } +{{/hasFields}} +{{^hasFields}} + _root_.scala.None +{{/hasFields}} } } + /** * Collects TCompactProtocol-encoded field values according to `getFieldBlob` into a map. */ def getFieldBlobs(ids: TraversableOnce[Short]): immutable$Map[Short, TFieldBlob] = - (ids flatMap { id => getFieldBlob(id) map { id -> _ } }).toMap + (ids.flatMap { id => getFieldBlob(id).map { fieldBlob => (id, fieldBlob) } }).toMap /** * Sets a field using a TCompactProtocol-encoded binary blob. If the field is a known @@ -706,7 +728,7 @@ class {{StructName}}( {{/optional}} {{/readWriteInfo}} {{/fields}} - case _ => _passthroughFields += (_blob.id -> _blob) + case _ => _passthroughFields += _root_.scala.Tuple2(_blob.id, _blob) } new {{InstanceClassName}}( {{#fields}} @@ -722,6 +744,7 @@ class {{StructName}}( * from the passthroughFields map, if present. */ def unsetField(_fieldId: Short): {{StructName}} = { +{{#hasFields}} {{#fields}} var {{fieldName}}: {{>optionalType}} = this.{{fieldName}} {{/fields}} @@ -738,6 +761,7 @@ class {{StructName}}( {{/fields}} case _ => } +{{/hasFields}} new {{InstanceClassName}}( {{#fields}} {{fieldName}}, @@ -831,17 +855,16 @@ class {{StructName}}( {{/hasConstructionRequiredFields}} override def canEqual(other: Any): Boolean = other.isInstanceOf[{{StructName}}] - private def _equals(x: {{StructName}}, y: {{StructName}}): Boolean = - x.productArity == y.productArity && - x.productIterator.sameElements(y.productIterator) && + private[this] def _equals(other: {{StructName}}): Boolean = + this.productArity == other.productArity && + this.productIterator.sameElements(other.productIterator) && {{#hasFailureFlags}} - x.flags == y.flags && + this.flags == other.flags && {{/hasFailureFlags}} - x._passthroughFields == y._passthroughFields + this._passthroughFields == other._passthroughFields override def equals(other: Any): Boolean = - canEqual(other) && - _equals(this, other.asInstanceOf[{{StructName}}]) + canEqual(other) && _equals(other.asInstanceOf[{{StructName}}]) override def hashCode: Int = { {{#hasFailureFlags}} @@ -857,17 +880,24 @@ class {{StructName}}( {{#hasExceptionMessage}} override def getMessage: String = String.valueOf({{exceptionMessageField}}) -{{/hasExceptionMessage}} +{{/hasExceptionMessage}} +{{^arity1ThroughN}} override def productArity: Int = {{arity}} +{{#arity0}} + override def productElement(n: Int): Any = throw new IndexOutOfBoundsException(_root_.java.lang.Integer.toString(n)) +{{/arity0}} +{{^arity0}} override def productElement(n: Int): Any = n match { {{#fields}} case {{index}} => this.{{fieldName}} {{/fields}} - case _ => throw new IndexOutOfBoundsException(n.toString) + case _ => throw new IndexOutOfBoundsException(_root_.java.lang.Integer.toString(n)) } +{{/arity0}} +{{/arity1ThroughN}} override def productPrefix: String = "{{StructName}}" def _codec: ValidatingThriftStructCodec3[{{StructName}}] = {{StructName}} @@ -889,23 +919,29 @@ class {{StructName}}( private[{{packageName}}] class {{StructName}}StructBuilder(instance: _root_.scala.Option[{{StructName}}], fieldTypes: IndexedSeq[ClassTag[_]]) extends StructBuilder[{{StructName}}](fieldTypes) { - def build(): {{StructName}} = instance match { - case _root_.scala.Some(i) => + def build(): {{StructName}} = { +{{#hasFields}} + val _fieldArray = fieldArray // shadow variable + if (instance.isDefined) { + val instanceValue = instance.get {{StructName}}( {{#fields}} - (if (fieldArray({{index}}) == null) i.{{fieldName}}{{#constructionRequired}}.get{{/constructionRequired}} else fieldArray({{index}})).asInstanceOf[{{>constructionOptionalType}}] + if (_fieldArray({{index}}) == null) instanceValue.{{fieldName}}{{#constructionRequired}}.get{{/constructionRequired}} else _fieldArray({{index}}).asInstanceOf[{{>constructionOptionalType}}] {{/fields|,}} ) - case _root_.scala.None => - if (fieldArray.contains(null)) throw new InvalidFieldsException(structBuildError("{{StructName}}")) - else { - {{StructName}}( + } else { + if (genericArrayOps(_fieldArray).contains(null)) throw new InvalidFieldsException(structBuildError("{{StructName}}")) + {{StructName}}( {{#fields}} - fieldArray({{index}}).asInstanceOf[{{>constructionOptionalType}}] + _fieldArray({{index}}).asInstanceOf[{{>constructionOptionalType}}] {{/fields|,}} - ) - } + ) } +{{/hasFields}} +{{^hasFields}} + {{StructName}}() +{{/hasFields}} + } } {{#adapt}} @@ -943,8 +979,9 @@ private class {{StructName}}__AdaptDecoder { {{/fields}} _iprot.readStructBegin() - while (!_done) { + do { val _field = _iprot.readFieldBegin() + val _fieldType = _field.`type` if (_field.`type` == TType.STOP) { _done = true } else { @@ -954,15 +991,14 @@ private class {{StructName}}__AdaptDecoder { {{>readAdaptField}} } {{/fields}} - case _ => - if (_passthroughFields == null) + if (_passthroughFields eq null) _passthroughFields = immutable$Map.newBuilder[Short, TFieldBlob] - _passthroughFields += (_field.id -> TFieldBlob.read(_field, _iprot)) + _passthroughFields += _root_.scala.Tuple2(_field.id, TFieldBlob.read(_field, _iprot)) } _iprot.readFieldEnd() } - } + } while (!_done) _iprot.readStructEnd() {{#fields}} @@ -971,7 +1007,7 @@ private class {{StructName}}__AdaptDecoder { {{/required}} {{/fields}} adapt.set__endOffset(_iprot.offset) - if (_passthroughFields != null) { + if (_passthroughFields ne null) { adapt.set__passthroughFields(_passthroughFields.result()) } adapt @@ -1009,7 +1045,7 @@ private class {{StructName}}__Adapt( {{/fields}} private[this] var _end_offset: Int = _ - def set__endOffset(offset: Int) = _end_offset = offset + def set__endOffset(offset: Int): Unit = _end_offset = offset private[this] var __passthroughFields: immutable$Map[Short, TFieldBlob] = {{StructName}}.NoPassthroughFields def set__passthroughFields(passthroughFields: immutable$Map[Short, TFieldBlob]): Unit = @@ -1031,9 +1067,10 @@ private class {{StructName}}__Adapt( override lazy val hashCode: Int = super.hashCode override def write(_oprot: TProtocol): Unit = { - _oprot match { - case i: AdaptTProtocol => i.writeRaw(_buf, _start_offset, _end_offset - _start_offset) - case _ => super.write(_oprot) + if (_oprot.isInstanceOf[AdaptTProtocol]) { + _oprot.asInstanceOf[AdaptTProtocol].writeRaw(_buf, _start_offset, _end_offset - _start_offset) + } else { + super.write(_oprot) } } } diff --git a/scrooge-generator/src/main/resources/scalagen/union.mustache b/scrooge-generator/src/main/resources/scalagen/union.mustache index 14b6ab054..8c585bebe 100644 --- a/scrooge-generator/src/main/resources/scalagen/union.mustache +++ b/scrooge-generator/src/main/resources/scalagen/union.mustache @@ -27,6 +27,7 @@ private object {{StructName}}Decoder { var _result: {{StructName}} = null _iprot.readStructBegin() val _field = _iprot.readFieldBegin() + val _fieldType = _field.`type` _field.id match { {{#fields}} {{#readWriteInfo}} @@ -34,33 +35,33 @@ private object {{StructName}}Decoder { {{/readWriteInfo}} {{/fields}} case _ => - if (_field.`type` != TType.STOP) { + if (_fieldType != TType.STOP) { _result = newUnknown(TFieldBlob.read(_field, _iprot)) } else { - TProtocolUtil.skip(_iprot, _field.`type`) + TProtocolUtil.skip(_iprot, _fieldType) } } - if (_field.`type` != TType.STOP) { + if (_fieldType != TType.STOP) { _iprot.readFieldEnd() var _done = false var _moreThanOne = false - while (!_done) { - val _field = _iprot.readFieldBegin() - if (_field.`type` == TType.STOP) + do { + val _newField = _iprot.readFieldBegin() + if (_newField.`type` == TType.STOP) _done = true else { _moreThanOne = true - TProtocolUtil.skip(_iprot, _field.`type`) + TProtocolUtil.skip(_iprot, _newField.`type`) _iprot.readFieldEnd() } - } + } while (!_done) if (_moreThanOne) { _iprot.readStructEnd() throw new TProtocolException("Cannot read a TUnion with more than one set value!") } } _iprot.readStructEnd() - if (_result == null) + if (_result eq null) throw new TProtocolException("Cannot read a TUnion with no set value!") _result } @@ -72,12 +73,17 @@ object {{StructName}}Aliases { type {{FieldName}}Alias = {{fieldType}} def withoutPassthroughFields_{{FieldName}}(obj: {{StructName}}.{{FieldName}}): {{StructName}}.{{FieldName}} = { +{{#hasPassthroughFields}} val field = obj.{{fieldName}} {{#passthroughFields}} {{StructName}}.{{FieldName}}( {{>withoutPassthrough}} ) {{/passthroughFields}} +{{/hasPassthroughFields}} +{{^hasPassthroughFields}} + {{StructName}}.{{FieldName}}(obj.{{fieldName}}) +{{/hasPassthroughFields}} } {{#hasDefaultValue}} @@ -85,7 +91,7 @@ object {{StructName}}Aliases { {{/hasDefaultValue}} {{#fieldKeyType}} val {{FieldName}}KeyTypeManifest: _root_.scala.Option[Manifest[{{fieldKeyType}}]] = - _root_.scala.Some(implicitly[Manifest[{{fieldKeyType}}]]) + _root_.scala.Some(manifest[{{fieldKeyType}}]) {{/fieldKeyType}} {{^fieldKeyType}} val {{FieldName}}KeyTypeManifest: _root_.scala.Option[Manifest[_]] = _root_.scala.None @@ -93,7 +99,7 @@ object {{StructName}}Aliases { {{#fieldValueType}} val {{FieldName}}ValueTypeManifest: _root_.scala.Option[Manifest[{{fieldValueType}}]] = - _root_.scala.Some(implicitly[Manifest[{{fieldValueType}}]]) + _root_.scala.Some(manifest[{{fieldValueType}}]) {{/fieldValueType}} {{^fieldValueType}} val {{FieldName}}ValueTypeManifest: _root_.scala.Option[Manifest[_]] = _root_.scala.None @@ -108,16 +114,16 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] { {{#fields}} val {{fieldConst}}: TField = new TField("{{fieldNameForWire}}", TType.{{constType}}, {{id}}) {{#isEnum}} - private[this] val {{fieldConst}}I32 = new TField("{{fieldNameForWire}}", TType.I32, {{id}}) + private[this] val {{fieldConst}}I32: TField = new TField("{{fieldNameForWire}}", TType.I32, {{id}}) {{/isEnum}} - val {{fieldConst}}Manifest: Manifest[{{FieldName}}] = implicitly[Manifest[{{FieldName}}]] + val {{fieldConst}}Manifest: Manifest[{{FieldName}}] = manifest[{{FieldName}}] {{/fields}} - lazy val structAnnotations: immutable$Map[java.lang.String, java.lang.String] = + {{#structAnnotations}}lazy {{/structAnnotations}}val structAnnotations: immutable$Map[java.lang.String, java.lang.String] = {{#structAnnotations}} immutable$Map[java.lang.String, java.lang.String]( {{#pairs}} - "{{key}}" -> "{{value}}" + ("{{key}}", "{{value}}") {{/pairs|,}} ) {{/structAnnotations}} @@ -128,7 +134,7 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] { /** * Field information in declaration order. */ - lazy val fieldInfos: scala.List[ThriftUnionFieldInfo[_ <: {{StructName}}, _]] = scala.List( + {{#hasFields}}lazy {{/hasFields}}val fieldInfos: scala.List[ThriftUnionFieldInfo[_ <: {{StructName}}, _]] = scala.List( {{#fields}} new ThriftUnionFieldInfo[{{FieldName}}, {{StructName}}Aliases.{{FieldName}}Alias]( {{FieldName}}.fieldInfo, @@ -139,8 +145,8 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] { override lazy val metaData = new ThriftStructMetaData( this, - Seq(), - Seq(), + Nil, + Nil, fieldInfos.asInstanceOf[Seq[ThriftUnionFieldInfo[_root_.com.twitter.scrooge.ThriftUnion with _root_.com.twitter.scrooge.ThriftStruct, _]]], structAnnotations) @@ -148,19 +154,22 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] { _item.write(_oprot) override def decode(_iprot: TProtocol): {{StructName}} = - {{StructName}}Decoder(_iprot, UnknownUnionField(_)) + {{StructName}}Decoder(_iprot, UnknownUnionField.apply) def apply(_iprot: TProtocol): {{StructName}} = decode(_iprot) import {{StructName}}Aliases._ def withoutPassthroughFields(struct: {{StructName}}): {{StructName}} = { - struct match { +{{#hasFields}} {{#fields}} - case obj: {{FieldName}} => withoutPassthroughFields_{{FieldName}}(obj) + {{^first}}else {{/first}}if (struct.isInstanceOf[{{FieldName}}]) withoutPassthroughFields_{{FieldName}}(struct.asInstanceOf[{{FieldName}}]) {{/fields}} - case unknown: UnknownUnionField => unknown // by definition pass-through - } + else struct //This is an UnknownUnionField, by definition passthrough +{{/hasFields}} +{{^hasFields}} + struct +{{/hasFields}} } {{#fields}} @@ -179,7 +188,7 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] { {{#fieldTypeAnnotations}} immutable$Map( {{#pairs}} - "{{key}}" -> "{{value}}" + ("{{key}}", "{{value}}") {{/pairs|,}} ), {{/fieldTypeAnnotations}} @@ -189,7 +198,7 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] { {{#fieldFieldAnnotations}} immutable$Map( {{#pairs}} - "{{key}}" -> "{{value}}" + ("{{key}}", "{{value}}") {{/pairs|,}} ) {{/fieldFieldAnnotations}} @@ -216,7 +225,7 @@ object {{StructName}} extends ValidatingThriftStructCodec3[{{StructName}}] { override def write(_oprot: TProtocol): Unit = { {{^isPrimitive}} - if ({{fieldName}} == null) + if ({{fieldName}} eq null) throw new TProtocolException("Cannot write a TUnion with no set value!") {{/isPrimitive}} _oprot.writeStructBegin(Union) diff --git a/scrooge-generator/src/main/resources/scalagen/withoutPassthrough.mustache b/scrooge-generator/src/main/resources/scalagen/withoutPassthrough.mustache index e095aa313..8b3a83914 100644 --- a/scrooge-generator/src/main/resources/scalagen/withoutPassthrough.mustache +++ b/scrooge-generator/src/main/resources/scalagen/withoutPassthrough.mustache @@ -8,21 +8,21 @@ field.map { field => {{/ptIter}} {{#ptMap}} field.map { case (key, value) => - {{#ptKey}} +{{#ptKey}} val newKey = { val field = key {{>withoutPassthrough}} } - {{/ptKey}} +{{/ptKey}} - {{#ptValue}} +{{#ptValue}} val newValue = { val field = value {{>withoutPassthrough}} } - {{/ptValue}} +{{/ptValue}} - newKey -> newValue + (newKey, newValue) } {{/ptMap}} {{#ptStruct}} diff --git a/scrooge-generator/src/main/resources/scalagen/writeField.mustache b/scrooge-generator/src/main/resources/scalagen/writeField.mustache index 067145dc5..2a4338729 100644 --- a/scrooge-generator/src/main/resources/scalagen/writeField.mustache +++ b/scrooge-generator/src/main/resources/scalagen/writeField.mustache @@ -5,12 +5,14 @@ if ({{fieldName}}.isDefined) { {{#nullable}} if ({{fieldName}} ne null) { {{/nullable}} -{{^nullable}} -if (true) { -{{/nullable}} {{/optional}} val {{valueVariableName}} = {{fieldName}}{{#optional}}.get{{/optional}} _oprot.writeFieldBegin({{fieldConst}}{{#isEnum}}I32{{/isEnum}}) {{>writeValue}} _oprot.writeFieldEnd() +{{#optional}} + } +{{/optional}} +{{^optional}}{{#nullable}} } +{{/nullable}}{{/optional}} diff --git a/scrooge-generator/src/main/resources/scalagen/writeList.mustache b/scrooge-generator/src/main/resources/scalagen/writeList.mustache index 1c6b2f21f..3b920163e 100644 --- a/scrooge-generator/src/main/resources/scalagen/writeList.mustache +++ b/scrooge-generator/src/main/resources/scalagen/writeList.mustache @@ -1,20 +1,19 @@ _oprot.writeListBegin(new TList(TType.{{eltWireConstType}}, {{name}}.size)) -{{name}} match { - case _: IndexedSeq[_] => - var _i = 0 - val _size = {{name}}.size - while (_i < _size) { - val {{eltName}} = {{name}}(_i) +if ({{name}}.isInstanceOf[IndexedSeq[_]]) { + var _i = 0 + val _size = {{name}}.size + while (_i < _size) { + val {{eltName}} = {{name}}(_i) {{#eltReadWriteInfo}} - {{>writeValue}} + {{>writeValue}} {{/eltReadWriteInfo}} - _i += 1 - } - case _ => - {{name}}.foreach { {{eltName}} => + _i += 1 + } +} else { + {{name}}.foreach { {{eltName}} => {{#eltReadWriteInfo}} - {{>writeValue}} + {{>writeValue}} {{/eltReadWriteInfo}} - } + } } _oprot.writeListEnd() diff --git a/scrooge-generator/src/main/scala/com/twitter/scrooge/backend/ServiceTemplate.scala b/scrooge-generator/src/main/scala/com/twitter/scrooge/backend/ServiceTemplate.scala index 9da4f187c..6bf77b98f 100644 --- a/scrooge-generator/src/main/scala/com/twitter/scrooge/backend/ServiceTemplate.scala +++ b/scrooge-generator/src/main/scala/com/twitter/scrooge/backend/ServiceTemplate.scala @@ -176,13 +176,18 @@ trait ServiceTemplate { self: TemplateGenerator => "typeName" -> genType(f.funcType), "isVoid" -> v(f.funcType == Void || f.funcType == OnewayVoid), "resultNamedArg" -> - v(if (f.funcType != Void && f.funcType != OnewayVoid) "success = Some(value)" else ""), - "exceptions" -> v(f.throws map { t => - Dictionary( - "exceptionType" -> genType(t.fieldType), - "fieldName" -> genID(t.sid) - ) - }) + v(if (f.funcType != Void && f.funcType != OnewayVoid) "success = Some(resTry.apply())" + else ""), + "exceptions" -> v(f.throws.zipWithIndex map { + case (t, index) => + Dictionary( + "exceptionType" -> genType(t.fieldType), + "fieldName" -> genID(t.sid), + "first" -> v(index == 0), + "last" -> v(index == f.throws.size - 1) + ) + }), + "hasExceptions" -> v(f.throws.nonEmpty) ) }), "hasMethodServices" -> v(service.functions.nonEmpty) @@ -335,13 +340,18 @@ trait ServiceTemplate { self: TemplateGenerator => ), "typeName" -> genType(f.funcType), "resultNamedArg" -> - v(if (f.funcType != Void && f.funcType != OnewayVoid) "success = Some(value)" else ""), - "exceptions" -> v(f.throws map { t => - Dictionary( - "exceptionType" -> genType(t.fieldType), - "fieldName" -> genID(t.sid) - ) - }) + v(if (f.funcType != Void && f.funcType != OnewayVoid) "success = Some(resTry.apply())" + else ""), + "exceptions" -> v(f.throws.zipWithIndex map { + case (t, index) => + Dictionary( + "exceptionType" -> genType(t.fieldType), + "fieldName" -> genID(t.sid), + "first" -> v(index == 0), + "last" -> v(index == f.throws.size - 1) + ) + }), + "hasExceptions" -> v(f.throws.nonEmpty) ) }) ) diff --git a/scrooge-generator/src/main/scala/com/twitter/scrooge/backend/StructTemplate.scala b/scrooge-generator/src/main/scala/com/twitter/scrooge/backend/StructTemplate.scala index aa6dc1747..026629d42 100644 --- a/scrooge-generator/src/main/scala/com/twitter/scrooge/backend/StructTemplate.scala +++ b/scrooge-generator/src/main/scala/com/twitter/scrooge/backend/StructTemplate.scala @@ -198,6 +198,7 @@ trait StructTemplate { self: TemplateGenerator => case _ => false }), "isNamedType" -> v(field.fieldType.isInstanceOf[NamedType]), + "hasPassthroughFields" -> v(!canCallWithoutPassthroughFields(field.fieldType)), "passthroughFields" -> { val insides = buildPassthroughFields(field.fieldType) if (field.requiredness.isOptional) { @@ -335,6 +336,34 @@ trait StructTemplate { self: TemplateGenerator => v(basePassthrough + overrides) } + /** + * Returns whether the fieldType is such that it cannot possibly contain passthrough fields. + * + * Examples - primitive types, Strings do not contain pass through. + * Collections containing only primitive elements also cannot. + * + * @param fieldType Field type being checked + * @return + */ + private def canCallWithoutPassthroughFields(fieldType: FieldType): Boolean = { + fieldType match { + case t if isPrimitive(t) => + true + case TBinary | TString => + true + case _: EnumType => + true + case ListType(eltType, _) => + canCallWithoutPassthroughFields(eltType) + case SetType(eltType, _) => + canCallWithoutPassthroughFields(eltType) + case MapType(keyType, valueType, _) => + canCallWithoutPassthroughFields(keyType) && canCallWithoutPassthroughFields(valueType) + case _ => + false + } + } + private def exceptionMsgFieldName(struct: StructLike): Option[SimpleID] = { val msgField: Option[Field] = struct.fields .find { field => @@ -458,6 +487,7 @@ trait StructTemplate { self: TemplateGenerator => "arity0" -> v(arity == 0), "arity1" -> v(if (arity == 1) fieldDictionaries.take(1) else Nil), "arityN" -> v(arity > 1 && arity <= 22), + "arity1ThroughN" -> v(arity >= 1 && arity <= 22), "withFieldGettersAndSetters" -> v(isStruct || isException), "withTrait" -> v(isStruct), "adapt" -> v(genAdapt),