From 594e5a5dca6aeeb0c2becc53a71a7747699c73c4 Mon Sep 17 00:00:00 2001 From: changvvb Date: Sun, 18 Apr 2021 01:04:14 +0800 Subject: [PATCH 01/17] WIP --- build.sbt | 15 +- .../scala/pbconverts/ProtoScalableMacro.scala | 820 +++++++++--------- .../pbconverts/ScalableImplicits.scala | 44 + .../main/scala/pbconverts/ProtoScalable.scala | 2 +- .../src/main/scala/pbconverts/Protoable.scala | 47 +- .../scala/pbconverts/ProtoableBuilder.scala | 8 +- .../src/main/scala/pbconverts/Scalable.scala | 34 +- .../scala/pbconverts/ScalableBuilder.scala | 8 +- .../scala/pbconverts/ScalableImplicits.scala | 44 + project/build.properties | 2 +- 10 files changed, 561 insertions(+), 463 deletions(-) create mode 100644 pbconverts/src/main/scala-3.00/pbconverts/ScalableImplicits.scala create mode 100644 pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala diff --git a/build.sbt b/build.sbt index cfcef45..b2876d2 100644 --- a/build.sbt +++ b/build.sbt @@ -1,25 +1,26 @@ import sbt._ -lazy val scala213 = "2.13.4" -lazy val scala212 = "2.12.12" +//lazy val scala213 = "2.13.4" +//lazy val scala212 = "2.12.12" +lazy val scala3 = "3.0.0-RC2" -lazy val supportedScalaVersions = List(scala212, scala213) +//lazy val supportedScalaVersions = List(scala212, scala213) val commonSettings = Seq( - scalaVersion := scala213, + scalaVersion := scala3, scalacOptions += "-language:experimental.macros", organization := "com.github.changvvb", - crossScalaVersions := supportedScalaVersions, +// crossScalaVersions := supportedScalaVersions, releasePublishArtifactsAction := PgpKeys.publishSigned.value ) lazy val `scala-protobuf-java-macro` = project.in(file("pbconverts-macro")) - .settings(libraryDependencies ++= Seq("org.scala-lang" % "scala-reflect" % scalaVersion.value)) +// .settings(libraryDependencies ++= Seq("org.scala-lang" % "scala-reflect" % scalaVersion.value)) .settings(commonSettings) .enablePlugins(ProtobufPlugin) lazy val `scala-protobuf-java` = project.in(file("pbconverts")) - .settings(libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.0" % "test") + .settings(libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.7" % "test") .settings(commonSettings) .dependsOn(`scala-protobuf-java-macro`) .enablePlugins(ProtobufTestPlugin) diff --git a/pbconverts-macro/src/main/scala/pbconverts/ProtoScalableMacro.scala b/pbconverts-macro/src/main/scala/pbconverts/ProtoScalableMacro.scala index 70b4459..289bd69 100644 --- a/pbconverts-macro/src/main/scala/pbconverts/ProtoScalableMacro.scala +++ b/pbconverts-macro/src/main/scala/pbconverts/ProtoScalableMacro.scala @@ -3,415 +3,415 @@ package pbconverts import com.google.protobuf.ByteString import scala.collection.mutable -import scala.reflect.macros.whitebox +//import scala.reflect.macros.whitebox // scalastyle:off number.of.methods -class ProtoScalableMacro(val c: whitebox.Context) { - import c.universe._ - - private[this] def packageName: Tree = q"_root_.pbconverts" - private[this] def builderIdent = Ident(TermName("builder")) - private[this] def entityIdent = Ident(TermName("entity")) - private[this] def protoIdent = Ident(TermName("proto")) - private[this] def implicitlyProtoable(entityType: Type, protoType: Type) = q"implicitly[$packageName.Protoable[$entityType,$protoType]]" - - private[this] def implicitlyScalable(entityType: Type, protoType: Type) = q"implicitly[$packageName.Scalable[$entityType,$protoType]]" - - private[this] def isOption(tpe: Type): Boolean = tpe <:< typeOf[Option[_]] - - private[this] def isIterable(tpe: Type): Boolean = - (tpe <:< typeOf[Iterable[_]] - || tpe <:< typeOf[Array[_]] - || tpe <:< typeOf[java.lang.Iterable[_]]) && !(tpe <:< typeOf[Map[_, _]] || tpe <:< typeOf[ByteString]) - - private[this] def isMap(tpe: Type): Boolean = tpe <:< typeOf[Map[_, _]] || tpe <:< typeOf[java.util.Map[_, _]] - - private[this] def getBuilderType(protoType: Type): Type = { - protoType.companion.member(TermName("newBuilder")).asTerm.alternatives.head.asMethod.returnType - } - - trait Processor { - - def caseClassType: Type - def protoType: Type - - def scalaTreeType: Type - def protoValueType: Type - - def resolvedCaseClassFieldType: Type = resolveFieldType(caseClassType, scalaTreeType) - - def tree: Option[Tree] - } - - // Convert expr (`scalaTree` in this class) to protobuf value - class ToProtoProcessor( - scalaTree: Tree, - override val scalaTreeType: Type, - override val caseClassType: Type, - override val protoType: Type, - override val protoFieldName: String - ) extends ProtoFieldAnalyst { - - private[this] def toProto(t1: Type, t2: Type): Tree = { - if (t1 <:< t2) { - scalaTree - } else { - q"${implicitlyProtoable(t1, t2)}.toProto($scalaTree)" - } - } - - override def protoValueType: Type = protoValueSetterType - - def optTree(optFieldType: Type): c.universe.Tree = { - val tree = if (isIterable(protoValueType)) { - seqTree(optFieldType) - } else if (isMap(protoValueType)) { - mapTree(optFieldType) - } else { - defaultTree(optFieldType) - } - If(q"$scalaTree.isDefined", tree, EmptyTree) - } - - def seqTree(iterableType: Type): c.universe.Tree = { - val listType = builderType.member(addAllMethodName).asMethod.paramLists.head.head.typeSignature - val valueTree = toProto(iterableType, listType) - q"${builderIdent}.$addAllMethodName($valueTree)" - } - - def mapTree(mapType: Type): c.universe.Tree = { - val putAllMapType = builderType.member(putAllMethodName).asMethod.paramLists.head.head.typeSignature - val valueTree = toProto(mapType, putAllMapType) - q"${builderIdent}.$putAllMethodName($valueTree)" - } - - def defaultTree(fieldType: Type): c.universe.Tree = { - val valueTree = toProto(fieldType, protoValueType) - q"${builderIdent}.$setField(${valueTree})" - } - - override def tree: Option[Tree] = { - if (protoValueType == NoType) { - None - } else { - val _tree = if (isOption(scalaTreeType)) { - optTree(resolvedCaseClassFieldType) - } else if (isIterable(protoValueType)) { - seqTree(resolvedCaseClassFieldType) - } else if (isMap(protoValueType)) { - mapTree(resolvedCaseClassFieldType) - } else { - defaultTree(resolvedCaseClassFieldType) - } - - if (scalaTreeType <:< typeOf[AnyRef]) { - val notNullCondition = q"$scalaTree ne null" - Some(If(notNullCondition, _tree, EmptyTree)) - } else { - Some(_tree) - } - } - } - } - - // Convert expr (`protoValueTree` in this class) to case class filed value - case class ToScalaProcessor(caseClassSelector: MethodSymbol, protoValueTree: Tree, protoValueType: Type, caseClassType: Type, protoType: Type) - extends AbstractToScalaProcessor - - trait AbstractToScalaProcessor extends Processor { - - def caseClassSelector: MethodSymbol - - def protoValueTree: Tree - - override def scalaTreeType: Type = caseClassSelector.returnType - - protected def toScala(t1: Type, t2: Type, value: Tree) = { - if (t2 <:< t1) { - value - } else { - q"${implicitlyScalable(t1, t2)}.toScala($value)" - } - } - - def optTree(optType: Type): c.universe.Tree = defaultTree(optType) - - def defaultTree(fieldType: Type): Tree = { - q"$caseClassSelector = ${toScala(fieldType, protoValueType, protoValueTree)}" - } - - override def tree: Option[Tree] = - if (protoValueType == NoType) { - None - } else { - if (isOption(scalaTreeType)) { - Some(optTree(resolvedCaseClassFieldType)) - } else { - Some(defaultTree(resolvedCaseClassFieldType)) - } - } - } - - // Contain some methods and vals to analyze Protobuf fields - trait ProtoFieldAnalyst extends Processor { - def protoFieldName: String - - val builderType = getBuilderType(protoType) - - def addAllMethodName: TermName = TermName(s"addAll$protoFieldName") - def putAllMethodName: TermName = TermName(s"putAll$protoFieldName") - - def addField: TermName = TermName(s"add$protoFieldName") - def putField: TermName = TermName(s"put$protoFieldName") - def setField: TermName = TermName(s"set$protoFieldName") - def getField: TermName = TermName(s"get$protoFieldName") - def getMapField: TermName = TermName(s"get${protoFieldName}Map") - def getListField: TermName = TermName(s"get${protoFieldName}List") - def builderSetter: TermName = if (isIterable(scalaTreeType)) addAllMethodName else setField - - val protoValueTree: Tree = { - if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 - q"$protoIdent.$getListField" - } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map - q"$protoIdent.$getMapField" - } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 - q"$protoIdent.$getField" - } else { - q"" - } - } - - lazy val protoValueSetterType: Type = { - val pbBuilderType = typeOf[com.google.protobuf.Message.Builder] - val setterOpt = if (builderType.member(addField) != NoSymbol) { - Some(builderType.member(addAllMethodName)) - } else if (builderType.member(putField) != NoSymbol) { - Some(builderType.member(putAllMethodName)) - } else if (builderType.member(setField) != NoSymbol) { - Some(builderType.member(setField)) - } else { - None - } - setterOpt.fold(NoType)(_.alternatives.map(_.asMethod.paramLists.head.head.typeSignature).find(t ⇒ !(t <:< pbBuilderType)).get) - } - - lazy val protoValueGetterType: Type = { - if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 - protoType.member(getListField).typeSignature.resultType - } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map - protoType.member(getMapField).typeSignature.resultType - } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 - protoType.member(getField).typeSignature.resultType - } else { - NoType - } - } - - } - - // Convert scala clase class field value to protobuf value - case class ToProtoFieldProcessor(accessor: MethodSymbol, override val caseClassType: Type, override val protoType: Type) - extends ToProtoProcessor(q"$entityIdent.$accessor", accessor.returnType, caseClassType, protoType, accessor.name.toString.capitalize) - - // Convert protobuf value to case class filed value - case class ToScalaFieldProcessor(accessor: MethodSymbol, override val caseClassType: Type, override val protoType: Type) - extends AbstractToScalaProcessor - with ProtoFieldAnalyst { - - override def caseClassSelector: MethodSymbol = accessor - - override def protoFieldName: String = accessor.name.toString.capitalize - - override def protoValueType: Type = protoValueGetterType - - override def optTree(optType: Type): c.universe.Tree = { - val hasProtoField = TermName(s"has$protoFieldName") - if (protoType.member(hasProtoField) == NoSymbol) { - defaultTree(optType) - } else { - q"$caseClassSelector = if (${protoIdent}.$hasProtoField) ${toScala(optType, protoValueType, protoValueTree)} else None" - } - } - } - - private[this] def resolveFieldType(entityType: Type, originType: Type): Type = - originType.asSeenFrom(entityType, entityType.typeSymbol.asClass) - - private[this] def resolveType[T: WeakTypeTag]: Type = { - val tpe = weakTypeOf[T] - tpe.dealias - } - - private[this] def getCaseAccessors(caseClassType: Type): Seq[MethodSymbol] = { - caseClassType.members.collect { case m: MethodSymbol if m.isCaseAccessor ⇒ m }.toSeq.reverse - } - - private[this] def defaultProtoableFieldConvertTrees(caseClassType: Type, protoType: Type): Map[String, Tree] = { - getCaseAccessors(caseClassType).flatMap { a ⇒ - val p = ToProtoFieldProcessor(a, caseClassType, protoType) - p.tree.map(p.protoFieldName -> _) - }.toMap - } - - private[this] def protoableBody(caseClassType: Type, protoType: Type, protoableFieldConvertTrees: Iterable[Tree]): Tree = { - q""" - override def toProto(${entityIdent.name.toTermName}: $caseClassType): $protoType = { - val ${builderIdent} = ${protoType.typeSymbol.companion}.newBuilder() - ..$protoableFieldConvertTrees - $builderIdent.build() - } - """ - } - - private def defalutScalableFieldConvertTrees(caseClassType: Type, protoType: Type): Map[String, Tree] = { - getCaseAccessors(caseClassType).flatMap(accessor ⇒ ToScalaFieldProcessor(accessor, caseClassType, protoType).tree.map(accessor.name.toString -> _)).toMap - } - - private def scalableBody(caseClassType: Type, protoType: Type, scalableFieldConvertTrees: Iterable[Tree]): Tree = { - q""" - override def toScala(${protoIdent.name.toTermName} :$protoType): $caseClassType = { - new ${caseClassType.typeSymbol} ( - ..${scalableFieldConvertTrees} - ) - } - """ - } - - def scalasImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { - val caseClassType = resolveType[T] - val protoType = resolveType[M] - val scalableFieldConvertTrees = defalutScalableFieldConvertTrees(caseClassType, protoType).values - scalasImpl(caseClassType, protoType, scalableFieldConvertTrees, Nil) - } - - private[this] def scalasImpl(caseClassType: Type, protoType: Type, scalableFieldConvertTrees: Iterable[Tree], perTrees: Iterable[Tree]): Tree = { - q""" - ..$perTrees - new $packageName.Scalable[$caseClassType, $protoType] { ${scalableBody(caseClassType, protoType, scalableFieldConvertTrees)} } - """ - } - - def protosImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { - val caseClassType = resolveType[T] - val protoType = resolveType[M] - protosImpl(caseClassType, protoType, defaultProtoableFieldConvertTrees(caseClassType, protoType).values, Nil) - } - - private[this] def protosImpl(caseClassType: Type, protoType: Type, protoableFieldConvertTrees: Iterable[Tree], perTrees: Iterable[Tree]): Tree = { - q""" - ..$perTrees - new $packageName.Protoable[$caseClassType,$protoType] { ${protoableBody(caseClassType, protoType, protoableFieldConvertTrees)} } - """ - } - - def convertsImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { - val caseClassType = resolveType[T] - val protoType = resolveType[M] - q""" - new $packageName.ProtoScalable[${resolveType[T]}, ${resolveType[M]}] { - ${scalableBody(caseClassType, protoType, defalutScalableFieldConvertTrees(caseClassType, protoType).values)} - ${protoableBody(caseClassType, protoType, defaultProtoableFieldConvertTrees(caseClassType, protoType).values)} - } - """ - } - - def buildProtoableImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { - val caseClassType = resolveType[T] - val protoType = resolveType[M] - val customTrees = MacroCache.builderFunctionTrees.getOrElse(getBuilderId(), mutable.Map.empty) - val (fixedCustomTrees, preTrees) = customTrees.map { - case (key, tree) ⇒ - tree match { // setField - case buildFunction: Function ⇒ - val functionName = TermName("builderFunction$" + MacroCache.getIdentityId) - val fromType = buildFunction.tpe.typeArgs.last // buildFunction 的返回值 - val buildExpr = new ToProtoProcessor(q"$functionName($entityIdent)", fromType, caseClassType, protoType, key).tree.get - (key -> buildExpr) -> q"val $functionName = $buildFunction" - case value: Tree ⇒ // setFieldValue - val identity = TermName("identity$" + MacroCache.getIdentityId) - val buildExpr = new ToProtoProcessor(q"$identity", value.tpe, caseClassType, protoType, key).tree.get - (key -> buildExpr) -> q"val $identity = $value" - } - }.unzip - val protoableFieldConvertTrees = (defaultProtoableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values - protosImpl(caseClassType, protoType, protoableFieldConvertTrees, preTrees) - } - - def buildScalableImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { - val caseClassType = resolveType[T] - val protoType = resolveType[M] - val builderId = getBuilderId() - val customTrees = MacroCache.builderFunctionTrees.getOrElse(builderId, mutable.Map.empty) - val entityType = resolveType[T] - - val (fixedCustomTrees, preTrees) = customTrees.map { - case (key, tree) ⇒ - val selector = entityType.member(TermName(key)) - tree match { - case buildFunction: Function ⇒ // setField - val functionName = TermName("builderFunction$" + MacroCache.getIdentityId) - val expr = new ToScalaProcessor(selector.asMethod, q"$functionName($protoIdent)", buildFunction.body.tpe, resolveType[T], resolveType[M]).tree.get - (key -> expr) -> q"val $functionName = $buildFunction" - case value: Tree ⇒ // setFieldValue - val identity = TermName("identity$" + MacroCache.getIdentityId) - val expr = new ToScalaProcessor(selector.asMethod, q"$identity", value.tpe, resolveType[T], resolveType[M]).tree.get - (key -> expr) -> q"val $identity = $value" - } - }.unzip - - val scalableFieldConvertTrees = (defalutScalableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values - scalasImpl(caseClassType, protoType, scalableFieldConvertTrees, preTrees) - } - - def setScalaFieldImpl[T: WeakTypeTag, M: WeakTypeTag, TF: WeakTypeTag, MF: WeakTypeTag](scalaField: Tree, value: Tree): Tree = { - val Function(_, Select(_, termName)) = scalaField - val builderId = getBuilderId() - MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(termName.toString, value) - q"new ${c.prefix.actualType}" - } - - def setProtoFieldImpl[T: WeakTypeTag, M: WeakTypeTag, TF: WeakTypeTag, MF: WeakTypeTag](protoFieldSelector: Tree, value: Tree): Tree = { - val getter = "^get(\\w+)$".r - val listGetter = "^get(\\w+)List$".r - val mapGetter = "^get(\\w+)Map$".r - val setter = protoFieldSelector.find { - case _: Select ⇒ true - case _: Tree ⇒ false - } match { - case Some(select: Select) ⇒ - select.name.toString match { - case mapGetter(n) if select.tpe.resultType <:< typeOf[java.util.Map[_, _]] ⇒ n - case listGetter(n) if select.tpe.resultType <:< typeOf[java.util.List[_]] ⇒ n - case getter(n) ⇒ n - case _ ⇒ c.abort(protoFieldSelector.pos, "Invalid setter") - } - case _ ⇒ c.abort(protoFieldSelector.pos, "Invalid setter") - } - val builderId = getBuilderId() - MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(setter, value) - q"new ${c.prefix.actualType}" - } - - val annoBuilderPrefix = "AnonBuilder$" - - def scalableBuilderApply[T: WeakTypeTag, M: WeakTypeTag]: Tree = { - val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) - q""" - class $className extends $packageName.ScalableBuilder[${resolveType[T]}, ${resolveType[M]}] - new $className - """ - } - - def protoableBuilderApply[T: WeakTypeTag, M: WeakTypeTag]: Tree = { - val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) - q""" - class $className extends $packageName.ProtoableBuilder[${resolveType[T]}, ${resolveType[M]}] - new $className - """ - } - - private[this] def getBuilderId() = { - c.prefix.actualType.toString.replace(annoBuilderPrefix, "").toInt - } - -} +//class ProtoScalableMacro(val c: whitebox.Context) { +// import c.universe._ + +// private[this] def packageName: Tree = q"_root_.pbconverts" +// private[this] def builderIdent = Ident(TermName("builder")) +// private[this] def entityIdent = Ident(TermName("entity")) +// private[this] def protoIdent = Ident(TermName("proto")) +// private[this] def implicitlyProtoable(entityType: Type, protoType: Type) = q"implicitly[$packageName.Protoable[$entityType,$protoType]]" +// +// private[this] def implicitlyScalable(entityType: Type, protoType: Type) = q"implicitly[$packageName.Scalable[$entityType,$protoType]]" +// +// private[this] def isOption(tpe: Type): Boolean = tpe <:< typeOf[Option[_]] +// +// private[this] def isIterable(tpe: Type): Boolean = +// (tpe <:< typeOf[Iterable[_]] +// || tpe <:< typeOf[Array[_]] +// || tpe <:< typeOf[java.lang.Iterable[_]]) && !(tpe <:< typeOf[Map[_, _]] || tpe <:< typeOf[ByteString]) +// +// private[this] def isMap(tpe: Type): Boolean = tpe <:< typeOf[Map[_, _]] || tpe <:< typeOf[java.util.Map[_, _]] +// +// private[this] def getBuilderType(protoType: Type): Type = { +// protoType.companion.member(TermName("newBuilder")).asTerm.alternatives.head.asMethod.returnType +// } +// +// trait Processor { +// +// def caseClassType: Type +// def protoType: Type +// +// def scalaTreeType: Type +// def protoValueType: Type +// +// def resolvedCaseClassFieldType: Type = resolveFieldType(caseClassType, scalaTreeType) +// +// def tree: Option[Tree] +// } +// +// // Convert expr (`scalaTree` in this class) to protobuf value +// class ToProtoProcessor( +// scalaTree: Tree, +// override val scalaTreeType: Type, +// override val caseClassType: Type, +// override val protoType: Type, +// override val protoFieldName: String +// ) extends ProtoFieldAnalyst { +// +// private[this] def toProto(t1: Type, t2: Type): Tree = { +// if (t1 <:< t2) { +// scalaTree +// } else { +// q"${implicitlyProtoable(t1, t2)}.toProto($scalaTree)" +// } +// } +// +// override def protoValueType: Type = protoValueSetterType +// +// def optTree(optFieldType: Type): c.universe.Tree = { +// val tree = if (isIterable(protoValueType)) { +// seqTree(optFieldType) +// } else if (isMap(protoValueType)) { +// mapTree(optFieldType) +// } else { +// defaultTree(optFieldType) +// } +// If(q"$scalaTree.isDefined", tree, EmptyTree) +// } +// +// def seqTree(iterableType: Type): c.universe.Tree = { +// val listType = builderType.member(addAllMethodName).asMethod.paramLists.head.head.typeSignature +// val valueTree = toProto(iterableType, listType) +// q"${builderIdent}.$addAllMethodName($valueTree)" +// } +// +// def mapTree(mapType: Type): c.universe.Tree = { +// val putAllMapType = builderType.member(putAllMethodName).asMethod.paramLists.head.head.typeSignature +// val valueTree = toProto(mapType, putAllMapType) +// q"${builderIdent}.$putAllMethodName($valueTree)" +// } +// +// def defaultTree(fieldType: Type): c.universe.Tree = { +// val valueTree = toProto(fieldType, protoValueType) +// q"${builderIdent}.$setField(${valueTree})" +// } +// +// override def tree: Option[Tree] = { +// if (protoValueType == NoType) { +// None +// } else { +// val _tree = if (isOption(scalaTreeType)) { +// optTree(resolvedCaseClassFieldType) +// } else if (isIterable(protoValueType)) { +// seqTree(resolvedCaseClassFieldType) +// } else if (isMap(protoValueType)) { +// mapTree(resolvedCaseClassFieldType) +// } else { +// defaultTree(resolvedCaseClassFieldType) +// } +// +// if (scalaTreeType <:< typeOf[AnyRef]) { +// val notNullCondition = q"$scalaTree ne null" +// Some(If(notNullCondition, _tree, EmptyTree)) +// } else { +// Some(_tree) +// } +// } +// } +// } +// +// // Convert expr (`protoValueTree` in this class) to case class filed value +// case class ToScalaProcessor(caseClassSelector: MethodSymbol, protoValueTree: Tree, protoValueType: Type, caseClassType: Type, protoType: Type) +// extends AbstractToScalaProcessor +// +// trait AbstractToScalaProcessor extends Processor { +// +// def caseClassSelector: MethodSymbol +// +// def protoValueTree: Tree +// +// override def scalaTreeType: Type = caseClassSelector.returnType +// +// protected def toScala(t1: Type, t2: Type, value: Tree) = { +// if (t2 <:< t1) { +// value +// } else { +// q"${implicitlyScalable(t1, t2)}.toScala($value)" +// } +// } +// +// def optTree(optType: Type): c.universe.Tree = defaultTree(optType) +// +// def defaultTree(fieldType: Type): Tree = { +// q"$caseClassSelector = ${toScala(fieldType, protoValueType, protoValueTree)}" +// } +// +// override def tree: Option[Tree] = +// if (protoValueType == NoType) { +// None +// } else { +// if (isOption(scalaTreeType)) { +// Some(optTree(resolvedCaseClassFieldType)) +// } else { +// Some(defaultTree(resolvedCaseClassFieldType)) +// } +// } +// } +// +// // Contain some methods and vals to analyze Protobuf fields +// trait ProtoFieldAnalyst extends Processor { +// def protoFieldName: String +// +// val builderType = getBuilderType(protoType) +// +// def addAllMethodName: TermName = TermName(s"addAll$protoFieldName") +// def putAllMethodName: TermName = TermName(s"putAll$protoFieldName") +// +// def addField: TermName = TermName(s"add$protoFieldName") +// def putField: TermName = TermName(s"put$protoFieldName") +// def setField: TermName = TermName(s"set$protoFieldName") +// def getField: TermName = TermName(s"get$protoFieldName") +// def getMapField: TermName = TermName(s"get${protoFieldName}Map") +// def getListField: TermName = TermName(s"get${protoFieldName}List") +// def builderSetter: TermName = if (isIterable(scalaTreeType)) addAllMethodName else setField +// +// val protoValueTree: Tree = { +// if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 +// q"$protoIdent.$getListField" +// } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map +// q"$protoIdent.$getMapField" +// } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 +// q"$protoIdent.$getField" +// } else { +// q"" +// } +// } +// +// lazy val protoValueSetterType: Type = { +// val pbBuilderType = typeOf[com.google.protobuf.Message.Builder] +// val setterOpt = if (builderType.member(addField) != NoSymbol) { +// Some(builderType.member(addAllMethodName)) +// } else if (builderType.member(putField) != NoSymbol) { +// Some(builderType.member(putAllMethodName)) +// } else if (builderType.member(setField) != NoSymbol) { +// Some(builderType.member(setField)) +// } else { +// None +// } +// setterOpt.fold(NoType)(_.alternatives.map(_.asMethod.paramLists.head.head.typeSignature).find(t ⇒ !(t <:< pbBuilderType)).get) +// } +// +// lazy val protoValueGetterType: Type = { +// if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 +// protoType.member(getListField).typeSignature.resultType +// } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map +// protoType.member(getMapField).typeSignature.resultType +// } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 +// protoType.member(getField).typeSignature.resultType +// } else { +// NoType +// } +// } +// +// } +// +// // Convert scala clase class field value to protobuf value +// case class ToProtoFieldProcessor(accessor: MethodSymbol, override val caseClassType: Type, override val protoType: Type) +// extends ToProtoProcessor(q"$entityIdent.$accessor", accessor.returnType, caseClassType, protoType, accessor.name.toString.capitalize) +// +// // Convert protobuf value to case class filed value +// case class ToScalaFieldProcessor(accessor: MethodSymbol, override val caseClassType: Type, override val protoType: Type) +// extends AbstractToScalaProcessor +// with ProtoFieldAnalyst { +// +// override def caseClassSelector: MethodSymbol = accessor +// +// override def protoFieldName: String = accessor.name.toString.capitalize +// +// override def protoValueType: Type = protoValueGetterType +// +// override def optTree(optType: Type): c.universe.Tree = { +// val hasProtoField = TermName(s"has$protoFieldName") +// if (protoType.member(hasProtoField) == NoSymbol) { +// defaultTree(optType) +// } else { +// q"$caseClassSelector = if (${protoIdent}.$hasProtoField) ${toScala(optType, protoValueType, protoValueTree)} else None" +// } +// } +// } +// +// private[this] def resolveFieldType(entityType: Type, originType: Type): Type = +// originType.asSeenFrom(entityType, entityType.typeSymbol.asClass) +// +// private[this] def resolveType[T: WeakTypeTag]: Type = { +// val tpe = weakTypeOf[T] +// tpe.dealias +// } +// +// private[this] def getCaseAccessors(caseClassType: Type): Seq[MethodSymbol] = { +// caseClassType.members.collect { case m: MethodSymbol if m.isCaseAccessor ⇒ m }.toSeq.reverse +// } +// +// private[this] def defaultProtoableFieldConvertTrees(caseClassType: Type, protoType: Type): Map[String, Tree] = { +// getCaseAccessors(caseClassType).flatMap { a ⇒ +// val p = ToProtoFieldProcessor(a, caseClassType, protoType) +// p.tree.map(p.protoFieldName -> _) +// }.toMap +// } +// +// private[this] def protoableBody(caseClassType: Type, protoType: Type, protoableFieldConvertTrees: Iterable[Tree]): Tree = { +// q""" +// override def toProto(${entityIdent.name.toTermName}: $caseClassType): $protoType = { +// val ${builderIdent} = ${protoType.typeSymbol.companion}.newBuilder() +// ..$protoableFieldConvertTrees +// $builderIdent.build() +// } +// """ +// } +// +// private def defalutScalableFieldConvertTrees(caseClassType: Type, protoType: Type): Map[String, Tree] = { +// getCaseAccessors(caseClassType).flatMap(accessor ⇒ ToScalaFieldProcessor(accessor, caseClassType, protoType).tree.map(accessor.name.toString -> _)).toMap +// } +// +// private def scalableBody(caseClassType: Type, protoType: Type, scalableFieldConvertTrees: Iterable[Tree]): Tree = { +// q""" +// override def toScala(${protoIdent.name.toTermName} :$protoType): $caseClassType = { +// new ${caseClassType.typeSymbol} ( +// ..${scalableFieldConvertTrees} +// ) +// } +// """ +// } +// +// def scalasImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { +// val caseClassType = resolveType[T] +// val protoType = resolveType[M] +// val scalableFieldConvertTrees = defalutScalableFieldConvertTrees(caseClassType, protoType).values +// scalasImpl(caseClassType, protoType, scalableFieldConvertTrees, Nil) +// } +// +// private[this] def scalasImpl(caseClassType: Type, protoType: Type, scalableFieldConvertTrees: Iterable[Tree], perTrees: Iterable[Tree]): Tree = { +// q""" +// ..$perTrees +// new $packageName.Scalable[$caseClassType, $protoType] { ${scalableBody(caseClassType, protoType, scalableFieldConvertTrees)} } +// """ +// } +// +// def protosImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { +// val caseClassType = resolveType[T] +// val protoType = resolveType[M] +// protosImpl(caseClassType, protoType, defaultProtoableFieldConvertTrees(caseClassType, protoType).values, Nil) +// } +// +// private[this] def protosImpl(caseClassType: Type, protoType: Type, protoableFieldConvertTrees: Iterable[Tree], perTrees: Iterable[Tree]): Tree = { +// q""" +// ..$perTrees +// new $packageName.Protoable[$caseClassType,$protoType] { ${protoableBody(caseClassType, protoType, protoableFieldConvertTrees)} } +// """ +// } +// +// def convertsImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { +// val caseClassType = resolveType[T] +// val protoType = resolveType[M] +// q""" +// new $packageName.ProtoScalable[${resolveType[T]}, ${resolveType[M]}] { +// ${scalableBody(caseClassType, protoType, defalutScalableFieldConvertTrees(caseClassType, protoType).values)} +// ${protoableBody(caseClassType, protoType, defaultProtoableFieldConvertTrees(caseClassType, protoType).values)} +// } +// """ +// } +// +// def buildProtoableImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { +// val caseClassType = resolveType[T] +// val protoType = resolveType[M] +// val customTrees = MacroCache.builderFunctionTrees.getOrElse(getBuilderId(), mutable.Map.empty) +// val (fixedCustomTrees, preTrees) = customTrees.map { +// case (key, tree) ⇒ +// tree match { // setField +// case buildFunction: Function ⇒ +// val functionName = TermName("builderFunction$" + MacroCache.getIdentityId) +// val fromType = buildFunction.tpe.typeArgs.last // buildFunction 的返回值 +// val buildExpr = new ToProtoProcessor(q"$functionName($entityIdent)", fromType, caseClassType, protoType, key).tree.get +// (key -> buildExpr) -> q"val $functionName = $buildFunction" +// case value: Tree ⇒ // setFieldValue +// val identity = TermName("identity$" + MacroCache.getIdentityId) +// val buildExpr = new ToProtoProcessor(q"$identity", value.tpe, caseClassType, protoType, key).tree.get +// (key -> buildExpr) -> q"val $identity = $value" +// } +// }.unzip +// val protoableFieldConvertTrees = (defaultProtoableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values +// protosImpl(caseClassType, protoType, protoableFieldConvertTrees, preTrees) +// } +// +// def buildScalableImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { +// val caseClassType = resolveType[T] +// val protoType = resolveType[M] +// val builderId = getBuilderId() +// val customTrees = MacroCache.builderFunctionTrees.getOrElse(builderId, mutable.Map.empty) +// val entityType = resolveType[T] +// +// val (fixedCustomTrees, preTrees) = customTrees.map { +// case (key, tree) ⇒ +// val selector = entityType.member(TermName(key)) +// tree match { +// case buildFunction: Function ⇒ // setField +// val functionName = TermName("builderFunction$" + MacroCache.getIdentityId) +// val expr = new ToScalaProcessor(selector.asMethod, q"$functionName($protoIdent)", buildFunction.body.tpe, resolveType[T], resolveType[M]).tree.get +// (key -> expr) -> q"val $functionName = $buildFunction" +// case value: Tree ⇒ // setFieldValue +// val identity = TermName("identity$" + MacroCache.getIdentityId) +// val expr = new ToScalaProcessor(selector.asMethod, q"$identity", value.tpe, resolveType[T], resolveType[M]).tree.get +// (key -> expr) -> q"val $identity = $value" +// } +// }.unzip +// +// val scalableFieldConvertTrees = (defalutScalableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values +// scalasImpl(caseClassType, protoType, scalableFieldConvertTrees, preTrees) +// } +// +// def setScalaFieldImpl[T: WeakTypeTag, M: WeakTypeTag, TF: WeakTypeTag, MF: WeakTypeTag](scalaField: Tree, value: Tree): Tree = { +// val Function(_, Select(_, termName)) = scalaField +// val builderId = getBuilderId() +// MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(termName.toString, value) +// q"new ${c.prefix.actualType}" +// } +// +// def setProtoFieldImpl[T: WeakTypeTag, M: WeakTypeTag, TF: WeakTypeTag, MF: WeakTypeTag](protoFieldSelector: Tree, value: Tree): Tree = { +// val getter = "^get(\\w+)$".r +// val listGetter = "^get(\\w+)List$".r +// val mapGetter = "^get(\\w+)Map$".r +// val setter = protoFieldSelector.find { +// case _: Select ⇒ true +// case _: Tree ⇒ false +// } match { +// case Some(select: Select) ⇒ +// select.name.toString match { +// case mapGetter(n) if select.tpe.resultType <:< typeOf[java.util.Map[_, _]] ⇒ n +// case listGetter(n) if select.tpe.resultType <:< typeOf[java.util.List[_]] ⇒ n +// case getter(n) ⇒ n +// case _ ⇒ c.abort(protoFieldSelector.pos, "Invalid setter") +// } +// case _ ⇒ c.abort(protoFieldSelector.pos, "Invalid setter") +// } +// val builderId = getBuilderId() +// MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(setter, value) +// q"new ${c.prefix.actualType}" +// } +// +// val annoBuilderPrefix = "AnonBuilder$" +// +// def scalableBuilderApply[T: WeakTypeTag, M: WeakTypeTag]: Tree = { +// val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) +// q""" +// class $className extends $packageName.ScalableBuilder[${resolveType[T]}, ${resolveType[M]}] +// new $className +// """ +// } +// +// def protoableBuilderApply[T: WeakTypeTag, M: WeakTypeTag]: Tree = { +// val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) +// q""" +// class $className extends $packageName.ProtoableBuilder[${resolveType[T]}, ${resolveType[M]}] +// new $className +// """ +// } +// +// private[this] def getBuilderId() = { +// c.prefix.actualType.toString.replace(annoBuilderPrefix, "").toInt +// } + +//} diff --git a/pbconverts/src/main/scala-3.00/pbconverts/ScalableImplicits.scala b/pbconverts/src/main/scala-3.00/pbconverts/ScalableImplicits.scala new file mode 100644 index 0000000..febbf52 --- /dev/null +++ b/pbconverts/src/main/scala-3.00/pbconverts/ScalableImplicits.scala @@ -0,0 +1,44 @@ +package pbconverts + +import scala.collection.BuildFrom +import scala.collection.JavaConverters._ +import scala.reflect.ClassTag + +trait ScalableImplicits { + + // java.lang.Iterable[M] => That[T] + implicit def iterableScalable[That[_], T, M](implicit + scalable: Scalable[T, M], + bf: BuildFrom[Seq[_], T, That[T]] + ): Scalable[That[T], java.lang.Iterable[M]] = + Scalable { proto ⇒ + bf.fromSpecific(Seq.empty)(proto.asScala.iterator.map(scalable.toScala)) + } + + implicit def iterableScalable2[That[T], T](implicit bf: BuildFrom[Seq[T], T, That[T]]): Scalable[That[T], java.lang.Iterable[T]] = + Scalable { proto ⇒ + bf.fromSpecific(Seq.empty)(proto.asScala) + } + + // // Repr[M] => That[T] + implicit def iterableSelfScalable[That, Repr <: Iterable[M], T, M](implicit + scalable: Scalable[T, M], + bf: BuildFrom[Iterable[_], T, That] + ): Scalable[That, Repr] = { proto ⇒ + bf.newBuilder(proto.map(scalable.toScala)).result() + } + + implicit def mapScalable4[K1, K2, V1, V2](implicit kScalable: Scalable[K1, K2], vScalable: Scalable[V1, V2]): Scalable[Map[K1, V1], java.util.Map[K2, V2]] = + Scalable[Map[K1, V1], java.util.Map[K2, V2]] { m ⇒ + m.asScala.map { case (k, v) ⇒ kScalable.toScala(k) -> vScalable.toScala(v) }.toMap + } + + implicit def mapScalable3[K, V1, V2](implicit vScalable: Scalable[V1, V2]): Scalable[Map[K, V1], java.util.Map[K, V2]] = + Scalable[Map[K, V1], java.util.Map[K, V2]] { m ⇒ m.asScala.map { case (k, v) ⇒ k -> vScalable.toScala(v) }.toMap } + + implicit def mapScalable2[K1, K2, V](implicit kScalable: Scalable[K1, K2]): Scalable[Map[K1, V], java.util.Map[K2, V]] = + Scalable[Map[K1, V], java.util.Map[K2, V]] { m ⇒ m.asScala.map { case (k, v) ⇒ kScalable.toScala(k) -> v }.toMap } + + implicit def mapScalable1[K, V]: Scalable[Map[K, V], java.util.Map[K, V]] = + Scalable[Map[K, V], java.util.Map[K, V]] { m ⇒ m.asScala.toMap } +} diff --git a/pbconverts/src/main/scala/pbconverts/ProtoScalable.scala b/pbconverts/src/main/scala/pbconverts/ProtoScalable.scala index 6912658..1b77f63 100644 --- a/pbconverts/src/main/scala/pbconverts/ProtoScalable.scala +++ b/pbconverts/src/main/scala/pbconverts/ProtoScalable.scala @@ -4,7 +4,7 @@ trait ProtoScalable[T, M] extends Protoable[T, M] with Scalable[T, M] object ProtoScalable { - def apply[T <: Product, M]: ProtoScalable[T, M] = macro ProtoScalableMacro.convertsImpl[T, M] + def apply[T <: Product, M]: ProtoScalable[T, M] = ??? // macro ProtoScalableMacro.convertsImpl[T, M] def apply[T, M](toProtoFun: T ⇒ M, toScalaFun: M ⇒ T): ProtoScalable[T, M] = new ProtoScalable[T, M] { diff --git a/pbconverts/src/main/scala/pbconverts/Protoable.scala b/pbconverts/src/main/scala/pbconverts/Protoable.scala index 68e238f..18f2599 100644 --- a/pbconverts/src/main/scala/pbconverts/Protoable.scala +++ b/pbconverts/src/main/scala/pbconverts/Protoable.scala @@ -12,30 +12,37 @@ trait Protoable[-T, +M] { object Protoable { - def apply[T <: Product, M]: Protoable[T, M] = macro ProtoScalableMacro.protosImpl[T, M] + def apply[T <: Product, M]: Protoable[T, M] = ??? // macro ProtoScalableMacro.protosImpl[T, M] def apply[T, M](f: T ⇒ M): Protoable[T, M] = new Protoable[T, M] { override def toProto(entity: T): M = f(entity) } - implicit val javaDoubleProtoable = Protoable[Double, java.lang.Double](_.toDouble) - implicit val javaFloatProtoable = Protoable[Float, java.lang.Float](_.toFloat) - implicit val javaIntergerProtoable = Protoable[Int, java.lang.Integer](_.toInt) - implicit val javaLongProtoable = Protoable[Long, java.lang.Long](_.toLong) - implicit val javaCharacterProtoable = Protoable[Char, java.lang.Character](_.toChar) - implicit val javaByteProtoable = Protoable[Byte, java.lang.Byte](_.toByte) - - implicit val stringValueProtoable = Protoable[String, StringValue](StringValue.of) - implicit val doubleValueProtoable = Protoable[Double, DoubleValue](DoubleValue.of) - implicit val floatValueProtoable = Protoable[Float, FloatValue](FloatValue.of) - implicit val int32ValueProtoable = Protoable[Int, Int32Value](Int32Value.of) - implicit val boolValueProtoable = Protoable[Boolean, BoolValue](BoolValue.of) - implicit val int64ValueProtoable = Protoable[Long, Int64Value](Int64Value.of) - - implicit val zonedDateTimeProtoable = Protoable[ZonedDateTime, Timestamp] { entity ⇒ - Timestamp.newBuilder().setSeconds(entity.toEpochSecond).setNanos(entity.getNano).build() - } + implicit val javaDoubleProtoable: Protoable[Double, java.lang.Double] = Protoable[Double, java.lang.Double](_.toDouble) + implicit val javaFloatProtoable: Protoable[Float, java.lang.Float] = Protoable[Float, java.lang.Float](_.toFloat) + implicit val javaIntergerProtoable: Protoable[Int, java.lang.Integer] = Protoable[Int, java.lang.Integer](_.toInt) + implicit val javaLongProtoable: Protoable[Long, java.lang.Long] = Protoable[Long, java.lang.Long](_.toLong) +// implicit val javaCharacterProtoable = Protoable[Char, java.lang.Character](_.toChar) +// implicit val javaByteProtoable = Protoable[Byte, java.lang.Byte](_.toByte) +// +// implicit val stringValueProtoable = Protoable[String, StringValue](StringValue.of) +// implicit val doubleValueProtoable = Protoable[Double, DoubleValue](DoubleValue.of) +// implicit val floatValueProtoable = Protoable[Float, FloatValue](FloatValue.of) +// implicit val int32ValueProtoable = Protoable[Int, Int32Value](Int32Value.of) +// implicit val boolValueProtoable = Protoable[Boolean, BoolValue](BoolValue.of) +// implicit val int64ValueProtoable = Protoable[Long, Int64Value](Int64Value.of) + +// implicit val stringValueProtoable = Protoable[String, StringValue](StringValue.of) +// implicit val doubleValueProtoable = Protoable[Double, DoubleValue](DoubleValue.of) +// implicit val floatValueProtoable = Protoable[Float, FloatValue](FloatValue.of) +// implicit val int32ValueProtoable = Protoable[Int, Int32Value](Int32Value.of) +// implicit val boolValueProtoable = Protoable[Boolean, BoolValue](BoolValue.of) +// implicit val int64ValueProtoable = Protoable[Long, Int64Value](Int64Value.of) +// +// implicit val zonedDateTimeProtoable = Protoable[ZonedDateTime, Timestamp] { entity ⇒ +// Timestamp.newBuilder().setSeconds(entity.toEpochSecond).setNanos(entity.getNano).build() +// } implicit def iterableProtoable[T, M](implicit protoable: Protoable[T, M]): Protoable[scala.Iterable[T], java.util.List[M]] = Protoable[scala.Iterable[T], java.util.List[M]] { entity ⇒ @@ -54,12 +61,12 @@ object Protoable { } implicit def optProtoable[F, Target <: Any](implicit protoable: Protoable[F, Target]): Protoable[Option[F], Target] = - Protoable[Option[F], Target] { entity: Option[F] ⇒ + Protoable[Option[F], Target] { (entity: Option[F]) ⇒ entity.map(protoable.toProto).getOrElse(None.orNull.asInstanceOf[Target]) } implicit def optProtoable2[T]: Protoable[Option[T], T] = - Protoable[Option[T], T] { opt: Option[T] => opt.getOrElse(None.orNull.asInstanceOf[T]) } + Protoable[Option[T], T] { (opt: Option[T]) => opt.getOrElse(None.orNull.asInstanceOf[T]) } implicit def mapProtoable1[K, V]: Protoable[Map[K, V], java.util.Map[K, V]] = Protoable[Map[K, V], java.util.Map[K, V]] { m ⇒ m.asJava } diff --git a/pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala b/pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala index 3742797..2af409d 100644 --- a/pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala +++ b/pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala @@ -4,13 +4,13 @@ import com.google.protobuf.Message class ProtoableBuilder[T, M <: Message]() { - def setField[TF, MF](protoFieldSelector: M ⇒ MF, value: T ⇒ TF): this.type = macro ProtoScalableMacro.setProtoFieldImpl[T, M, TF, MF] + def setField[TF, MF](protoFieldSelector: M ⇒ MF, value: T ⇒ TF): this.type = ??? //macro ProtoScalableMacro.setProtoFieldImpl[T, M, TF, MF] - def setFieldValue[TF, MF](protoFieldSelector: M ⇒ MF, value: TF): this.type = macro ProtoScalableMacro.setProtoFieldImpl[T, M, TF, MF] + def setFieldValue[TF, MF](protoFieldSelector: M ⇒ MF, value: TF): this.type = ??? //macro ProtoScalableMacro.setProtoFieldImpl[T, M, TF, MF] - def build: Protoable[T, M] = macro ProtoScalableMacro.buildProtoableImpl[T, M] + def build: Protoable[T, M] = ??? //macro ProtoScalableMacro.buildProtoableImpl[T, M] } object ProtoableBuilder { - def apply[T, M <: Message]: ProtoableBuilder[T, M] = macro ProtoScalableMacro.protoableBuilderApply[T, M] + def apply[T, M <: Message]: ProtoableBuilder[T, M] = ??? //macro ProtoScalableMacro.protoableBuilderApply[T, M] } diff --git a/pbconverts/src/main/scala/pbconverts/Scalable.scala b/pbconverts/src/main/scala/pbconverts/Scalable.scala index e6bf054..987edaa 100644 --- a/pbconverts/src/main/scala/pbconverts/Scalable.scala +++ b/pbconverts/src/main/scala/pbconverts/Scalable.scala @@ -13,28 +13,30 @@ trait Scalable[+T, -M] { object Scalable extends ScalableImplicits { - def apply[T <: Product, M]: Scalable[T, M] = macro ProtoScalableMacro.scalasImpl[T, M] + def apply[T <: Product, M]: Scalable[T, M] = ??? // macro ProtoScalableMacro.scalasImpl[T, M] def apply[T, M](convert: M ⇒ T): Scalable[T, M] = new Scalable[T, M] { override def toScala(proto: M): T = convert(proto) } - implicit val javaIntegerScalable = Scalable[Int, java.lang.Integer](_.toInt) - implicit val javaLongScalable = Scalable[Long, java.lang.Long](_.toLong) - implicit val javaDoubleScalable = Scalable[Double, java.lang.Double](_.toDouble) - implicit val javaFloatScalable = Scalable[Float, java.lang.Float](_.toFloat) - implicit val javaCharacterScalable = Scalable[Char, java.lang.Character](_.toChar) - implicit val javaByteScalable = Scalable[Byte, java.lang.Byte](_.toByte) - - implicit val stringValueScalable = Scalable[String, StringValue](_.getValue) - implicit val int32ValueScalable = Scalable[Int, Int32Value](_.getValue) - implicit val int64ValueScalable = Scalable[Long, Int64Value](_.getValue) - implicit val doubleValueScalable = Scalable[Double, DoubleValue](_.getValue) - implicit val floatValueScalable = Scalable[Float, FloatValue](_.getValue) - implicit val boolValueScalable = Scalable[Boolean, BoolValue](_.getValue) - - implicit val zonedDateTimeProtoable = Scalable[ZonedDateTime, Timestamp] { proto ⇒ + given Int = 1 + + given Scalable[Int, java.lang.Integer] = Scalable[Int, java.lang.Integer].apply(_.toInt) +// given javaLongScalable: Scalable[Long, java.lang.Long] with Scalable[Long, java.lang.Long](_.toLong) +// given javaDoubleScalable:Scalable[Double, java.lang.Double] with Scalable[Double, java.lang.Double](_.toDouble) +// given javaFloatScalable:Scalable[Float, java.lang.Float] with Scalable[Float, java.lang.Float](_.toFloat) +// given javaCharacterScalable:Scalable[Char, java.lang.Character] with Scalable[Char, java.lang.Character](_.toChar) +// given javaByteScalable:Scalable[Byte, java.lang.Byte] with Scalable[Byte, java.lang.Byte](_.toByte) + +// given Scalable [String, StringValue] = Scalable [String, StringValue] (_.getValue) +// given Scalable [Int, Int32Value] = Scalable [Int, Int32Value] (_.getValue) +// given Scalable [Long, Int64Value] = Scalable [Long, Int64Value] (_.getValue) +// given Scalable [Double, DoubleValue] = Scalable [Double, DoubleValue] (_.getValue) +// given Scalable [Float, FloatValue] = Scalable [Float, FloatValue] (_.getValue) +// given Scalable [Boolean, BoolValue] = Scalable [Boolean, BoolValue] (_.getValue) + + implicit val zonedDateTimeProtoable: Scalable[ZonedDateTime, Timestamp] = Scalable[ZonedDateTime, Timestamp] { proto ⇒ Instant.ofEpochSecond(proto.getSeconds, proto.getNanos).atZone(ZoneId.systemDefault()) } diff --git a/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala b/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala index 1d8565c..8a9003b 100644 --- a/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala +++ b/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala @@ -2,13 +2,13 @@ package pbconverts class ScalableBuilder[+T, M]() { - def setField[TF, MF](scalaField: T ⇒ TF, value: M ⇒ MF): ScalableBuilder[T, M] = macro ProtoScalableMacro.setScalaFieldImpl[T, M, TF, MF] + def setField[TF, MF](scalaField: T ⇒ TF, value: M ⇒ MF): ScalableBuilder[T, M] = ??? //macro ProtoScalableMacro.setScalaFieldImpl[T, M, TF, MF] - def setFieldValue[TF, MF](scalaField: T ⇒ TF, value: MF): ScalableBuilder[T, M] = macro ProtoScalableMacro.setScalaFieldImpl[T, M, TF, MF] + def setFieldValue[TF, MF](scalaField: T ⇒ TF, value: MF): ScalableBuilder[T, M] = ??? //macro ProtoScalableMacro.setScalaFieldImpl[T, M, TF, MF] - def build: Scalable[T, M] = macro ProtoScalableMacro.buildScalableImpl[T, M] + def build: Scalable[T, M] = ??? // macro ProtoScalableMacro.buildScalableImpl[T, M] } object ScalableBuilder { - def apply[T, M]: ScalableBuilder[T, M] = macro ProtoScalableMacro.scalableBuilderApply[T, M] + def apply[T, M]: ScalableBuilder[T, M] = ??? //macro ProtoScalableMacro.scalableBuilderApply[T, M] } diff --git a/pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala b/pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala new file mode 100644 index 0000000..febbf52 --- /dev/null +++ b/pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala @@ -0,0 +1,44 @@ +package pbconverts + +import scala.collection.BuildFrom +import scala.collection.JavaConverters._ +import scala.reflect.ClassTag + +trait ScalableImplicits { + + // java.lang.Iterable[M] => That[T] + implicit def iterableScalable[That[_], T, M](implicit + scalable: Scalable[T, M], + bf: BuildFrom[Seq[_], T, That[T]] + ): Scalable[That[T], java.lang.Iterable[M]] = + Scalable { proto ⇒ + bf.fromSpecific(Seq.empty)(proto.asScala.iterator.map(scalable.toScala)) + } + + implicit def iterableScalable2[That[T], T](implicit bf: BuildFrom[Seq[T], T, That[T]]): Scalable[That[T], java.lang.Iterable[T]] = + Scalable { proto ⇒ + bf.fromSpecific(Seq.empty)(proto.asScala) + } + + // // Repr[M] => That[T] + implicit def iterableSelfScalable[That, Repr <: Iterable[M], T, M](implicit + scalable: Scalable[T, M], + bf: BuildFrom[Iterable[_], T, That] + ): Scalable[That, Repr] = { proto ⇒ + bf.newBuilder(proto.map(scalable.toScala)).result() + } + + implicit def mapScalable4[K1, K2, V1, V2](implicit kScalable: Scalable[K1, K2], vScalable: Scalable[V1, V2]): Scalable[Map[K1, V1], java.util.Map[K2, V2]] = + Scalable[Map[K1, V1], java.util.Map[K2, V2]] { m ⇒ + m.asScala.map { case (k, v) ⇒ kScalable.toScala(k) -> vScalable.toScala(v) }.toMap + } + + implicit def mapScalable3[K, V1, V2](implicit vScalable: Scalable[V1, V2]): Scalable[Map[K, V1], java.util.Map[K, V2]] = + Scalable[Map[K, V1], java.util.Map[K, V2]] { m ⇒ m.asScala.map { case (k, v) ⇒ k -> vScalable.toScala(v) }.toMap } + + implicit def mapScalable2[K1, K2, V](implicit kScalable: Scalable[K1, K2]): Scalable[Map[K1, V], java.util.Map[K2, V]] = + Scalable[Map[K1, V], java.util.Map[K2, V]] { m ⇒ m.asScala.map { case (k, v) ⇒ kScalable.toScala(k) -> v }.toMap } + + implicit def mapScalable1[K, V]: Scalable[Map[K, V], java.util.Map[K, V]] = + Scalable[Map[K, V], java.util.Map[K, V]] { m ⇒ m.asScala.toMap } +} diff --git a/project/build.properties b/project/build.properties index d18a12e..1129869 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1 +1 @@ -sbt.version = 1.4.7 +sbt.version = 1.5.0-RC2 From 08db549b09b96507caf429b9485c16e4e43298b1 Mon Sep 17 00:00:00 2001 From: changvvb Date: Mon, 19 Apr 2021 10:12:33 +0800 Subject: [PATCH 02/17] wip --- build.sbt | 2 +- .../scala/pbconverts/ProtoScalableMacro.scala | 131 +- .../src/main/scala/pbconverts/Converter.scala | 4 +- .../main/scala/pbconverts/MacroCache.scala | 13 + .../scala/pbconverts/ProtoScalableMacro.scala | 494 ++ .../src/main/scala/pbconverts/Protoable.scala | 73 +- .../src/main/scala/pbconverts/Scalable.scala | 43 +- .../scala/pbconverts/ScalableImplicits.scala | 22 +- .../src/test/protobuf/conversion_test.proto | 100 +- .../src/test/resources/MessageWithType.java | 1 + .../MessageWithTypeSpec.scala | 0 pbconverts/src/test/resources/Person.java | 1 + .../ProtoableBuilderSpec.scala | 0 .../ProtoableSpec.scala | 0 .../ScalableBuilderSpec.scala | 0 .../ScalableSpec.scala | 0 .../test/scala/pbconverts/ConversionTest.java | 7492 +++++++++++++++++ .../scala/pbconverts/MessageWithType.scala | 3 - .../src/test/scala/pbconverts/Person.scala | 11 - .../test/scala/pbconverts/TestMessage.scala | 148 +- 20 files changed, 8264 insertions(+), 274 deletions(-) create mode 100644 pbconverts/src/main/scala/pbconverts/MacroCache.scala create mode 100644 pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala create mode 100644 pbconverts/src/test/resources/MessageWithType.java rename pbconverts/src/test/{scala/pbconverts => resources}/MessageWithTypeSpec.scala (100%) create mode 100644 pbconverts/src/test/resources/Person.java rename pbconverts/src/test/{scala/pbconverts => resources}/ProtoableBuilderSpec.scala (100%) rename pbconverts/src/test/{scala/pbconverts => resources}/ProtoableSpec.scala (100%) rename pbconverts/src/test/{scala/pbconverts => resources}/ScalableBuilderSpec.scala (100%) rename pbconverts/src/test/{scala/pbconverts => resources}/ScalableSpec.scala (100%) create mode 100644 pbconverts/src/test/scala/pbconverts/ConversionTest.java delete mode 100644 pbconverts/src/test/scala/pbconverts/MessageWithType.scala delete mode 100644 pbconverts/src/test/scala/pbconverts/Person.scala diff --git a/build.sbt b/build.sbt index b2876d2..bbb0d41 100644 --- a/build.sbt +++ b/build.sbt @@ -29,7 +29,7 @@ lazy val root = project.in(file(".")).withId("root") .aggregate(`scala-protobuf-java`, `scala-protobuf-java-macro`) .settings(publishArtifact := false) -scalafmtOnCompile in ThisBuild := true +//scalafmtOnCompile in ThisBuild := true // publish diff --git a/pbconverts-macro/src/main/scala/pbconverts/ProtoScalableMacro.scala b/pbconverts-macro/src/main/scala/pbconverts/ProtoScalableMacro.scala index 289bd69..cfee82e 100644 --- a/pbconverts-macro/src/main/scala/pbconverts/ProtoScalableMacro.scala +++ b/pbconverts-macro/src/main/scala/pbconverts/ProtoScalableMacro.scala @@ -1,14 +1,15 @@ -package pbconverts - -import com.google.protobuf.ByteString - -import scala.collection.mutable +//package pbconverts +// +//import com.google.protobuf.ByteString +// +//import scala.collection.mutable //import scala.reflect.macros.whitebox - -// scalastyle:off number.of.methods -//class ProtoScalableMacro(val c: whitebox.Context) { -// import c.universe._ - +//import scala.quoted +//import _root_.quoted.Expr +// +//// scalastyle:off number.of.methods +//object ProtoScalableMacro { +// // private[this] def packageName: Tree = q"_root_.pbconverts" // private[this] def builderIdent = Ident(TermName("builder")) // private[this] def entityIdent = Ident(TermName("entity")) @@ -158,53 +159,56 @@ import scala.collection.mutable // // val builderType = getBuilderType(protoType) // -// def addAllMethodName: TermName = TermName(s"addAll$protoFieldName") -// def putAllMethodName: TermName = TermName(s"putAll$protoFieldName") -// -// def addField: TermName = TermName(s"add$protoFieldName") -// def putField: TermName = TermName(s"put$protoFieldName") -// def setField: TermName = TermName(s"set$protoFieldName") -// def getField: TermName = TermName(s"get$protoFieldName") -// def getMapField: TermName = TermName(s"get${protoFieldName}Map") -// def getListField: TermName = TermName(s"get${protoFieldName}List") -// def builderSetter: TermName = if (isIterable(scalaTreeType)) addAllMethodName else setField +//// def addAllMethodName: TermName = TermName(s"addAll$protoFieldName") +//// def putAllMethodName: TermName = TermName(s"putAll$protoFieldName") +//// +//// def addField: TermName = TermName(s"add$protoFieldName") +//// def putField: TermName = TermName(s"put$protoFieldName") +//// def setField: TermName = TermName(s"set$protoFieldName") +//// def getField: TermName = TermName(s"get$protoFieldName") +//// def getMapField: TermName = TermName(s"get${protoFieldName}Map") +//// def getListField: TermName = TermName(s"get${protoFieldName}List") +//// def builderSetter: TermName = if (isIterable(scalaTreeType)) addAllMethodName else setField // // val protoValueTree: Tree = { -// if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 -// q"$protoIdent.$getListField" -// } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map -// q"$protoIdent.$getMapField" -// } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 -// q"$protoIdent.$getField" -// } else { -// q"" -// } +//// if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 +//// q"$protoIdent.$getListField" +//// } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map +//// q"$protoIdent.$getMapField" +//// } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 +//// q"$protoIdent.$getField" +//// } else { +//// q"" +//// } +// ??? // } // -// lazy val protoValueSetterType: Type = { -// val pbBuilderType = typeOf[com.google.protobuf.Message.Builder] -// val setterOpt = if (builderType.member(addField) != NoSymbol) { -// Some(builderType.member(addAllMethodName)) -// } else if (builderType.member(putField) != NoSymbol) { -// Some(builderType.member(putAllMethodName)) -// } else if (builderType.member(setField) != NoSymbol) { -// Some(builderType.member(setField)) -// } else { -// None -// } -// setterOpt.fold(NoType)(_.alternatives.map(_.asMethod.paramLists.head.head.typeSignature).find(t ⇒ !(t <:< pbBuilderType)).get) +// lazy val protoValueSetterType: TypeRepr = { +//// val pbBuilderType = typeOf[com.google.protobuf.Message.Builder] +//// val setterOpt = if (builderType.member(addField) != NoSymbol) { +//// Some(builderType.member(addAllMethodName)) +//// } else if (builderType.member(putField) != NoSymbol) { +//// Some(builderType.member(putAllMethodName)) +//// } else if (builderType.member(setField) != NoSymbol) { +//// Some(builderType.member(setField)) +//// } else { +//// None +//// } +//// setterOpt.fold(NoType)(_.alternatives.map(_.asMethod.paramLists.head.head.typeSignature).find(t ⇒ !(t <:< pbBuilderType)).get) +// ??? // } // -// lazy val protoValueGetterType: Type = { -// if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 -// protoType.member(getListField).typeSignature.resultType -// } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map -// protoType.member(getMapField).typeSignature.resultType -// } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 -// protoType.member(getField).typeSignature.resultType -// } else { -// NoType -// } +// lazy val protoValueGetterType: TypeRepr = { +//// if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 +//// protoType.member(getListField).typeSignature.resultType +//// } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map +//// protoType.member(getMapField).typeSignature.resultType +//// } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 +//// protoType.member(getField).typeSignature.resultType +//// } else { +//// NoType +//// } +// ??? // } // // } @@ -242,25 +246,26 @@ import scala.collection.mutable // tpe.dealias // } // -// private[this] def getCaseAccessors(caseClassType: Type): Seq[MethodSymbol] = { +// private[this] def getCaseAccessors(caseClassType: TypeRepr): Seq[Symbole] = { // caseClassType.members.collect { case m: MethodSymbol if m.isCaseAccessor ⇒ m }.toSeq.reverse // } // -// private[this] def defaultProtoableFieldConvertTrees(caseClassType: Type, protoType: Type): Map[String, Tree] = { +// private[this] def defaultProtoableFieldConvertTrees(caseClassType: TypeRepr, protoType: TypeRepr): Map[String, Tree] = { // getCaseAccessors(caseClassType).flatMap { a ⇒ // val p = ToProtoFieldProcessor(a, caseClassType, protoType) // p.tree.map(p.protoFieldName -> _) // }.toMap // } // -// private[this] def protoableBody(caseClassType: Type, protoType: Type, protoableFieldConvertTrees: Iterable[Tree]): Tree = { -// q""" -// override def toProto(${entityIdent.name.toTermName}: $caseClassType): $protoType = { -// val ${builderIdent} = ${protoType.typeSymbol.companion}.newBuilder() -// ..$protoableFieldConvertTrees -// $builderIdent.build() -// } -// """ +// private[this] def protoableBody(caseClassType: TypeRepr, protoType: TypeRepr, protoableFieldConvertTrees: Iterable[Tree]): Tree = { +//// q""" +//// override def toProto(${entityIdent.name.toTermName}: $caseClassType): $protoType = { +//// val ${builderIdent} = ${protoType.typeSymbol.companion}.newBuilder() +//// ..$protoableFieldConvertTrees +//// $builderIdent.build() +//// } +//// """ +// ??? // } // // private def defalutScalableFieldConvertTrees(caseClassType: Type, protoType: Type): Map[String, Tree] = { @@ -277,7 +282,7 @@ import scala.collection.mutable // """ // } // -// def scalasImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { +// def scalasImpl[T, M]: Expr[Scalable] = { // val caseClassType = resolveType[T] // val protoType = resolveType[M] // val scalableFieldConvertTrees = defalutScalableFieldConvertTrees(caseClassType, protoType).values @@ -413,5 +418,5 @@ import scala.collection.mutable // private[this] def getBuilderId() = { // c.prefix.actualType.toString.replace(annoBuilderPrefix, "").toInt // } - +// //} diff --git a/pbconverts/src/main/scala/pbconverts/Converter.scala b/pbconverts/src/main/scala/pbconverts/Converter.scala index e27b012..ea35e68 100644 --- a/pbconverts/src/main/scala/pbconverts/Converter.scala +++ b/pbconverts/src/main/scala/pbconverts/Converter.scala @@ -2,8 +2,8 @@ package pbconverts object Converter { - def toProto[T, M](d: T)(implicit protoable: Protoable[T, M]): M = protoable.toProto(d) + def toProto[T, M](d: T)(using protoable: Protoable[T, M]): M = protoable.toProto(d) - def toScala[T, M](m: M)(implicit scalable: Scalable[T, M]): T = scalable.toScala(m) + def toScala[T, M](m: M)(using scalable: Scalable[T, M]): T = scalable.toScala(m) } diff --git a/pbconverts/src/main/scala/pbconverts/MacroCache.scala b/pbconverts/src/main/scala/pbconverts/MacroCache.scala new file mode 100644 index 0000000..14da99b --- /dev/null +++ b/pbconverts/src/main/scala/pbconverts/MacroCache.scala @@ -0,0 +1,13 @@ +package pbconverts + +import scala.collection.mutable + +object MacroCache { + private var builderCount = 0 + private var identityCount = 0 + + def getBuilderId: Int = builderCount.synchronized { builderCount += 1; builderCount } + def getIdentityId: Int = identityCount.synchronized { identityCount += 1; identityCount } + + lazy val builderFunctionTrees: mutable.Map[Int, mutable.Map[String, Any]] = mutable.Map.empty +} diff --git a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala new file mode 100644 index 0000000..86dab71 --- /dev/null +++ b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala @@ -0,0 +1,494 @@ +package pbconverts + +import com.google.protobuf.MessageLite.Builder +import com.google.protobuf.{ByteString, GeneratedMessageV3, Message} +import quoted.{Expr, Quotes, Type} + +import scala.collection.mutable + +// scalastyle:off number.of.methods +class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Type[M])(using quotas:Quotes) { + import quotas.reflect._ + + private[this] val scalaClassType = quotas.reflect.TypeRepr.of[T](using typeT) + private[this] val protoClassType = quotas.reflect.TypeRepr.of[M](using typeM) + + private[this] val protoClassSymbol: quotas.reflect.Symbol = quotas.reflect.TypeReprMethods.classSymbol(protoClassType).get + private[this] val protoClassSymbolCompanion = quotas.reflect.SymbolMethods.companionClass(protoClassSymbol) + private[this] val builderSymbol = quotas.reflect.SymbolMethods.declaredMethod(protoClassSymbolCompanion)("newBuilder").head +// private[this] val newBuilderTree = Apply(builderSymbol.tree.asInstanceOf[Term], List.empty) + private[this] val newProtoTree = New(protoClassSymbol.tree.asInstanceOf[TypeTree]).asExprOf[M] + + + + + + + private val x = quotas.reflect.SymbolMethods.memberMethod(protoClassSymbolCompanion)("newBuilder").head + println(x) + + Apply(protoClassSymbol.tree) + + + private[this] def packageName = ???//q"_root_.pbconverts" + private[this] def builderIdent = ???//Ident(TermRef("builder")) + private[this] def entityIdent = ??? //Ident.apply(TermRef(,"entity")) //Ident(TermRef("entity")) + private[this] def protoIdent = ??? //Ident(TermRef("proto")) + private[this] def implicitlyProtoable(entityType: TypeRepr, protoType: TypeRepr) = ??? //q"implicitly[$packageName.Protoable[$entityType,$protoType]]" + + private[this] def implicitlyScalable(entityType: TypeRepr, protoType: TypeRepr) = ??? //q"implicitly[$packageName.Scalable[$entityType,$protoType]]" + + private[this] def isOption(tpe: TypeRepr): Boolean = { + tpe <:< TypeRepr.of[Option[_]] + } + + private[this] def isIterable(tpe: TypeRepr): Boolean = + (tpe <:< TypeRepr.of[Iterable[_]] + || tpe <:< TypeRepr.of[Array[_]] + || tpe <:< TypeRepr.of[java.lang.Iterable[_]]) && !(tpe <:< TypeRepr.of[Map[_, _]] || tpe <:< TypeRepr.of[ByteString]) + + private[this] def isMap(tpe: TypeRepr): Boolean = tpe <:< TypeRepr.of[Map[_, _]] || tpe <:< TypeRepr.of[java.util.Map[_, _]] + + private[this] def getBuilderType(): TypeRepr = { +// TypeReprMethods +// protoType.companion.member(TermName("newBuilder")).asTerm.alternatives.head.asMethod.returnType + ??? + } + + private trait Processor { + + def scalaTreeType: TypeRepr + def protoValueType: TypeRepr + + def resolvedCaseClassFieldType: TypeRepr = resolveFieldType(scalaTreeType) + + def tree: Option[Tree] + } + + // Convert expr (`scalaTree` in this class) to protobuf value + private class ToProtoProcessor( + scalaTree: Tree, + override val scalaTreeType: TypeRepr, + override val protoFieldName: String + ) extends ProtoFieldAnalyst { + + private[this] def toProto(t1: TypeRepr, t2: TypeRepr): Tree = { + if (t1 <:< t2) { + scalaTree + } else { + ??? +// q"${implicitlyProtoable(t1, t2)}.toProto($scalaTree)" + } + } + + override def protoValueType: TypeRepr = protoValueSetterType + + def optTree(optFieldType: TypeRepr): Tree = { + val tree = if (isIterable(protoValueType)) { + seqTree(optFieldType) + } else if (isMap(protoValueType)) { + mapTree(optFieldType) + } else { + defaultTree(optFieldType) + } + ??? +// If(q"$scalaTree.isDefined", tree, EmptyTree) + } + + def seqTree(iterableType: TypeRepr): Tree = { +// val listType = builderType.member(addAllMethodName).asMethod.paramLists.head.head.typeSignature +// val valueTree = toProto(iterableType, listType) +// q"${builderIdent}.$addAllMethodName($valueTree)" + ??? + } + + def mapTree(mapType: TypeRepr): Tree = { +// val putAllMapType = builderType.member(putAllMethodName).asMethod.paramLists.head.head.typeSignature +// val valueTree = toProto(mapType, putAllMapType) +// q"${builderIdent}.$putAllMethodName($valueTree)" + ??? + } + + def defaultTree(fieldType: TypeRepr): Tree = { +// val valueTree = toProto(fieldType, protoValueType) +// q"${builderIdent}.$setField(${valueTree})" + ??? + } + + override def tree: Option[Tree] = { +// if (protoValueType == NoType) { + if (protoValueType == ???) { + None + } else { + val _tree = if (isOption(scalaTreeType)) { + optTree(resolvedCaseClassFieldType) + } else if (isIterable(protoValueType)) { + seqTree(resolvedCaseClassFieldType) + } else if (isMap(protoValueType)) { + mapTree(resolvedCaseClassFieldType) + } else { + defaultTree(resolvedCaseClassFieldType) + } + + if (scalaTreeType <:< TypeRepr.of[AnyRef]) { +// val notNullCondition = q"$scalaTree ne null" +// Some(If(notNullCondition, _tree, EmptyTree)) + ??? + } else { + Some(_tree) + } + } + } + } + + // Convert expr (`protoValueTree` in this class) to case class filed value + private case class ToScalaProcessor(caseClassSelector: Symbol, protoValueTree: Tree, protoValueType: TypeRepr) + extends AbstractToScalaProcessor + + private trait AbstractToScalaProcessor extends Processor { + + def caseClassSelector: Symbol + + def protoValueTree: Tree + + override def scalaTreeType: TypeRepr = ???//caseClassSelector.returnType + + protected def toScala(t1: TypeRepr, t2: TypeRepr, value: Tree) = { + if (t2 <:< t1) { + value + } else { +// q"${implicitlyScalable(t1, t2)}.toScala($value)" + ??? + } + } + + def optTree(optType: TypeRepr): Tree = defaultTree(optType) + + def defaultTree(fieldType: TypeRepr): Tree = { +// q"$caseClassSelector = ${toScala(fieldType, protoValueType, protoValueTree)}" + ??? + } + + override def tree: Option[Tree] = + if (protoValueType == ???) { +// if (protoValueType == NoType) { + None + } else { + if (isOption(scalaTreeType)) { + Some(optTree(resolvedCaseClassFieldType)) + } else { + Some(defaultTree(resolvedCaseClassFieldType)) + } + } + } + + // Contain some methods and vals to analyze Protobuf fields + private trait ProtoFieldAnalyst extends Processor { + def protoFieldName: String + + val builderType = getBuilderType() + + + def addAllMethodName: ByName = ???//ByName(s"addAll$protoFieldName") + def putAllMethodName: ByName = ???//ByName(s"putAll$protoFieldName") + + def addField: ByName = ???//TermName(s"add$protoFieldName") + def putField: ByName = ???//TermName(s"put$protoFieldName") + def setField: ByName = ???//TermName(s"set$protoFieldName") + def getField: ByName = ???//TermName(s"get$protoFieldName") + def getMapField: ByName = ???//TermName(s"get${protoFieldName}Map") + def getListField: ByName = ???//TermName(s"get${protoFieldName}List") + def builderSetter: ByName = if (isIterable(scalaTreeType)) addAllMethodName else setField + + val protoValueTree: Tree = { +// if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 +// q"$protoIdent.$getListField" +// } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map +// q"$protoIdent.$getMapField" +// } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 +// q"$protoIdent.$getField" +// } else { +// q"" +// } + ??? + } + + lazy val protoValueSetterType: TypeRepr = { +// val pbBuilderType = typeOf[com.google.protobuf.Message.Builder] +// val setterOpt = if (builderType.member(addField) != NoSymbol) { +// Some(builderType.member(addAllMethodName)) +// } else if (builderType.member(putField) != NoSymbol) { +// Some(builderType.member(putAllMethodName)) +// } else if (builderType.member(setField) != NoSymbol) { +// Some(builderType.member(setField)) +// } else { +// None +// } +// setterOpt.fold(NoType)(_.alternatives.map(_.asMethod.paramLists.head.head.typeSignature).find(t ⇒ !(t <:< pbBuilderType)).get) + ??? + } + + lazy val protoValueGetterType: TypeRepr = { +// if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 +// protoType.member(getListField).typeSignature.resultType +// } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map +// protoType.member(getMapField).typeSignature.resultType +// } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 +// protoType.member(getField).typeSignature.resultType +// } else { +// NoType +// } + ??? + } + + } + + + + // Convert scala clase class field value to protobuf value + private case class ToProtoFieldProcessor(scalaEntity:Ident,accessor: Symbol) + extends ToProtoProcessor( + Apply(scalaEntity,List(accessor.asInstanceOf[Term])), + ??? /*accessor.returnType*/, + accessor.name.toString.capitalize) + + // Convert protobuf value to case class filed value + private case class ToScalaFieldProcessor(accessor: Symbol) + extends AbstractToScalaProcessor + with ProtoFieldAnalyst { + + override def caseClassSelector: Symbol = accessor + + override def protoFieldName: String = accessor.name.toString.capitalize + + override def protoValueType: TypeRepr = protoValueGetterType + + override def optTree(optType: TypeRepr): Tree = { + val hasProtoField = ByName( ??? /*s"has$protoFieldName"*/) +// if (protoType.member(hasProtoField) == NoSymbol) { +// defaultTree(optType) +// } else { +// q"$caseClassSelector = if (${protoIdent}.$hasProtoField) ${toScala(optType, protoValueType, protoValueTree)} else None" +// } + ??? + } + } + + private[this] def resolveFieldType(originType: TypeRepr): TypeRepr = { +// originType.asSeenFrom(entityType, entityType.typeSymbol.asClass) + ??? + } + + private[this] def resolveType[T](using Type[T]): TypeRepr = { +// val tpe = weakTypeOf[T] +// tpe.dealias +// ??? + TypeRepr.of[T] + } + + private[this] def getCaseAccessors(): List[Symbol] = { + val classSymbol = quotas.reflect.TypeReprMethods.classSymbol(scalaClassType).get + quotas.reflect.SymbolMethods.caseFields(classSymbol) + } + + private[this] def defaultProtoableFieldConvertTrees(scalaEntity:Ident): Map[String, Tree] = { + getCaseAccessors().flatMap { a ⇒ + val p = ToProtoFieldProcessor(scalaEntity,a) + p.tree.map(p.protoFieldName -> _) + }.toMap + } + + private[this] def protoableBody(protoableFieldConvertTrees: Iterable[Tree]): Tree = { +// q""" +// override def toProto(${entityIdent.name.toTermName}: $caseClassType): $protoType = { +// val ${builderIdent} = ${protoType.typeSymbol.companion}.newBuilder() +// ..$protoableFieldConvertTrees +// $builderIdent.build() +// } +// """ + ??? + } + + private def defalutScalableFieldConvertTrees(): Map[String, Tree] = { + getCaseAccessors().flatMap(accessor ⇒ ToScalaFieldProcessor(accessor).tree.map(accessor.name.toString -> _)).toMap + } + + private def scalableBody(scalableFieldConvertTrees: Iterable[Tree]): Tree = { +// q""" +// override def toScala(${protoIdent.name.toTermName} :$protoType): $caseClassType = { +// new ${caseClassType.typeSymbol} ( +// ..${scalableFieldConvertTrees} +// ) +// } +// """ + ??? + } + + def scalasImpl[T, M](using Type[T], Type[M]): Expr[Scalable[T,M]] = { + val scalableFieldConvertTrees = defalutScalableFieldConvertTrees().values + + quotas.reflect.TreeMethods + .asExpr(scalasImpl(scalableFieldConvertTrees, Nil)).asInstanceOf[Expr[Scalable[T,M]]] + } + + private[this] def scalasImpl(scalableFieldConvertTrees: Iterable[Tree], perTrees: Iterable[Tree]): Tree = { +// q""" +// ..$perTrees +// new $packageName.Scalable[$caseClassType, $protoType] { ${scalableBody(caseClassType, protoType, scalableFieldConvertTrees)} } +// """ + ??? + } + + private def protosImpl: Expr[Protoable[T,M]] = { + protosImpl(ident => defaultProtoableFieldConvertTrees(ident).values, Nil) + } + + + private[this] inline def protosImpl(protoableFieldConvertTrees:Ident => Iterable[Tree], perTrees: Iterable[Tree]): Expr[Protoable[T,M]] = { +// q""" +// ..$perTrees +// new $packageName.Protoable[$caseClassType,$protoType] { ${protoableBody(caseClassType, protoType, protoableFieldConvertTrees)} } +// """ + '{ + new Protoable[T,M] { + override def toProto(scalaEntity: T): M = { + val proto:M = ${newProtoTree} + val builder = proto.toBuilder +// ..$protoableFieldConvertTrees +// builder.build() + ${quotas.reflect.TreeMethods.asExprOf(Apply('{builder}.asInstanceOf[Term],List.empty[Term]).asInstanceOf[Nothing])} + } + } + } + } + + def convertsImpl[T, M](using Type[T], Type[M]): Expr[ProtoScalable[T,M]] = { +// q""" +// new $packageName.ProtoScalable[${resolveType[T]}, ${resolveType[M]}] { +// ${scalableBody(caseClassType, protoType, defalutScalableFieldConvertTrees(caseClassType, protoType).values)} +// ${protoableBody(caseClassType, protoType, defaultProtoableFieldConvertTrees(caseClassType, protoType).values)} +// } +// """ + ??? + } + + private def buildProtoableImpl[T, M]: Tree = { +// val caseClassType = resolveType[T] +// val protoType = resolveType[M] +// val customTrees = MacroCache.builderFunctionTrees.getOrElse(getBuilderId(), mutable.Map.empty) +// val (fixedCustomTrees, preTrees) = customTrees.map { +// case (key, tree) ⇒ +// tree match { // setField +// case buildFunction: Function ⇒ +// val functionName = TermName("builderFunction$" + MacroCache.getIdentityId) +// val fromType = buildFunction.tpe.typeArgs.last // buildFunction 的返回值 +// val buildExpr = new ToProtoProcessor(q"$functionName($entityIdent)", fromType, caseClassType, protoType, key).tree.get +// (key -> buildExpr) -> q"val $functionName = $buildFunction" +// case value: Tree ⇒ // setFieldValue +// val identity = TermName("identity$" + MacroCache.getIdentityId) +// val buildExpr = new ToProtoProcessor(q"$identity", value.tpe, caseClassType, protoType, key).tree.get +// (key -> buildExpr) -> q"val $identity = $value" +// } +// }.unzip +// val protoableFieldConvertTrees = (defaultProtoableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values +// protosImpl(caseClassType, protoType, protoableFieldConvertTrees, preTrees) + ??? + } + + private def buildScalableImpl[T, M]: Tree = { +// val caseClassType = resolveType[T] +// val protoType = resolveType[M] +// val builderId = getBuilderId() +// val customTrees = MacroCache.builderFunctionTrees.getOrElse(builderId, mutable.Map.empty) +// val entityType = resolveType[T] +// +// val (fixedCustomTrees, preTrees) = customTrees.map { +// case (key, tree) ⇒ +// val selector = entityType.member(TermName(key)) +// tree match { +// case buildFunction: Function ⇒ // setField +// val functionName = TermName("builderFunction$" + MacroCache.getIdentityId) +// val expr = new ToScalaProcessor(selector.asMethod, q"$functionName($protoIdent)", buildFunction.body.tpe, resolveType[T], resolveType[M]).tree.get +// (key -> expr) -> q"val $functionName = $buildFunction" +// case value: Tree ⇒ // setFieldValue +// val identity = TermName("identity$" + MacroCache.getIdentityId) +// val expr = new ToScalaProcessor(selector.asMethod, q"$identity", value.tpe, resolveType[T], resolveType[M]).tree.get +// (key -> expr) -> q"val $identity = $value" +// } +// }.unzip +// +// val scalableFieldConvertTrees = (defalutScalableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values +// scalasImpl(caseClassType, protoType, scalableFieldConvertTrees, preTrees) + ??? + } + + private def setScalaFieldImpl[T, M, TF, MF](scalaField: Tree, value: Tree): Tree = { +// val Function(_, Select(_, termName)) = scalaField +// val builderId = getBuilderId() +// MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(termName.toString, value) +// q"new ${c.prefix.actualType}" + ??? + } + + private def setProtoFieldImpl[T, M, TF, MF](protoFieldSelector: Tree, value: Tree): Tree = { +// val getter = "^get(\\w+)$".r +// val listGetter = "^get(\\w+)List$".r +// val mapGetter = "^get(\\w+)Map$".r +// val setter = protoFieldSelector.find { +// case _: Select ⇒ true +// case _: Tree ⇒ false +// } match { +// case Some(select: Select) ⇒ +// select.name.toString match { +// case mapGetter(n) if select.tpe.resultType <:< typeOf[java.util.Map[_, _]] ⇒ n +// case listGetter(n) if select.tpe.resultType <:< typeOf[java.util.List[_]] ⇒ n +// case getter(n) ⇒ n +// case _ ⇒ c.abort(protoFieldSelector.pos, "Invalid setter") +// } +// case _ ⇒ c.abort(protoFieldSelector.pos, "Invalid setter") +// } +// val builderId = getBuilderId() +// MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(setter, value) +// q"new ${c.prefix.actualType}" + ??? + } + + val annoBuilderPrefix = "AnonBuilder$" + + private def scalableBuilderApply[T, M]: Tree = { +// val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) +// q""" +// class $className extends $packageName.ScalableBuilder[${resolveType[T]}, ${resolveType[M]}] +// new $className +// """ + ??? + } + + private def protoableBuilderApply[T, M]: Tree = { +// val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) +// q""" +// class $className extends $packageName.ProtoableBuilder[${resolveType[T]}, ${resolveType[M]}] +// new $className +// """ + ??? + } + + private[this] def getBuilderId() = { +// c.prefix.actualType.toString.replace(annoBuilderPrefix, "").toInt + quotas.reflect.Position.ofMacroExpansion + } + +} + + +object ProtoScalableMacro { + + inline def protoable[T,M<:GeneratedMessageV3]:Protoable[T,M] = { + ${protosImpl[T,M]} + } + + def protosImpl[T,M<:GeneratedMessageV3](using t:Type[T], m:Type[M],quotes: Quotes ):Expr[Protoable[T,M]] = { + val protoScalableMacro = new ProtoScalableMacro(using t, m) + protoScalableMacro.protosImpl + } +} \ No newline at end of file diff --git a/pbconverts/src/main/scala/pbconverts/Protoable.scala b/pbconverts/src/main/scala/pbconverts/Protoable.scala index 18f2599..cb9ba0a 100644 --- a/pbconverts/src/main/scala/pbconverts/Protoable.scala +++ b/pbconverts/src/main/scala/pbconverts/Protoable.scala @@ -1,8 +1,9 @@ package pbconverts -import java.time.ZonedDateTime +import annotation.targetName -import com.google.protobuf.{BoolValue, DoubleValue, FloatValue, Int32Value, Int64Value, StringValue, Timestamp} +import java.time.ZonedDateTime +import com.google.protobuf.{BoolValue, DoubleValue, FloatValue, GeneratedMessageV3, Int32Value, Int64Value, Message, StringValue, Timestamp} import scala.collection.JavaConverters._ @@ -12,72 +13,68 @@ trait Protoable[-T, +M] { object Protoable { - def apply[T <: Product, M]: Protoable[T, M] = ??? // macro ProtoScalableMacro.protosImpl[T, M] + inline def apply[T <: Product, M <: GeneratedMessageV3]: Protoable[T, M] = { + ProtoScalableMacro.protoable[T, M] + } def apply[T, M](f: T ⇒ M): Protoable[T, M] = new Protoable[T, M] { override def toProto(entity: T): M = f(entity) } - implicit val javaDoubleProtoable: Protoable[Double, java.lang.Double] = Protoable[Double, java.lang.Double](_.toDouble) - implicit val javaFloatProtoable: Protoable[Float, java.lang.Float] = Protoable[Float, java.lang.Float](_.toFloat) - implicit val javaIntergerProtoable: Protoable[Int, java.lang.Integer] = Protoable[Int, java.lang.Integer](_.toInt) - implicit val javaLongProtoable: Protoable[Long, java.lang.Long] = Protoable[Long, java.lang.Long](_.toLong) -// implicit val javaCharacterProtoable = Protoable[Char, java.lang.Character](_.toChar) -// implicit val javaByteProtoable = Protoable[Byte, java.lang.Byte](_.toByte) -// -// implicit val stringValueProtoable = Protoable[String, StringValue](StringValue.of) -// implicit val doubleValueProtoable = Protoable[Double, DoubleValue](DoubleValue.of) -// implicit val floatValueProtoable = Protoable[Float, FloatValue](FloatValue.of) -// implicit val int32ValueProtoable = Protoable[Int, Int32Value](Int32Value.of) -// implicit val boolValueProtoable = Protoable[Boolean, BoolValue](BoolValue.of) -// implicit val int64ValueProtoable = Protoable[Long, Int64Value](Int64Value.of) - -// implicit val stringValueProtoable = Protoable[String, StringValue](StringValue.of) -// implicit val doubleValueProtoable = Protoable[Double, DoubleValue](DoubleValue.of) -// implicit val floatValueProtoable = Protoable[Float, FloatValue](FloatValue.of) -// implicit val int32ValueProtoable = Protoable[Int, Int32Value](Int32Value.of) -// implicit val boolValueProtoable = Protoable[Boolean, BoolValue](BoolValue.of) -// implicit val int64ValueProtoable = Protoable[Long, Int64Value](Int64Value.of) -// -// implicit val zonedDateTimeProtoable = Protoable[ZonedDateTime, Timestamp] { entity ⇒ -// Timestamp.newBuilder().setSeconds(entity.toEpochSecond).setNanos(entity.getNano).build() -// } - - implicit def iterableProtoable[T, M](implicit protoable: Protoable[T, M]): Protoable[scala.Iterable[T], java.util.List[M]] = + given Protoable[Double, java.lang.Double] = Protoable(_.toDouble) + given Protoable[Float, java.lang.Float] = Protoable(_.toFloat) + given Protoable[Int, java.lang.Integer] = Protoable(_.toInt) + given Protoable[Long, java.lang.Long] = Protoable(_.toLong) + given Protoable[Char, java.lang.Character] = Protoable(_.toChar) + given Protoable[Byte, java.lang.Byte] = Protoable(_.toByte) + + given Protoable[String, StringValue]= Protoable(StringValue.of) + given Protoable[Double, DoubleValue]= Protoable(DoubleValue.of) + given Protoable[Float, FloatValue]= Protoable(FloatValue.of) + given Protoable[Int, Int32Value]= Protoable(Int32Value.of) + given Protoable[Boolean, BoolValue]= Protoable(BoolValue.of) + given Protoable[Long, Int64Value]= Protoable(Int64Value.of) + + given Protoable[ZonedDateTime, Timestamp] = Protoable { entity ⇒ + Timestamp.newBuilder().setSeconds(entity.toEpochSecond).setNanos(entity.getNano).build() + } + + given [T, M](using protoable: Protoable[T, M]): Protoable[scala.Iterable[T], java.util.List[M]] = Protoable[scala.Iterable[T], java.util.List[M]] { entity ⇒ entity.toList.map(protoable.toProto).asJava } - implicit def iterableProtoable2[T]: Protoable[scala.Iterable[T], java.util.List[T]] = + given [T]: Protoable[scala.Iterable[T], java.util.List[T]] = Protoable[scala.Iterable[T], java.util.List[T]] { entity ⇒ entity.toList.asJava } - implicit def arrayProtoable[T]: Protoable[Array[T], java.util.List[T]] = + given[T]: Protoable[Array[T], java.util.List[T]] = Protoable[Array[T], java.util.List[T]] { entity ⇒ entity.toList.asJava } - implicit def arrayProtoable2[T, M](implicit protoable: Protoable[T, M]): Protoable[Array[T], java.lang.Iterable[M]] = + given[T, M](using protoable: Protoable[T, M]): Protoable[Array[T], java.lang.Iterable[M]] = Protoable[Array[T], java.util.List[M]] { entity ⇒ entity.toList.map(protoable.toProto).asJava } - implicit def optProtoable[F, Target <: Any](implicit protoable: Protoable[F, Target]): Protoable[Option[F], Target] = + given[F, Target <: Any](using protoable: Protoable[F, Target]): Protoable[Option[F], Target] = Protoable[Option[F], Target] { (entity: Option[F]) ⇒ entity.map(protoable.toProto).getOrElse(None.orNull.asInstanceOf[Target]) } - implicit def optProtoable2[T]: Protoable[Option[T], T] = + given[T]: Protoable[Option[T], T] = Protoable[Option[T], T] { (opt: Option[T]) => opt.getOrElse(None.orNull.asInstanceOf[T]) } - implicit def mapProtoable1[K, V]: Protoable[Map[K, V], java.util.Map[K, V]] = + given[K, V]: Protoable[Map[K, V], java.util.Map[K, V]] = Protoable[Map[K, V], java.util.Map[K, V]] { m ⇒ m.asJava } - implicit def mapProtoable2[K1, K2, V](implicit kProtoable: Protoable[K1, K2]): Protoable[Map[K1, V], java.util.Map[K2, V]] = + @targetName("for key mapping") + given[K1, K2, V](using kProtoable: Protoable[K1, K2]): Protoable[Map[K1, V], java.util.Map[K2, V]] = Protoable[Map[K1, V], java.util.Map[K2, V]] { m ⇒ m.map { case (k, v) ⇒ kProtoable.toProto(k) -> v }.asJava } - implicit def mapProtoable3[K, V1, V2](implicit vProtoable: Protoable[V1, V2]): Protoable[Map[K, V1], java.util.Map[K, V2]] = + given[K, V1, V2](using vProtoable: Protoable[V1, V2]): Protoable[Map[K, V1], java.util.Map[K, V2]] = Protoable[Map[K, V1], java.util.Map[K, V2]] { m ⇒ m.map { case (k, v) ⇒ k -> vProtoable.toProto(v) }.asJava } - implicit def mapProtoable4[K1, K2, V1, V2](implicit + given[K1, K2, V1, V2](using kProtoable: Protoable[K1, K2], vProtoable: Protoable[V1, V2] ): Protoable[Map[K1, V1], java.util.Map[K2, V2]] = diff --git a/pbconverts/src/main/scala/pbconverts/Scalable.scala b/pbconverts/src/main/scala/pbconverts/Scalable.scala index 987edaa..02a0471 100644 --- a/pbconverts/src/main/scala/pbconverts/Scalable.scala +++ b/pbconverts/src/main/scala/pbconverts/Scalable.scala @@ -1,10 +1,10 @@ package pbconverts import java.time.{Instant, ZoneId, ZonedDateTime} - import com.google.protobuf.{BoolValue, DoubleValue, FloatValue, Int32Value, Int64Value, StringValue, Timestamp} import scala.collection.JavaConverters._ +import scala.concurrent.ExecutionContext import scala.reflect.ClassTag trait Scalable[+T, -M] { @@ -22,38 +22,39 @@ object Scalable extends ScalableImplicits { given Int = 1 - given Scalable[Int, java.lang.Integer] = Scalable[Int, java.lang.Integer].apply(_.toInt) -// given javaLongScalable: Scalable[Long, java.lang.Long] with Scalable[Long, java.lang.Long](_.toLong) -// given javaDoubleScalable:Scalable[Double, java.lang.Double] with Scalable[Double, java.lang.Double](_.toDouble) -// given javaFloatScalable:Scalable[Float, java.lang.Float] with Scalable[Float, java.lang.Float](_.toFloat) -// given javaCharacterScalable:Scalable[Char, java.lang.Character] with Scalable[Char, java.lang.Character](_.toChar) -// given javaByteScalable:Scalable[Byte, java.lang.Byte] with Scalable[Byte, java.lang.Byte](_.toByte) - -// given Scalable [String, StringValue] = Scalable [String, StringValue] (_.getValue) -// given Scalable [Int, Int32Value] = Scalable [Int, Int32Value] (_.getValue) -// given Scalable [Long, Int64Value] = Scalable [Long, Int64Value] (_.getValue) -// given Scalable [Double, DoubleValue] = Scalable [Double, DoubleValue] (_.getValue) -// given Scalable [Float, FloatValue] = Scalable [Float, FloatValue] (_.getValue) -// given Scalable [Boolean, BoolValue] = Scalable [Boolean, BoolValue] (_.getValue) - - implicit val zonedDateTimeProtoable: Scalable[ZonedDateTime, Timestamp] = Scalable[ZonedDateTime, Timestamp] { proto ⇒ + given Scalable[Int, java.lang.Integer] = Scalable(_.toInt) + given Scalable[Long, java.lang.Long] = Scalable(_.toLong) + + given Scalable[Double, java.lang.Double] = Scalable(_.toDouble) + given Scalable[Float, java.lang.Float] = Scalable(_.toFloat) + given Scalable[Char, java.lang.Character] = Scalable(_.toChar) + given javaByteScalable:Scalable[Byte, java.lang.Byte] = Scalable(_.toByte) + + given Scalable [String, StringValue] = Scalable (_.getValue) + given Scalable [Int, Int32Value] = Scalable(_.getValue) + given Scalable [Long, Int64Value] = Scalable(_.getValue) + given Scalable [Double, DoubleValue] = Scalable(_.getValue) + given Scalable [Float, FloatValue] = Scalable(_.getValue) + given Scalable [Boolean, BoolValue] = Scalable(_.getValue) + + given Scalable[ZonedDateTime, Timestamp] = Scalable { proto ⇒ Instant.ofEpochSecond(proto.getSeconds, proto.getNanos).atZone(ZoneId.systemDefault()) } - // java.lang.Iterable[M] => Array[T] - implicit def arrayScalable[T: ClassTag, M](implicit scalable: Scalable[T, M]): Scalable[Array[T], java.lang.Iterable[M]] = + //java.lang.Iterable[M] => Array[T] + given [T:ClassTag,M](using scalable:Scalable[T, M]):Scalable[Array[T], java.lang.Iterable[M]] = Scalable { proto ⇒ proto.asScala.map(scalable.toScala).toArray } - implicit def arrayScalable2[T: ClassTag]: Scalable[Array[T], java.lang.Iterable[T]] = Scalable { proto ⇒ proto.asScala.toArray } + given [T: ClassTag]: Scalable[Array[T], java.lang.Iterable[T]] = Scalable { proto ⇒ proto.asScala.toArray } // M => Option[T] - implicit def optScalable[T, M](implicit scalable: Scalable[T, M]): Scalable[Option[T], M] = + given [T, M](using scalable: Scalable[T, M]): Scalable[Option[T], M] = Scalable { proto ⇒ Option(scalable.toScala(proto)) } - implicit def optScalable2[T]: Scalable[Option[T], T] = Scalable(Option(_)) + given [T]: Scalable[Option[T], T] = Scalable(Option(_)) } diff --git a/pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala b/pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala index febbf52..003bf46 100644 --- a/pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala +++ b/pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala @@ -1,44 +1,44 @@ package pbconverts +import annotation.targetName + import scala.collection.BuildFrom import scala.collection.JavaConverters._ import scala.reflect.ClassTag trait ScalableImplicits { - // java.lang.Iterable[M] => That[T] - implicit def iterableScalable[That[_], T, M](implicit - scalable: Scalable[T, M], - bf: BuildFrom[Seq[_], T, That[T]] - ): Scalable[That[T], java.lang.Iterable[M]] = +// java.lang.Iterable[M] => That[T] + given[That[_], T, M](using scalable: Scalable[T, M], bf: BuildFrom[Seq[_], T, That[T]]): Scalable[That[T], java.lang.Iterable[M]] = Scalable { proto ⇒ bf.fromSpecific(Seq.empty)(proto.asScala.iterator.map(scalable.toScala)) } - implicit def iterableScalable2[That[T], T](implicit bf: BuildFrom[Seq[T], T, That[T]]): Scalable[That[T], java.lang.Iterable[T]] = + given [That[T], T](using bf: BuildFrom[Seq[T], T, That[T]]): Scalable[That[T], java.lang.Iterable[T]] = Scalable { proto ⇒ bf.fromSpecific(Seq.empty)(proto.asScala) } // // Repr[M] => That[T] - implicit def iterableSelfScalable[That, Repr <: Iterable[M], T, M](implicit + given[That, Repr <: Iterable[M], T, M](using scalable: Scalable[T, M], bf: BuildFrom[Iterable[_], T, That] ): Scalable[That, Repr] = { proto ⇒ bf.newBuilder(proto.map(scalable.toScala)).result() } - implicit def mapScalable4[K1, K2, V1, V2](implicit kScalable: Scalable[K1, K2], vScalable: Scalable[V1, V2]): Scalable[Map[K1, V1], java.util.Map[K2, V2]] = + given [K1, K2, V1, V2](using kScalable: Scalable[K1, K2], vScalable: Scalable[V1, V2]): Scalable[Map[K1, V1], java.util.Map[K2, V2]] = Scalable[Map[K1, V1], java.util.Map[K2, V2]] { m ⇒ m.asScala.map { case (k, v) ⇒ kScalable.toScala(k) -> vScalable.toScala(v) }.toMap } - implicit def mapScalable3[K, V1, V2](implicit vScalable: Scalable[V1, V2]): Scalable[Map[K, V1], java.util.Map[K, V2]] = + given [K, V1, V2](using vScalable: Scalable[V1, V2]): Scalable[Map[K, V1], java.util.Map[K, V2]] = Scalable[Map[K, V1], java.util.Map[K, V2]] { m ⇒ m.asScala.map { case (k, v) ⇒ k -> vScalable.toScala(v) }.toMap } - implicit def mapScalable2[K1, K2, V](implicit kScalable: Scalable[K1, K2]): Scalable[Map[K1, V], java.util.Map[K2, V]] = + @targetName("key mapping") + given [K1, K2, V](using kScalable: Scalable[K1, K2]): Scalable[Map[K1, V], java.util.Map[K2, V]] = Scalable[Map[K1, V], java.util.Map[K2, V]] { m ⇒ m.asScala.map { case (k, v) ⇒ kScalable.toScala(k) -> v }.toMap } - implicit def mapScalable1[K, V]: Scalable[Map[K, V], java.util.Map[K, V]] = + given [K, V]: Scalable[Map[K, V], java.util.Map[K, V]] = Scalable[Map[K, V], java.util.Map[K, V]] { m ⇒ m.asScala.toMap } } diff --git a/pbconverts/src/test/protobuf/conversion_test.proto b/pbconverts/src/test/protobuf/conversion_test.proto index 4dc9e38..2b3fc84 100644 --- a/pbconverts/src/test/protobuf/conversion_test.proto +++ b/pbconverts/src/test/protobuf/conversion_test.proto @@ -1,50 +1,50 @@ -syntax = "proto3"; - -option java_package = "pbconverts"; - -import "google/protobuf/wrappers.proto"; -import "google/protobuf/timestamp.proto"; - -message PBTestMessage { - int32 int_value = 1; - int64 long_value = 2; - float float_value = 3; - double double_value = 4; - bool bool_value = 5; - string string_value = 6; - google.protobuf.Int32Value int_Opt = 7; - google.protobuf.Int64Value long_Opt = 8; - google.protobuf.FloatValue float_Opt = 9; - google.protobuf.DoubleValue double_opt = 10; - google.protobuf.BoolValue bool_opt = 11; - google.protobuf.StringValue string_opt = 12; - google.protobuf.Timestamp time = 13; - google.protobuf.Timestamp time_opt = 14; - repeated int32 int_array = 15; - repeated string string_array = 16; - repeated PBPerson person_array = 17; - repeated double seq = 18; - map string_string_k_v = 19; - map long_string_k_v = 20; - map string_int_k_v = 21; - map long_int_k_v = 22; -} - -message PBPerson { - int64 id = 1; - string name = 2; - google.protobuf.StringValue phone = 3; - repeated string hobbies = 4; -} - -message PBTestBytes { - bytes test_bytes = 1; -} - -message IntMessage { - int32 value = 1; -} - -message StringMessage { - string value = 1; -} +//syntax = "proto3"; +// +//option java_package = "pbconverts"; +// +//import "google/protobuf/wrappers.proto"; +//import "google/protobuf/timestamp.proto"; +// +//message PBTestMessage { +// int32 int_value = 1; +// int64 long_value = 2; +// float float_value = 3; +// double double_value = 4; +// bool bool_value = 5; +// string string_value = 6; +// google.protobuf.Int32Value int_Opt = 7; +// google.protobuf.Int64Value long_Opt = 8; +// google.protobuf.FloatValue float_Opt = 9; +// google.protobuf.DoubleValue double_opt = 10; +// google.protobuf.BoolValue bool_opt = 11; +// google.protobuf.StringValue string_opt = 12; +// google.protobuf.Timestamp time = 13; +// google.protobuf.Timestamp time_opt = 14; +// repeated int32 int_array = 15; +// repeated string string_array = 16; +// repeated PBPerson person_array = 17; +// repeated double seq = 18; +// map string_string_k_v = 19; +// map long_string_k_v = 20; +// map string_int_k_v = 21; +// map long_int_k_v = 22; +//} +// +//message PBPerson { +// int64 id = 1; +// string name = 2; +// google.protobuf.StringValue phone = 3; +// repeated string hobbies = 4; +//} +// +//message PBTestBytes { +// bytes test_bytes = 1; +//} +// +//message IntMessage { +// int32 value = 1; +//} +// +//message StringMessage { +// string value = 1; +//} diff --git a/pbconverts/src/test/resources/MessageWithType.java b/pbconverts/src/test/resources/MessageWithType.java new file mode 100644 index 0000000..54c3882 --- /dev/null +++ b/pbconverts/src/test/resources/MessageWithType.java @@ -0,0 +1 @@ +package pbconverts;case class MessageWithType[T](value: T) diff --git a/pbconverts/src/test/scala/pbconverts/MessageWithTypeSpec.scala b/pbconverts/src/test/resources/MessageWithTypeSpec.scala similarity index 100% rename from pbconverts/src/test/scala/pbconverts/MessageWithTypeSpec.scala rename to pbconverts/src/test/resources/MessageWithTypeSpec.scala diff --git a/pbconverts/src/test/resources/Person.java b/pbconverts/src/test/resources/Person.java new file mode 100644 index 0000000..c5f770e --- /dev/null +++ b/pbconverts/src/test/resources/Person.java @@ -0,0 +1 @@ +package pbconverts;case class Person(id: Long, name: String, phone: Option[String], hobbies: Seq[String]) diff --git a/pbconverts/src/test/scala/pbconverts/ProtoableBuilderSpec.scala b/pbconverts/src/test/resources/ProtoableBuilderSpec.scala similarity index 100% rename from pbconverts/src/test/scala/pbconverts/ProtoableBuilderSpec.scala rename to pbconverts/src/test/resources/ProtoableBuilderSpec.scala diff --git a/pbconverts/src/test/scala/pbconverts/ProtoableSpec.scala b/pbconverts/src/test/resources/ProtoableSpec.scala similarity index 100% rename from pbconverts/src/test/scala/pbconverts/ProtoableSpec.scala rename to pbconverts/src/test/resources/ProtoableSpec.scala diff --git a/pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala b/pbconverts/src/test/resources/ScalableBuilderSpec.scala similarity index 100% rename from pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala rename to pbconverts/src/test/resources/ScalableBuilderSpec.scala diff --git a/pbconverts/src/test/scala/pbconverts/ScalableSpec.scala b/pbconverts/src/test/resources/ScalableSpec.scala similarity index 100% rename from pbconverts/src/test/scala/pbconverts/ScalableSpec.scala rename to pbconverts/src/test/resources/ScalableSpec.scala diff --git a/pbconverts/src/test/scala/pbconverts/ConversionTest.java b/pbconverts/src/test/scala/pbconverts/ConversionTest.java new file mode 100644 index 0000000..5661dc8 --- /dev/null +++ b/pbconverts/src/test/scala/pbconverts/ConversionTest.java @@ -0,0 +1,7492 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: conversion_test.proto + +package pbconverts; + +import com.google.protobuf.GeneratedMessageV3; +import com.google.protobuf.GeneratedMessageV3.*; + +public final class ConversionTest { + private ConversionTest() {} + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistryLite registry) { + } + + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions( + (com.google.protobuf.ExtensionRegistryLite) registry); + } + public interface PBTestMessageOrBuilder extends + // @@protoc_insertion_point(interface_extends:PBTestMessage) + com.google.protobuf.MessageOrBuilder { + + /** + * int32 int_value = 1; + * @return The intValue. + */ + int getIntValue(); + + /** + * int64 long_value = 2; + * @return The longValue. + */ + long getLongValue(); + + /** + * float float_value = 3; + * @return The floatValue. + */ + float getFloatValue(); + + /** + * double double_value = 4; + * @return The doubleValue. + */ + double getDoubleValue(); + + /** + * bool bool_value = 5; + * @return The boolValue. + */ + boolean getBoolValue(); + + /** + * string string_value = 6; + * @return The stringValue. + */ + String getStringValue(); + /** + * string string_value = 6; + * @return The bytes for stringValue. + */ + com.google.protobuf.ByteString + getStringValueBytes(); + + /** + * .google.protobuf.Int32Value int_Opt = 7; + * @return Whether the intOpt field is set. + */ + boolean hasIntOpt(); + /** + * .google.protobuf.Int32Value int_Opt = 7; + * @return The intOpt. + */ + com.google.protobuf.Int32Value getIntOpt(); + /** + * .google.protobuf.Int32Value int_Opt = 7; + */ + com.google.protobuf.Int32ValueOrBuilder getIntOptOrBuilder(); + + /** + * .google.protobuf.Int64Value long_Opt = 8; + * @return Whether the longOpt field is set. + */ + boolean hasLongOpt(); + /** + * .google.protobuf.Int64Value long_Opt = 8; + * @return The longOpt. + */ + com.google.protobuf.Int64Value getLongOpt(); + /** + * .google.protobuf.Int64Value long_Opt = 8; + */ + com.google.protobuf.Int64ValueOrBuilder getLongOptOrBuilder(); + + /** + * .google.protobuf.FloatValue float_Opt = 9; + * @return Whether the floatOpt field is set. + */ + boolean hasFloatOpt(); + /** + * .google.protobuf.FloatValue float_Opt = 9; + * @return The floatOpt. + */ + com.google.protobuf.FloatValue getFloatOpt(); + /** + * .google.protobuf.FloatValue float_Opt = 9; + */ + com.google.protobuf.FloatValueOrBuilder getFloatOptOrBuilder(); + + /** + * .google.protobuf.DoubleValue double_opt = 10; + * @return Whether the doubleOpt field is set. + */ + boolean hasDoubleOpt(); + /** + * .google.protobuf.DoubleValue double_opt = 10; + * @return The doubleOpt. + */ + com.google.protobuf.DoubleValue getDoubleOpt(); + /** + * .google.protobuf.DoubleValue double_opt = 10; + */ + com.google.protobuf.DoubleValueOrBuilder getDoubleOptOrBuilder(); + + /** + * .google.protobuf.BoolValue bool_opt = 11; + * @return Whether the boolOpt field is set. + */ + boolean hasBoolOpt(); + /** + * .google.protobuf.BoolValue bool_opt = 11; + * @return The boolOpt. + */ + com.google.protobuf.BoolValue getBoolOpt(); + /** + * .google.protobuf.BoolValue bool_opt = 11; + */ + com.google.protobuf.BoolValueOrBuilder getBoolOptOrBuilder(); + + /** + * .google.protobuf.StringValue string_opt = 12; + * @return Whether the stringOpt field is set. + */ + boolean hasStringOpt(); + /** + * .google.protobuf.StringValue string_opt = 12; + * @return The stringOpt. + */ + com.google.protobuf.StringValue getStringOpt(); + /** + * .google.protobuf.StringValue string_opt = 12; + */ + com.google.protobuf.StringValueOrBuilder getStringOptOrBuilder(); + + /** + * .google.protobuf.Timestamp time = 13; + * @return Whether the time field is set. + */ + boolean hasTime(); + /** + * .google.protobuf.Timestamp time = 13; + * @return The time. + */ + com.google.protobuf.Timestamp getTime(); + /** + * .google.protobuf.Timestamp time = 13; + */ + com.google.protobuf.TimestampOrBuilder getTimeOrBuilder(); + + /** + * .google.protobuf.Timestamp time_opt = 14; + * @return Whether the timeOpt field is set. + */ + boolean hasTimeOpt(); + /** + * .google.protobuf.Timestamp time_opt = 14; + * @return The timeOpt. + */ + com.google.protobuf.Timestamp getTimeOpt(); + /** + * .google.protobuf.Timestamp time_opt = 14; + */ + com.google.protobuf.TimestampOrBuilder getTimeOptOrBuilder(); + + /** + * repeated int32 int_array = 15; + * @return A list containing the intArray. + */ + java.util.List getIntArrayList(); + /** + * repeated int32 int_array = 15; + * @return The count of intArray. + */ + int getIntArrayCount(); + /** + * repeated int32 int_array = 15; + * @param index The index of the element to return. + * @return The intArray at the given index. + */ + int getIntArray(int index); + + /** + * repeated string string_array = 16; + * @return A list containing the stringArray. + */ + java.util.List + getStringArrayList(); + /** + * repeated string string_array = 16; + * @return The count of stringArray. + */ + int getStringArrayCount(); + /** + * repeated string string_array = 16; + * @param index The index of the element to return. + * @return The stringArray at the given index. + */ + String getStringArray(int index); + /** + * repeated string string_array = 16; + * @param index The index of the value to return. + * @return The bytes of the stringArray at the given index. + */ + com.google.protobuf.ByteString + getStringArrayBytes(int index); + + /** + * repeated .PBPerson person_array = 17; + */ + java.util.List + getPersonArrayList(); + /** + * repeated .PBPerson person_array = 17; + */ + PBPerson getPersonArray(int index); + /** + * repeated .PBPerson person_array = 17; + */ + int getPersonArrayCount(); + /** + * repeated .PBPerson person_array = 17; + */ + java.util.List + getPersonArrayOrBuilderList(); + /** + * repeated .PBPerson person_array = 17; + */ + PBPersonOrBuilder getPersonArrayOrBuilder( + int index); + + /** + * repeated double seq = 18; + * @return A list containing the seq. + */ + java.util.List getSeqList(); + /** + * repeated double seq = 18; + * @return The count of seq. + */ + int getSeqCount(); + /** + * repeated double seq = 18; + * @param index The index of the element to return. + * @return The seq at the given index. + */ + double getSeq(int index); + + /** + * map<string, string> string_string_k_v = 19; + */ + int getStringStringKVCount(); + /** + * map<string, string> string_string_k_v = 19; + */ + boolean containsStringStringKV( + String key); + /** + * Use {@link #getStringStringKVMap()} instead. + */ + @Deprecated + java.util.Map + getStringStringKV(); + /** + * map<string, string> string_string_k_v = 19; + */ + java.util.Map + getStringStringKVMap(); + /** + * map<string, string> string_string_k_v = 19; + */ + + String getStringStringKVOrDefault( + String key, + String defaultValue); + /** + * map<string, string> string_string_k_v = 19; + */ + + String getStringStringKVOrThrow( + String key); + + /** + * map<int64, string> long_string_k_v = 20; + */ + int getLongStringKVCount(); + /** + * map<int64, string> long_string_k_v = 20; + */ + boolean containsLongStringKV( + long key); + /** + * Use {@link #getLongStringKVMap()} instead. + */ + @Deprecated + java.util.Map + getLongStringKV(); + /** + * map<int64, string> long_string_k_v = 20; + */ + java.util.Map + getLongStringKVMap(); + /** + * map<int64, string> long_string_k_v = 20; + */ + + String getLongStringKVOrDefault( + long key, + String defaultValue); + /** + * map<int64, string> long_string_k_v = 20; + */ + + String getLongStringKVOrThrow( + long key); + + /** + * map<string, int32> string_int_k_v = 21; + */ + int getStringIntKVCount(); + /** + * map<string, int32> string_int_k_v = 21; + */ + boolean containsStringIntKV( + String key); + /** + * Use {@link #getStringIntKVMap()} instead. + */ + @Deprecated + java.util.Map + getStringIntKV(); + /** + * map<string, int32> string_int_k_v = 21; + */ + java.util.Map + getStringIntKVMap(); + /** + * map<string, int32> string_int_k_v = 21; + */ + + int getStringIntKVOrDefault( + String key, + int defaultValue); + /** + * map<string, int32> string_int_k_v = 21; + */ + + int getStringIntKVOrThrow( + String key); + + /** + * map<int64, int32> long_int_k_v = 22; + */ + int getLongIntKVCount(); + /** + * map<int64, int32> long_int_k_v = 22; + */ + boolean containsLongIntKV( + long key); + /** + * Use {@link #getLongIntKVMap()} instead. + */ + @Deprecated + java.util.Map + getLongIntKV(); + /** + * map<int64, int32> long_int_k_v = 22; + */ + java.util.Map + getLongIntKVMap(); + /** + * map<int64, int32> long_int_k_v = 22; + */ + + int getLongIntKVOrDefault( + long key, + int defaultValue); + /** + * map<int64, int32> long_int_k_v = 22; + */ + + int getLongIntKVOrThrow( + long key); + } + /** + * Protobuf type {@code PBTestMessage} + */ + public static final class PBTestMessage extends + GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:PBTestMessage) + PBTestMessageOrBuilder { + private static final long serialVersionUID = 0L; + // Use PBTestMessage.newBuilder() to construct. + private PBTestMessage(GeneratedMessageV3.Builder builder) { + super(builder); + } + private PBTestMessage() { + stringValue_ = ""; + intArray_ = emptyIntList(); + stringArray_ = com.google.protobuf.LazyStringArrayList.EMPTY; + personArray_ = java.util.Collections.emptyList(); + seq_ = emptyDoubleList(); + } + + @Override + @SuppressWarnings({"unused"}) + protected Object newInstance( + UnusedPrivateParameter unused) { + return new PBTestMessage(); + } + + @Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private PBTestMessage( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + case 8: { + + intValue_ = input.readInt32(); + break; + } + case 16: { + + longValue_ = input.readInt64(); + break; + } + case 29: { + + floatValue_ = input.readFloat(); + break; + } + case 33: { + + doubleValue_ = input.readDouble(); + break; + } + case 40: { + + boolValue_ = input.readBool(); + break; + } + case 50: { + String s = input.readStringRequireUtf8(); + + stringValue_ = s; + break; + } + case 58: { + com.google.protobuf.Int32Value.Builder subBuilder = null; + if (intOpt_ != null) { + subBuilder = intOpt_.toBuilder(); + } + intOpt_ = input.readMessage(com.google.protobuf.Int32Value.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(intOpt_); + intOpt_ = subBuilder.buildPartial(); + } + + break; + } + case 66: { + com.google.protobuf.Int64Value.Builder subBuilder = null; + if (longOpt_ != null) { + subBuilder = longOpt_.toBuilder(); + } + longOpt_ = input.readMessage(com.google.protobuf.Int64Value.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(longOpt_); + longOpt_ = subBuilder.buildPartial(); + } + + break; + } + case 74: { + com.google.protobuf.FloatValue.Builder subBuilder = null; + if (floatOpt_ != null) { + subBuilder = floatOpt_.toBuilder(); + } + floatOpt_ = input.readMessage(com.google.protobuf.FloatValue.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(floatOpt_); + floatOpt_ = subBuilder.buildPartial(); + } + + break; + } + case 82: { + com.google.protobuf.DoubleValue.Builder subBuilder = null; + if (doubleOpt_ != null) { + subBuilder = doubleOpt_.toBuilder(); + } + doubleOpt_ = input.readMessage(com.google.protobuf.DoubleValue.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(doubleOpt_); + doubleOpt_ = subBuilder.buildPartial(); + } + + break; + } + case 90: { + com.google.protobuf.BoolValue.Builder subBuilder = null; + if (boolOpt_ != null) { + subBuilder = boolOpt_.toBuilder(); + } + boolOpt_ = input.readMessage(com.google.protobuf.BoolValue.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(boolOpt_); + boolOpt_ = subBuilder.buildPartial(); + } + + break; + } + case 98: { + com.google.protobuf.StringValue.Builder subBuilder = null; + if (stringOpt_ != null) { + subBuilder = stringOpt_.toBuilder(); + } + stringOpt_ = input.readMessage(com.google.protobuf.StringValue.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(stringOpt_); + stringOpt_ = subBuilder.buildPartial(); + } + + break; + } + case 106: { + com.google.protobuf.Timestamp.Builder subBuilder = null; + if (time_ != null) { + subBuilder = time_.toBuilder(); + } + time_ = input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(time_); + time_ = subBuilder.buildPartial(); + } + + break; + } + case 114: { + com.google.protobuf.Timestamp.Builder subBuilder = null; + if (timeOpt_ != null) { + subBuilder = timeOpt_.toBuilder(); + } + timeOpt_ = input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(timeOpt_); + timeOpt_ = subBuilder.buildPartial(); + } + + break; + } + case 120: { + if (!((mutable_bitField0_ & 0x00000001) != 0)) { + intArray_ = newIntList(); + mutable_bitField0_ |= 0x00000001; + } + intArray_.addInt(input.readInt32()); + break; + } + case 122: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + if (!((mutable_bitField0_ & 0x00000001) != 0) && input.getBytesUntilLimit() > 0) { + intArray_ = newIntList(); + mutable_bitField0_ |= 0x00000001; + } + while (input.getBytesUntilLimit() > 0) { + intArray_.addInt(input.readInt32()); + } + input.popLimit(limit); + break; + } + case 130: { + String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000002) != 0)) { + stringArray_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000002; + } + stringArray_.add(s); + break; + } + case 138: { + if (!((mutable_bitField0_ & 0x00000004) != 0)) { + personArray_ = new java.util.ArrayList(); + mutable_bitField0_ |= 0x00000004; + } + personArray_.add( + input.readMessage(PBPerson.parser(), extensionRegistry)); + break; + } + case 145: { + if (!((mutable_bitField0_ & 0x00000008) != 0)) { + seq_ = newDoubleList(); + mutable_bitField0_ |= 0x00000008; + } + seq_.addDouble(input.readDouble()); + break; + } + case 146: { + int length = input.readRawVarint32(); + int limit = input.pushLimit(length); + if (!((mutable_bitField0_ & 0x00000008) != 0) && input.getBytesUntilLimit() > 0) { + seq_ = newDoubleList(); + mutable_bitField0_ |= 0x00000008; + } + while (input.getBytesUntilLimit() > 0) { + seq_.addDouble(input.readDouble()); + } + input.popLimit(limit); + break; + } + case 154: { + if (!((mutable_bitField0_ & 0x00000010) != 0)) { + stringStringKV_ = com.google.protobuf.MapField.newMapField( + StringStringKVDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000010; + } + com.google.protobuf.MapEntry + stringStringKV__ = input.readMessage( + StringStringKVDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); + stringStringKV_.getMutableMap().put( + stringStringKV__.getKey(), stringStringKV__.getValue()); + break; + } + case 162: { + if (!((mutable_bitField0_ & 0x00000020) != 0)) { + longStringKV_ = com.google.protobuf.MapField.newMapField( + LongStringKVDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000020; + } + com.google.protobuf.MapEntry + longStringKV__ = input.readMessage( + LongStringKVDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); + longStringKV_.getMutableMap().put( + longStringKV__.getKey(), longStringKV__.getValue()); + break; + } + case 170: { + if (!((mutable_bitField0_ & 0x00000040) != 0)) { + stringIntKV_ = com.google.protobuf.MapField.newMapField( + StringIntKVDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000040; + } + com.google.protobuf.MapEntry + stringIntKV__ = input.readMessage( + StringIntKVDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); + stringIntKV_.getMutableMap().put( + stringIntKV__.getKey(), stringIntKV__.getValue()); + break; + } + case 178: { + if (!((mutable_bitField0_ & 0x00000080) != 0)) { + longIntKV_ = com.google.protobuf.MapField.newMapField( + LongIntKVDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000080; + } + com.google.protobuf.MapEntry + longIntKV__ = input.readMessage( + LongIntKVDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); + longIntKV_.getMutableMap().put( + longIntKV__.getKey(), longIntKV__.getValue()); + break; + } + default: { + if (!parseUnknownField( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) != 0)) { + intArray_.makeImmutable(); // C + } + if (((mutable_bitField0_ & 0x00000002) != 0)) { + stringArray_ = stringArray_.getUnmodifiableView(); + } + if (((mutable_bitField0_ & 0x00000004) != 0)) { + personArray_ = java.util.Collections.unmodifiableList(personArray_); + } + if (((mutable_bitField0_ & 0x00000008) != 0)) { + seq_.makeImmutable(); // C + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ConversionTest.internal_static_PBTestMessage_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + @Override + protected com.google.protobuf.MapField internalGetMapField( + int number) { + switch (number) { + case 19: + return internalGetStringStringKV(); + case 20: + return internalGetLongStringKV(); + case 21: + return internalGetStringIntKV(); + case 22: + return internalGetLongIntKV(); + default: + throw new RuntimeException( + "Invalid map field number: " + number); + } + } + @Override + protected GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return ConversionTest.internal_static_PBTestMessage_fieldAccessorTable + .ensureFieldAccessorsInitialized( + PBTestMessage.class, Builder.class); + } + + public static final int INT_VALUE_FIELD_NUMBER = 1; + private int intValue_; + /** + * int32 int_value = 1; + * @return The intValue. + */ + @Override + public int getIntValue() { + return intValue_; + } + + public static final int LONG_VALUE_FIELD_NUMBER = 2; + private long longValue_; + /** + * int64 long_value = 2; + * @return The longValue. + */ + @Override + public long getLongValue() { + return longValue_; + } + + public static final int FLOAT_VALUE_FIELD_NUMBER = 3; + private float floatValue_; + /** + * float float_value = 3; + * @return The floatValue. + */ + @Override + public float getFloatValue() { + return floatValue_; + } + + public static final int DOUBLE_VALUE_FIELD_NUMBER = 4; + private double doubleValue_; + /** + * double double_value = 4; + * @return The doubleValue. + */ + @Override + public double getDoubleValue() { + return doubleValue_; + } + + public static final int BOOL_VALUE_FIELD_NUMBER = 5; + private boolean boolValue_; + /** + * bool bool_value = 5; + * @return The boolValue. + */ + @Override + public boolean getBoolValue() { + return boolValue_; + } + + public static final int STRING_VALUE_FIELD_NUMBER = 6; + private volatile Object stringValue_; + /** + * string string_value = 6; + * @return The stringValue. + */ + @Override + public String getStringValue() { + Object ref = stringValue_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + stringValue_ = s; + return s; + } + } + /** + * string string_value = 6; + * @return The bytes for stringValue. + */ + @Override + public com.google.protobuf.ByteString + getStringValueBytes() { + Object ref = stringValue_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (String) ref); + stringValue_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int INT_OPT_FIELD_NUMBER = 7; + private com.google.protobuf.Int32Value intOpt_; + /** + * .google.protobuf.Int32Value int_Opt = 7; + * @return Whether the intOpt field is set. + */ + @Override + public boolean hasIntOpt() { + return intOpt_ != null; + } + /** + * .google.protobuf.Int32Value int_Opt = 7; + * @return The intOpt. + */ + @Override + public com.google.protobuf.Int32Value getIntOpt() { + return intOpt_ == null ? com.google.protobuf.Int32Value.getDefaultInstance() : intOpt_; + } + /** + * .google.protobuf.Int32Value int_Opt = 7; + */ + @Override + public com.google.protobuf.Int32ValueOrBuilder getIntOptOrBuilder() { + return getIntOpt(); + } + + public static final int LONG_OPT_FIELD_NUMBER = 8; + private com.google.protobuf.Int64Value longOpt_; + /** + * .google.protobuf.Int64Value long_Opt = 8; + * @return Whether the longOpt field is set. + */ + @Override + public boolean hasLongOpt() { + return longOpt_ != null; + } + /** + * .google.protobuf.Int64Value long_Opt = 8; + * @return The longOpt. + */ + @Override + public com.google.protobuf.Int64Value getLongOpt() { + return longOpt_ == null ? com.google.protobuf.Int64Value.getDefaultInstance() : longOpt_; + } + /** + * .google.protobuf.Int64Value long_Opt = 8; + */ + @Override + public com.google.protobuf.Int64ValueOrBuilder getLongOptOrBuilder() { + return getLongOpt(); + } + + public static final int FLOAT_OPT_FIELD_NUMBER = 9; + private com.google.protobuf.FloatValue floatOpt_; + /** + * .google.protobuf.FloatValue float_Opt = 9; + * @return Whether the floatOpt field is set. + */ + @Override + public boolean hasFloatOpt() { + return floatOpt_ != null; + } + /** + * .google.protobuf.FloatValue float_Opt = 9; + * @return The floatOpt. + */ + @Override + public com.google.protobuf.FloatValue getFloatOpt() { + return floatOpt_ == null ? com.google.protobuf.FloatValue.getDefaultInstance() : floatOpt_; + } + /** + * .google.protobuf.FloatValue float_Opt = 9; + */ + @Override + public com.google.protobuf.FloatValueOrBuilder getFloatOptOrBuilder() { + return getFloatOpt(); + } + + public static final int DOUBLE_OPT_FIELD_NUMBER = 10; + private com.google.protobuf.DoubleValue doubleOpt_; + /** + * .google.protobuf.DoubleValue double_opt = 10; + * @return Whether the doubleOpt field is set. + */ + @Override + public boolean hasDoubleOpt() { + return doubleOpt_ != null; + } + /** + * .google.protobuf.DoubleValue double_opt = 10; + * @return The doubleOpt. + */ + @Override + public com.google.protobuf.DoubleValue getDoubleOpt() { + return doubleOpt_ == null ? com.google.protobuf.DoubleValue.getDefaultInstance() : doubleOpt_; + } + /** + * .google.protobuf.DoubleValue double_opt = 10; + */ + @Override + public com.google.protobuf.DoubleValueOrBuilder getDoubleOptOrBuilder() { + return getDoubleOpt(); + } + + public static final int BOOL_OPT_FIELD_NUMBER = 11; + private com.google.protobuf.BoolValue boolOpt_; + /** + * .google.protobuf.BoolValue bool_opt = 11; + * @return Whether the boolOpt field is set. + */ + @Override + public boolean hasBoolOpt() { + return boolOpt_ != null; + } + /** + * .google.protobuf.BoolValue bool_opt = 11; + * @return The boolOpt. + */ + @Override + public com.google.protobuf.BoolValue getBoolOpt() { + return boolOpt_ == null ? com.google.protobuf.BoolValue.getDefaultInstance() : boolOpt_; + } + /** + * .google.protobuf.BoolValue bool_opt = 11; + */ + @Override + public com.google.protobuf.BoolValueOrBuilder getBoolOptOrBuilder() { + return getBoolOpt(); + } + + public static final int STRING_OPT_FIELD_NUMBER = 12; + private com.google.protobuf.StringValue stringOpt_; + /** + * .google.protobuf.StringValue string_opt = 12; + * @return Whether the stringOpt field is set. + */ + @Override + public boolean hasStringOpt() { + return stringOpt_ != null; + } + /** + * .google.protobuf.StringValue string_opt = 12; + * @return The stringOpt. + */ + @Override + public com.google.protobuf.StringValue getStringOpt() { + return stringOpt_ == null ? com.google.protobuf.StringValue.getDefaultInstance() : stringOpt_; + } + /** + * .google.protobuf.StringValue string_opt = 12; + */ + @Override + public com.google.protobuf.StringValueOrBuilder getStringOptOrBuilder() { + return getStringOpt(); + } + + public static final int TIME_FIELD_NUMBER = 13; + private com.google.protobuf.Timestamp time_; + /** + * .google.protobuf.Timestamp time = 13; + * @return Whether the time field is set. + */ + @Override + public boolean hasTime() { + return time_ != null; + } + /** + * .google.protobuf.Timestamp time = 13; + * @return The time. + */ + @Override + public com.google.protobuf.Timestamp getTime() { + return time_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : time_; + } + /** + * .google.protobuf.Timestamp time = 13; + */ + @Override + public com.google.protobuf.TimestampOrBuilder getTimeOrBuilder() { + return getTime(); + } + + public static final int TIME_OPT_FIELD_NUMBER = 14; + private com.google.protobuf.Timestamp timeOpt_; + /** + * .google.protobuf.Timestamp time_opt = 14; + * @return Whether the timeOpt field is set. + */ + @Override + public boolean hasTimeOpt() { + return timeOpt_ != null; + } + /** + * .google.protobuf.Timestamp time_opt = 14; + * @return The timeOpt. + */ + @Override + public com.google.protobuf.Timestamp getTimeOpt() { + return timeOpt_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : timeOpt_; + } + /** + * .google.protobuf.Timestamp time_opt = 14; + */ + @Override + public com.google.protobuf.TimestampOrBuilder getTimeOptOrBuilder() { + return getTimeOpt(); + } + + public static final int INT_ARRAY_FIELD_NUMBER = 15; + private com.google.protobuf.Internal.IntList intArray_; + /** + * repeated int32 int_array = 15; + * @return A list containing the intArray. + */ + @Override + public java.util.List + getIntArrayList() { + return intArray_; + } + /** + * repeated int32 int_array = 15; + * @return The count of intArray. + */ + public int getIntArrayCount() { + return intArray_.size(); + } + /** + * repeated int32 int_array = 15; + * @param index The index of the element to return. + * @return The intArray at the given index. + */ + public int getIntArray(int index) { + return intArray_.getInt(index); + } + private int intArrayMemoizedSerializedSize = -1; + + public static final int STRING_ARRAY_FIELD_NUMBER = 16; + private com.google.protobuf.LazyStringList stringArray_; + /** + * repeated string string_array = 16; + * @return A list containing the stringArray. + */ + public com.google.protobuf.ProtocolStringList + getStringArrayList() { + return stringArray_; + } + /** + * repeated string string_array = 16; + * @return The count of stringArray. + */ + public int getStringArrayCount() { + return stringArray_.size(); + } + /** + * repeated string string_array = 16; + * @param index The index of the element to return. + * @return The stringArray at the given index. + */ + public String getStringArray(int index) { + return stringArray_.get(index); + } + /** + * repeated string string_array = 16; + * @param index The index of the value to return. + * @return The bytes of the stringArray at the given index. + */ + public com.google.protobuf.ByteString + getStringArrayBytes(int index) { + return stringArray_.getByteString(index); + } + + public static final int PERSON_ARRAY_FIELD_NUMBER = 17; + private java.util.List personArray_; + /** + * repeated .PBPerson person_array = 17; + */ + @Override + public java.util.List getPersonArrayList() { + return personArray_; + } + /** + * repeated .PBPerson person_array = 17; + */ + @Override + public java.util.List + getPersonArrayOrBuilderList() { + return personArray_; + } + /** + * repeated .PBPerson person_array = 17; + */ + @Override + public int getPersonArrayCount() { + return personArray_.size(); + } + /** + * repeated .PBPerson person_array = 17; + */ + @Override + public PBPerson getPersonArray(int index) { + return personArray_.get(index); + } + /** + * repeated .PBPerson person_array = 17; + */ + @Override + public PBPersonOrBuilder getPersonArrayOrBuilder( + int index) { + return personArray_.get(index); + } + + public static final int SEQ_FIELD_NUMBER = 18; + private com.google.protobuf.Internal.DoubleList seq_; + /** + * repeated double seq = 18; + * @return A list containing the seq. + */ + @Override + public java.util.List + getSeqList() { + return seq_; + } + /** + * repeated double seq = 18; + * @return The count of seq. + */ + public int getSeqCount() { + return seq_.size(); + } + /** + * repeated double seq = 18; + * @param index The index of the element to return. + * @return The seq at the given index. + */ + public double getSeq(int index) { + return seq_.getDouble(index); + } + private int seqMemoizedSerializedSize = -1; + + public static final int STRING_STRING_K_V_FIELD_NUMBER = 19; + private static final class StringStringKVDefaultEntryHolder { + static final com.google.protobuf.MapEntry< + String, String> defaultEntry = + com.google.protobuf.MapEntry + .newDefaultInstance( + ConversionTest.internal_static_PBTestMessage_StringStringKVEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.STRING, + "", + com.google.protobuf.WireFormat.FieldType.STRING, + ""); + } + private com.google.protobuf.MapField< + String, String> stringStringKV_; + private com.google.protobuf.MapField + internalGetStringStringKV() { + if (stringStringKV_ == null) { + return com.google.protobuf.MapField.emptyMapField( + StringStringKVDefaultEntryHolder.defaultEntry); + } + return stringStringKV_; + } + + public int getStringStringKVCount() { + return internalGetStringStringKV().getMap().size(); + } + /** + * map<string, string> string_string_k_v = 19; + */ + + @Override + public boolean containsStringStringKV( + String key) { + if (key == null) { throw new NullPointerException(); } + return internalGetStringStringKV().getMap().containsKey(key); + } + /** + * Use {@link #getStringStringKVMap()} instead. + */ + @Override + @Deprecated + public java.util.Map getStringStringKV() { + return getStringStringKVMap(); + } + /** + * map<string, string> string_string_k_v = 19; + */ + @Override + + public java.util.Map getStringStringKVMap() { + return internalGetStringStringKV().getMap(); + } + /** + * map<string, string> string_string_k_v = 19; + */ + @Override + + public String getStringStringKVOrDefault( + String key, + String defaultValue) { + if (key == null) { throw new NullPointerException(); } + java.util.Map map = + internalGetStringStringKV().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + * map<string, string> string_string_k_v = 19; + */ + @Override + + public String getStringStringKVOrThrow( + String key) { + if (key == null) { throw new NullPointerException(); } + java.util.Map map = + internalGetStringStringKV().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); + } + + public static final int LONG_STRING_K_V_FIELD_NUMBER = 20; + private static final class LongStringKVDefaultEntryHolder { + static final com.google.protobuf.MapEntry< + Long, String> defaultEntry = + com.google.protobuf.MapEntry + .newDefaultInstance( + ConversionTest.internal_static_PBTestMessage_LongStringKVEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.INT64, + 0L, + com.google.protobuf.WireFormat.FieldType.STRING, + ""); + } + private com.google.protobuf.MapField< + Long, String> longStringKV_; + private com.google.protobuf.MapField + internalGetLongStringKV() { + if (longStringKV_ == null) { + return com.google.protobuf.MapField.emptyMapField( + LongStringKVDefaultEntryHolder.defaultEntry); + } + return longStringKV_; + } + + public int getLongStringKVCount() { + return internalGetLongStringKV().getMap().size(); + } + /** + * map<int64, string> long_string_k_v = 20; + */ + + @Override + public boolean containsLongStringKV( + long key) { + + return internalGetLongStringKV().getMap().containsKey(key); + } + /** + * Use {@link #getLongStringKVMap()} instead. + */ + @Override + @Deprecated + public java.util.Map getLongStringKV() { + return getLongStringKVMap(); + } + /** + * map<int64, string> long_string_k_v = 20; + */ + @Override + + public java.util.Map getLongStringKVMap() { + return internalGetLongStringKV().getMap(); + } + /** + * map<int64, string> long_string_k_v = 20; + */ + @Override + + public String getLongStringKVOrDefault( + long key, + String defaultValue) { + + java.util.Map map = + internalGetLongStringKV().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + * map<int64, string> long_string_k_v = 20; + */ + @Override + + public String getLongStringKVOrThrow( + long key) { + + java.util.Map map = + internalGetLongStringKV().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); + } + + public static final int STRING_INT_K_V_FIELD_NUMBER = 21; + private static final class StringIntKVDefaultEntryHolder { + static final com.google.protobuf.MapEntry< + String, Integer> defaultEntry = + com.google.protobuf.MapEntry + .newDefaultInstance( + ConversionTest.internal_static_PBTestMessage_StringIntKVEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.STRING, + "", + com.google.protobuf.WireFormat.FieldType.INT32, + 0); + } + private com.google.protobuf.MapField< + String, Integer> stringIntKV_; + private com.google.protobuf.MapField + internalGetStringIntKV() { + if (stringIntKV_ == null) { + return com.google.protobuf.MapField.emptyMapField( + StringIntKVDefaultEntryHolder.defaultEntry); + } + return stringIntKV_; + } + + public int getStringIntKVCount() { + return internalGetStringIntKV().getMap().size(); + } + /** + * map<string, int32> string_int_k_v = 21; + */ + + @Override + public boolean containsStringIntKV( + String key) { + if (key == null) { throw new NullPointerException(); } + return internalGetStringIntKV().getMap().containsKey(key); + } + /** + * Use {@link #getStringIntKVMap()} instead. + */ + @Override + @Deprecated + public java.util.Map getStringIntKV() { + return getStringIntKVMap(); + } + /** + * map<string, int32> string_int_k_v = 21; + */ + @Override + + public java.util.Map getStringIntKVMap() { + return internalGetStringIntKV().getMap(); + } + /** + * map<string, int32> string_int_k_v = 21; + */ + @Override + + public int getStringIntKVOrDefault( + String key, + int defaultValue) { + if (key == null) { throw new NullPointerException(); } + java.util.Map map = + internalGetStringIntKV().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + * map<string, int32> string_int_k_v = 21; + */ + @Override + + public int getStringIntKVOrThrow( + String key) { + if (key == null) { throw new NullPointerException(); } + java.util.Map map = + internalGetStringIntKV().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); + } + + public static final int LONG_INT_K_V_FIELD_NUMBER = 22; + private static final class LongIntKVDefaultEntryHolder { + static final com.google.protobuf.MapEntry< + Long, Integer> defaultEntry = + com.google.protobuf.MapEntry + .newDefaultInstance( + ConversionTest.internal_static_PBTestMessage_LongIntKVEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.INT64, + 0L, + com.google.protobuf.WireFormat.FieldType.INT32, + 0); + } + private com.google.protobuf.MapField< + Long, Integer> longIntKV_; + private com.google.protobuf.MapField + internalGetLongIntKV() { + if (longIntKV_ == null) { + return com.google.protobuf.MapField.emptyMapField( + LongIntKVDefaultEntryHolder.defaultEntry); + } + return longIntKV_; + } + + public int getLongIntKVCount() { + return internalGetLongIntKV().getMap().size(); + } + /** + * map<int64, int32> long_int_k_v = 22; + */ + + @Override + public boolean containsLongIntKV( + long key) { + + return internalGetLongIntKV().getMap().containsKey(key); + } + /** + * Use {@link #getLongIntKVMap()} instead. + */ + @Override + @Deprecated + public java.util.Map getLongIntKV() { + return getLongIntKVMap(); + } + /** + * map<int64, int32> long_int_k_v = 22; + */ + @Override + + public java.util.Map getLongIntKVMap() { + return internalGetLongIntKV().getMap(); + } + /** + * map<int64, int32> long_int_k_v = 22; + */ + @Override + + public int getLongIntKVOrDefault( + long key, + int defaultValue) { + + java.util.Map map = + internalGetLongIntKV().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + * map<int64, int32> long_int_k_v = 22; + */ + @Override + + public int getLongIntKVOrThrow( + long key) { + + java.util.Map map = + internalGetLongIntKV().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); + } + + private byte memoizedIsInitialized = -1; + @Override + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + @Override + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (intValue_ != 0) { + output.writeInt32(1, intValue_); + } + if (longValue_ != 0L) { + output.writeInt64(2, longValue_); + } + if (floatValue_ != 0F) { + output.writeFloat(3, floatValue_); + } + if (doubleValue_ != 0D) { + output.writeDouble(4, doubleValue_); + } + if (boolValue_ != false) { + output.writeBool(5, boolValue_); + } + if (!getStringValueBytes().isEmpty()) { + GeneratedMessageV3.writeString(output, 6, stringValue_); + } + if (intOpt_ != null) { + output.writeMessage(7, getIntOpt()); + } + if (longOpt_ != null) { + output.writeMessage(8, getLongOpt()); + } + if (floatOpt_ != null) { + output.writeMessage(9, getFloatOpt()); + } + if (doubleOpt_ != null) { + output.writeMessage(10, getDoubleOpt()); + } + if (boolOpt_ != null) { + output.writeMessage(11, getBoolOpt()); + } + if (stringOpt_ != null) { + output.writeMessage(12, getStringOpt()); + } + if (time_ != null) { + output.writeMessage(13, getTime()); + } + if (timeOpt_ != null) { + output.writeMessage(14, getTimeOpt()); + } + if (getIntArrayList().size() > 0) { + output.writeUInt32NoTag(122); + output.writeUInt32NoTag(intArrayMemoizedSerializedSize); + } + for (int i = 0; i < intArray_.size(); i++) { + output.writeInt32NoTag(intArray_.getInt(i)); + } + for (int i = 0; i < stringArray_.size(); i++) { + GeneratedMessageV3.writeString(output, 16, stringArray_.getRaw(i)); + } + for (int i = 0; i < personArray_.size(); i++) { + output.writeMessage(17, personArray_.get(i)); + } + if (getSeqList().size() > 0) { + output.writeUInt32NoTag(146); + output.writeUInt32NoTag(seqMemoizedSerializedSize); + } + for (int i = 0; i < seq_.size(); i++) { + output.writeDoubleNoTag(seq_.getDouble(i)); + } + GeneratedMessageV3 + .serializeStringMapTo( + output, + internalGetStringStringKV(), + StringStringKVDefaultEntryHolder.defaultEntry, + 19); + GeneratedMessageV3 + .serializeLongMapTo( + output, + internalGetLongStringKV(), + LongStringKVDefaultEntryHolder.defaultEntry, + 20); + GeneratedMessageV3 + .serializeStringMapTo( + output, + internalGetStringIntKV(), + StringIntKVDefaultEntryHolder.defaultEntry, + 21); + GeneratedMessageV3 + .serializeLongMapTo( + output, + internalGetLongIntKV(), + LongIntKVDefaultEntryHolder.defaultEntry, + 22); + unknownFields.writeTo(output); + } + + @Override + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (intValue_ != 0) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, intValue_); + } + if (longValue_ != 0L) { + size += com.google.protobuf.CodedOutputStream + .computeInt64Size(2, longValue_); + } + if (floatValue_ != 0F) { + size += com.google.protobuf.CodedOutputStream + .computeFloatSize(3, floatValue_); + } + if (doubleValue_ != 0D) { + size += com.google.protobuf.CodedOutputStream + .computeDoubleSize(4, doubleValue_); + } + if (boolValue_ != false) { + size += com.google.protobuf.CodedOutputStream + .computeBoolSize(5, boolValue_); + } + if (!getStringValueBytes().isEmpty()) { + size += GeneratedMessageV3.computeStringSize(6, stringValue_); + } + if (intOpt_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(7, getIntOpt()); + } + if (longOpt_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(8, getLongOpt()); + } + if (floatOpt_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(9, getFloatOpt()); + } + if (doubleOpt_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(10, getDoubleOpt()); + } + if (boolOpt_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(11, getBoolOpt()); + } + if (stringOpt_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(12, getStringOpt()); + } + if (time_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(13, getTime()); + } + if (timeOpt_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(14, getTimeOpt()); + } + { + int dataSize = 0; + for (int i = 0; i < intArray_.size(); i++) { + dataSize += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(intArray_.getInt(i)); + } + size += dataSize; + if (!getIntArrayList().isEmpty()) { + size += 1; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + intArrayMemoizedSerializedSize = dataSize; + } + { + int dataSize = 0; + for (int i = 0; i < stringArray_.size(); i++) { + dataSize += computeStringSizeNoTag(stringArray_.getRaw(i)); + } + size += dataSize; + size += 2 * getStringArrayList().size(); + } + for (int i = 0; i < personArray_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(17, personArray_.get(i)); + } + { + int dataSize = 0; + dataSize = 8 * getSeqList().size(); + size += dataSize; + if (!getSeqList().isEmpty()) { + size += 2; + size += com.google.protobuf.CodedOutputStream + .computeInt32SizeNoTag(dataSize); + } + seqMemoizedSerializedSize = dataSize; + } + for (java.util.Map.Entry entry + : internalGetStringStringKV().getMap().entrySet()) { + com.google.protobuf.MapEntry + stringStringKV__ = StringStringKVDefaultEntryHolder.defaultEntry.newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(19, stringStringKV__); + } + for (java.util.Map.Entry entry + : internalGetLongStringKV().getMap().entrySet()) { + com.google.protobuf.MapEntry + longStringKV__ = LongStringKVDefaultEntryHolder.defaultEntry.newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(20, longStringKV__); + } + for (java.util.Map.Entry entry + : internalGetStringIntKV().getMap().entrySet()) { + com.google.protobuf.MapEntry + stringIntKV__ = StringIntKVDefaultEntryHolder.defaultEntry.newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(21, stringIntKV__); + } + for (java.util.Map.Entry entry + : internalGetLongIntKV().getMap().entrySet()) { + com.google.protobuf.MapEntry + longIntKV__ = LongIntKVDefaultEntryHolder.defaultEntry.newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(22, longIntKV__); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof PBTestMessage)) { + return super.equals(obj); + } + PBTestMessage other = (PBTestMessage) obj; + + if (getIntValue() + != other.getIntValue()) return false; + if (getLongValue() + != other.getLongValue()) return false; + if (Float.floatToIntBits(getFloatValue()) + != Float.floatToIntBits( + other.getFloatValue())) return false; + if (Double.doubleToLongBits(getDoubleValue()) + != Double.doubleToLongBits( + other.getDoubleValue())) return false; + if (getBoolValue() + != other.getBoolValue()) return false; + if (!getStringValue() + .equals(other.getStringValue())) return false; + if (hasIntOpt() != other.hasIntOpt()) return false; + if (hasIntOpt()) { + if (!getIntOpt() + .equals(other.getIntOpt())) return false; + } + if (hasLongOpt() != other.hasLongOpt()) return false; + if (hasLongOpt()) { + if (!getLongOpt() + .equals(other.getLongOpt())) return false; + } + if (hasFloatOpt() != other.hasFloatOpt()) return false; + if (hasFloatOpt()) { + if (!getFloatOpt() + .equals(other.getFloatOpt())) return false; + } + if (hasDoubleOpt() != other.hasDoubleOpt()) return false; + if (hasDoubleOpt()) { + if (!getDoubleOpt() + .equals(other.getDoubleOpt())) return false; + } + if (hasBoolOpt() != other.hasBoolOpt()) return false; + if (hasBoolOpt()) { + if (!getBoolOpt() + .equals(other.getBoolOpt())) return false; + } + if (hasStringOpt() != other.hasStringOpt()) return false; + if (hasStringOpt()) { + if (!getStringOpt() + .equals(other.getStringOpt())) return false; + } + if (hasTime() != other.hasTime()) return false; + if (hasTime()) { + if (!getTime() + .equals(other.getTime())) return false; + } + if (hasTimeOpt() != other.hasTimeOpt()) return false; + if (hasTimeOpt()) { + if (!getTimeOpt() + .equals(other.getTimeOpt())) return false; + } + if (!getIntArrayList() + .equals(other.getIntArrayList())) return false; + if (!getStringArrayList() + .equals(other.getStringArrayList())) return false; + if (!getPersonArrayList() + .equals(other.getPersonArrayList())) return false; + if (!getSeqList() + .equals(other.getSeqList())) return false; + if (!internalGetStringStringKV().equals( + other.internalGetStringStringKV())) return false; + if (!internalGetLongStringKV().equals( + other.internalGetLongStringKV())) return false; + if (!internalGetStringIntKV().equals( + other.internalGetStringIntKV())) return false; + if (!internalGetLongIntKV().equals( + other.internalGetLongIntKV())) return false; + if (!unknownFields.equals(other.unknownFields)) return false; + return true; + } + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + INT_VALUE_FIELD_NUMBER; + hash = (53 * hash) + getIntValue(); + hash = (37 * hash) + LONG_VALUE_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashLong( + getLongValue()); + hash = (37 * hash) + FLOAT_VALUE_FIELD_NUMBER; + hash = (53 * hash) + Float.floatToIntBits( + getFloatValue()); + hash = (37 * hash) + DOUBLE_VALUE_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashLong( + Double.doubleToLongBits(getDoubleValue())); + hash = (37 * hash) + BOOL_VALUE_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( + getBoolValue()); + hash = (37 * hash) + STRING_VALUE_FIELD_NUMBER; + hash = (53 * hash) + getStringValue().hashCode(); + if (hasIntOpt()) { + hash = (37 * hash) + INT_OPT_FIELD_NUMBER; + hash = (53 * hash) + getIntOpt().hashCode(); + } + if (hasLongOpt()) { + hash = (37 * hash) + LONG_OPT_FIELD_NUMBER; + hash = (53 * hash) + getLongOpt().hashCode(); + } + if (hasFloatOpt()) { + hash = (37 * hash) + FLOAT_OPT_FIELD_NUMBER; + hash = (53 * hash) + getFloatOpt().hashCode(); + } + if (hasDoubleOpt()) { + hash = (37 * hash) + DOUBLE_OPT_FIELD_NUMBER; + hash = (53 * hash) + getDoubleOpt().hashCode(); + } + if (hasBoolOpt()) { + hash = (37 * hash) + BOOL_OPT_FIELD_NUMBER; + hash = (53 * hash) + getBoolOpt().hashCode(); + } + if (hasStringOpt()) { + hash = (37 * hash) + STRING_OPT_FIELD_NUMBER; + hash = (53 * hash) + getStringOpt().hashCode(); + } + if (hasTime()) { + hash = (37 * hash) + TIME_FIELD_NUMBER; + hash = (53 * hash) + getTime().hashCode(); + } + if (hasTimeOpt()) { + hash = (37 * hash) + TIME_OPT_FIELD_NUMBER; + hash = (53 * hash) + getTimeOpt().hashCode(); + } + if (getIntArrayCount() > 0) { + hash = (37 * hash) + INT_ARRAY_FIELD_NUMBER; + hash = (53 * hash) + getIntArrayList().hashCode(); + } + if (getStringArrayCount() > 0) { + hash = (37 * hash) + STRING_ARRAY_FIELD_NUMBER; + hash = (53 * hash) + getStringArrayList().hashCode(); + } + if (getPersonArrayCount() > 0) { + hash = (37 * hash) + PERSON_ARRAY_FIELD_NUMBER; + hash = (53 * hash) + getPersonArrayList().hashCode(); + } + if (getSeqCount() > 0) { + hash = (37 * hash) + SEQ_FIELD_NUMBER; + hash = (53 * hash) + getSeqList().hashCode(); + } + if (!internalGetStringStringKV().getMap().isEmpty()) { + hash = (37 * hash) + STRING_STRING_K_V_FIELD_NUMBER; + hash = (53 * hash) + internalGetStringStringKV().hashCode(); + } + if (!internalGetLongStringKV().getMap().isEmpty()) { + hash = (37 * hash) + LONG_STRING_K_V_FIELD_NUMBER; + hash = (53 * hash) + internalGetLongStringKV().hashCode(); + } + if (!internalGetStringIntKV().getMap().isEmpty()) { + hash = (37 * hash) + STRING_INT_K_V_FIELD_NUMBER; + hash = (53 * hash) + internalGetStringIntKV().hashCode(); + } + if (!internalGetLongIntKV().getMap().isEmpty()) { + hash = (37 * hash) + LONG_INT_K_V_FIELD_NUMBER; + hash = (53 * hash) + internalGetLongIntKV().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static PBTestMessage parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static PBTestMessage parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static PBTestMessage parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static PBTestMessage parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static PBTestMessage parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static PBTestMessage parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static PBTestMessage parseFrom(java.io.InputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static PBTestMessage parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static PBTestMessage parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static PBTestMessage parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static PBTestMessage parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static PBTestMessage parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + @Override + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(PBTestMessage prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + @Override + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @Override + protected Builder newBuilderForType( + GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code PBTestMessage} + */ + public static final class Builder extends + GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:PBTestMessage) + PBTestMessageOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ConversionTest.internal_static_PBTestMessage_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField( + int number) { + switch (number) { + case 19: + return internalGetStringStringKV(); + case 20: + return internalGetLongStringKV(); + case 21: + return internalGetStringIntKV(); + case 22: + return internalGetLongIntKV(); + default: + throw new RuntimeException( + "Invalid map field number: " + number); + } + } + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMutableMapField( + int number) { + switch (number) { + case 19: + return internalGetMutableStringStringKV(); + case 20: + return internalGetMutableLongStringKV(); + case 21: + return internalGetMutableStringIntKV(); + case 22: + return internalGetMutableLongIntKV(); + default: + throw new RuntimeException( + "Invalid map field number: " + number); + } + } + @Override + protected GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return ConversionTest.internal_static_PBTestMessage_fieldAccessorTable + .ensureFieldAccessorsInitialized( + PBTestMessage.class, Builder.class); + } + + // Construct using pbconverts.ConversionTest.PBTestMessage.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (GeneratedMessageV3 + .alwaysUseFieldBuilders) { + getPersonArrayFieldBuilder(); + } + } + @Override + public Builder clear() { + super.clear(); + intValue_ = 0; + + longValue_ = 0L; + + floatValue_ = 0F; + + doubleValue_ = 0D; + + boolValue_ = false; + + stringValue_ = ""; + + if (intOptBuilder_ == null) { + intOpt_ = null; + } else { + intOpt_ = null; + intOptBuilder_ = null; + } + if (longOptBuilder_ == null) { + longOpt_ = null; + } else { + longOpt_ = null; + longOptBuilder_ = null; + } + if (floatOptBuilder_ == null) { + floatOpt_ = null; + } else { + floatOpt_ = null; + floatOptBuilder_ = null; + } + if (doubleOptBuilder_ == null) { + doubleOpt_ = null; + } else { + doubleOpt_ = null; + doubleOptBuilder_ = null; + } + if (boolOptBuilder_ == null) { + boolOpt_ = null; + } else { + boolOpt_ = null; + boolOptBuilder_ = null; + } + if (stringOptBuilder_ == null) { + stringOpt_ = null; + } else { + stringOpt_ = null; + stringOptBuilder_ = null; + } + if (timeBuilder_ == null) { + time_ = null; + } else { + time_ = null; + timeBuilder_ = null; + } + if (timeOptBuilder_ == null) { + timeOpt_ = null; + } else { + timeOpt_ = null; + timeOptBuilder_ = null; + } + intArray_ = emptyIntList(); + bitField0_ = (bitField0_ & ~0x00000001); + stringArray_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000002); + if (personArrayBuilder_ == null) { + personArray_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000004); + } else { + personArrayBuilder_.clear(); + } + seq_ = emptyDoubleList(); + bitField0_ = (bitField0_ & ~0x00000008); + internalGetMutableStringStringKV().clear(); + internalGetMutableLongStringKV().clear(); + internalGetMutableStringIntKV().clear(); + internalGetMutableLongIntKV().clear(); + return this; + } + + @Override + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return ConversionTest.internal_static_PBTestMessage_descriptor; + } + + @Override + public PBTestMessage getDefaultInstanceForType() { + return PBTestMessage.getDefaultInstance(); + } + + @Override + public PBTestMessage build() { + PBTestMessage result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + @Override + public PBTestMessage buildPartial() { + PBTestMessage result = new PBTestMessage(this); + int from_bitField0_ = bitField0_; + result.intValue_ = intValue_; + result.longValue_ = longValue_; + result.floatValue_ = floatValue_; + result.doubleValue_ = doubleValue_; + result.boolValue_ = boolValue_; + result.stringValue_ = stringValue_; + if (intOptBuilder_ == null) { + result.intOpt_ = intOpt_; + } else { + result.intOpt_ = intOptBuilder_.build(); + } + if (longOptBuilder_ == null) { + result.longOpt_ = longOpt_; + } else { + result.longOpt_ = longOptBuilder_.build(); + } + if (floatOptBuilder_ == null) { + result.floatOpt_ = floatOpt_; + } else { + result.floatOpt_ = floatOptBuilder_.build(); + } + if (doubleOptBuilder_ == null) { + result.doubleOpt_ = doubleOpt_; + } else { + result.doubleOpt_ = doubleOptBuilder_.build(); + } + if (boolOptBuilder_ == null) { + result.boolOpt_ = boolOpt_; + } else { + result.boolOpt_ = boolOptBuilder_.build(); + } + if (stringOptBuilder_ == null) { + result.stringOpt_ = stringOpt_; + } else { + result.stringOpt_ = stringOptBuilder_.build(); + } + if (timeBuilder_ == null) { + result.time_ = time_; + } else { + result.time_ = timeBuilder_.build(); + } + if (timeOptBuilder_ == null) { + result.timeOpt_ = timeOpt_; + } else { + result.timeOpt_ = timeOptBuilder_.build(); + } + if (((bitField0_ & 0x00000001) != 0)) { + intArray_.makeImmutable(); + bitField0_ = (bitField0_ & ~0x00000001); + } + result.intArray_ = intArray_; + if (((bitField0_ & 0x00000002) != 0)) { + stringArray_ = stringArray_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000002); + } + result.stringArray_ = stringArray_; + if (personArrayBuilder_ == null) { + if (((bitField0_ & 0x00000004) != 0)) { + personArray_ = java.util.Collections.unmodifiableList(personArray_); + bitField0_ = (bitField0_ & ~0x00000004); + } + result.personArray_ = personArray_; + } else { + result.personArray_ = personArrayBuilder_.build(); + } + if (((bitField0_ & 0x00000008) != 0)) { + seq_.makeImmutable(); + bitField0_ = (bitField0_ & ~0x00000008); + } + result.seq_ = seq_; + result.stringStringKV_ = internalGetStringStringKV(); + result.stringStringKV_.makeImmutable(); + result.longStringKV_ = internalGetLongStringKV(); + result.longStringKV_.makeImmutable(); + result.stringIntKV_ = internalGetStringIntKV(); + result.stringIntKV_.makeImmutable(); + result.longIntKV_ = internalGetLongIntKV(); + result.longIntKV_.makeImmutable(); + onBuilt(); + return result; + } + + @Override + public Builder clone() { + return super.clone(); + } + @Override + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return super.setField(field, value); + } + @Override + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return super.clearField(field); + } + @Override + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return super.clearOneof(oneof); + } + @Override + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, Object value) { + return super.setRepeatedField(field, index, value); + } + @Override + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return super.addRepeatedField(field, value); + } + @Override + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof PBTestMessage) { + return mergeFrom((PBTestMessage)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(PBTestMessage other) { + if (other == PBTestMessage.getDefaultInstance()) return this; + if (other.getIntValue() != 0) { + setIntValue(other.getIntValue()); + } + if (other.getLongValue() != 0L) { + setLongValue(other.getLongValue()); + } + if (other.getFloatValue() != 0F) { + setFloatValue(other.getFloatValue()); + } + if (other.getDoubleValue() != 0D) { + setDoubleValue(other.getDoubleValue()); + } + if (other.getBoolValue() != false) { + setBoolValue(other.getBoolValue()); + } + if (!other.getStringValue().isEmpty()) { + stringValue_ = other.stringValue_; + onChanged(); + } + if (other.hasIntOpt()) { + mergeIntOpt(other.getIntOpt()); + } + if (other.hasLongOpt()) { + mergeLongOpt(other.getLongOpt()); + } + if (other.hasFloatOpt()) { + mergeFloatOpt(other.getFloatOpt()); + } + if (other.hasDoubleOpt()) { + mergeDoubleOpt(other.getDoubleOpt()); + } + if (other.hasBoolOpt()) { + mergeBoolOpt(other.getBoolOpt()); + } + if (other.hasStringOpt()) { + mergeStringOpt(other.getStringOpt()); + } + if (other.hasTime()) { + mergeTime(other.getTime()); + } + if (other.hasTimeOpt()) { + mergeTimeOpt(other.getTimeOpt()); + } + if (!other.intArray_.isEmpty()) { + if (intArray_.isEmpty()) { + intArray_ = other.intArray_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureIntArrayIsMutable(); + intArray_.addAll(other.intArray_); + } + onChanged(); + } + if (!other.stringArray_.isEmpty()) { + if (stringArray_.isEmpty()) { + stringArray_ = other.stringArray_; + bitField0_ = (bitField0_ & ~0x00000002); + } else { + ensureStringArrayIsMutable(); + stringArray_.addAll(other.stringArray_); + } + onChanged(); + } + if (personArrayBuilder_ == null) { + if (!other.personArray_.isEmpty()) { + if (personArray_.isEmpty()) { + personArray_ = other.personArray_; + bitField0_ = (bitField0_ & ~0x00000004); + } else { + ensurePersonArrayIsMutable(); + personArray_.addAll(other.personArray_); + } + onChanged(); + } + } else { + if (!other.personArray_.isEmpty()) { + if (personArrayBuilder_.isEmpty()) { + personArrayBuilder_.dispose(); + personArrayBuilder_ = null; + personArray_ = other.personArray_; + bitField0_ = (bitField0_ & ~0x00000004); + personArrayBuilder_ = + GeneratedMessageV3.alwaysUseFieldBuilders ? + getPersonArrayFieldBuilder() : null; + } else { + personArrayBuilder_.addAllMessages(other.personArray_); + } + } + } + if (!other.seq_.isEmpty()) { + if (seq_.isEmpty()) { + seq_ = other.seq_; + bitField0_ = (bitField0_ & ~0x00000008); + } else { + ensureSeqIsMutable(); + seq_.addAll(other.seq_); + } + onChanged(); + } + internalGetMutableStringStringKV().mergeFrom( + other.internalGetStringStringKV()); + internalGetMutableLongStringKV().mergeFrom( + other.internalGetLongStringKV()); + internalGetMutableStringIntKV().mergeFrom( + other.internalGetStringIntKV()); + internalGetMutableLongIntKV().mergeFrom( + other.internalGetLongIntKV()); + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + @Override + public final boolean isInitialized() { + return true; + } + + @Override + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + PBTestMessage parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (PBTestMessage) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + private int intValue_ ; + /** + * int32 int_value = 1; + * @return The intValue. + */ + @Override + public int getIntValue() { + return intValue_; + } + /** + * int32 int_value = 1; + * @param value The intValue to set. + * @return This builder for chaining. + */ + public Builder setIntValue(int value) { + + intValue_ = value; + onChanged(); + return this; + } + /** + * int32 int_value = 1; + * @return This builder for chaining. + */ + public Builder clearIntValue() { + + intValue_ = 0; + onChanged(); + return this; + } + + private long longValue_ ; + /** + * int64 long_value = 2; + * @return The longValue. + */ + @Override + public long getLongValue() { + return longValue_; + } + /** + * int64 long_value = 2; + * @param value The longValue to set. + * @return This builder for chaining. + */ + public Builder setLongValue(long value) { + + longValue_ = value; + onChanged(); + return this; + } + /** + * int64 long_value = 2; + * @return This builder for chaining. + */ + public Builder clearLongValue() { + + longValue_ = 0L; + onChanged(); + return this; + } + + private float floatValue_ ; + /** + * float float_value = 3; + * @return The floatValue. + */ + @Override + public float getFloatValue() { + return floatValue_; + } + /** + * float float_value = 3; + * @param value The floatValue to set. + * @return This builder for chaining. + */ + public Builder setFloatValue(float value) { + + floatValue_ = value; + onChanged(); + return this; + } + /** + * float float_value = 3; + * @return This builder for chaining. + */ + public Builder clearFloatValue() { + + floatValue_ = 0F; + onChanged(); + return this; + } + + private double doubleValue_ ; + /** + * double double_value = 4; + * @return The doubleValue. + */ + @Override + public double getDoubleValue() { + return doubleValue_; + } + /** + * double double_value = 4; + * @param value The doubleValue to set. + * @return This builder for chaining. + */ + public Builder setDoubleValue(double value) { + + doubleValue_ = value; + onChanged(); + return this; + } + /** + * double double_value = 4; + * @return This builder for chaining. + */ + public Builder clearDoubleValue() { + + doubleValue_ = 0D; + onChanged(); + return this; + } + + private boolean boolValue_ ; + /** + * bool bool_value = 5; + * @return The boolValue. + */ + @Override + public boolean getBoolValue() { + return boolValue_; + } + /** + * bool bool_value = 5; + * @param value The boolValue to set. + * @return This builder for chaining. + */ + public Builder setBoolValue(boolean value) { + + boolValue_ = value; + onChanged(); + return this; + } + /** + * bool bool_value = 5; + * @return This builder for chaining. + */ + public Builder clearBoolValue() { + + boolValue_ = false; + onChanged(); + return this; + } + + private Object stringValue_ = ""; + /** + * string string_value = 6; + * @return The stringValue. + */ + public String getStringValue() { + Object ref = stringValue_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + stringValue_ = s; + return s; + } else { + return (String) ref; + } + } + /** + * string string_value = 6; + * @return The bytes for stringValue. + */ + public com.google.protobuf.ByteString + getStringValueBytes() { + Object ref = stringValue_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (String) ref); + stringValue_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * string string_value = 6; + * @param value The stringValue to set. + * @return This builder for chaining. + */ + public Builder setStringValue( + String value) { + if (value == null) { + throw new NullPointerException(); + } + + stringValue_ = value; + onChanged(); + return this; + } + /** + * string string_value = 6; + * @return This builder for chaining. + */ + public Builder clearStringValue() { + + stringValue_ = getDefaultInstance().getStringValue(); + onChanged(); + return this; + } + /** + * string string_value = 6; + * @param value The bytes for stringValue to set. + * @return This builder for chaining. + */ + public Builder setStringValueBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + stringValue_ = value; + onChanged(); + return this; + } + + private com.google.protobuf.Int32Value intOpt_; + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.Int32Value, com.google.protobuf.Int32Value.Builder, com.google.protobuf.Int32ValueOrBuilder> intOptBuilder_; + /** + * .google.protobuf.Int32Value int_Opt = 7; + * @return Whether the intOpt field is set. + */ + public boolean hasIntOpt() { + return intOptBuilder_ != null || intOpt_ != null; + } + /** + * .google.protobuf.Int32Value int_Opt = 7; + * @return The intOpt. + */ + public com.google.protobuf.Int32Value getIntOpt() { + if (intOptBuilder_ == null) { + return intOpt_ == null ? com.google.protobuf.Int32Value.getDefaultInstance() : intOpt_; + } else { + return intOptBuilder_.getMessage(); + } + } + /** + * .google.protobuf.Int32Value int_Opt = 7; + */ + public Builder setIntOpt(com.google.protobuf.Int32Value value) { + if (intOptBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + intOpt_ = value; + onChanged(); + } else { + intOptBuilder_.setMessage(value); + } + + return this; + } + /** + * .google.protobuf.Int32Value int_Opt = 7; + */ + public Builder setIntOpt( + com.google.protobuf.Int32Value.Builder builderForValue) { + if (intOptBuilder_ == null) { + intOpt_ = builderForValue.build(); + onChanged(); + } else { + intOptBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + * .google.protobuf.Int32Value int_Opt = 7; + */ + public Builder mergeIntOpt(com.google.protobuf.Int32Value value) { + if (intOptBuilder_ == null) { + if (intOpt_ != null) { + intOpt_ = + com.google.protobuf.Int32Value.newBuilder(intOpt_).mergeFrom(value).buildPartial(); + } else { + intOpt_ = value; + } + onChanged(); + } else { + intOptBuilder_.mergeFrom(value); + } + + return this; + } + /** + * .google.protobuf.Int32Value int_Opt = 7; + */ + public Builder clearIntOpt() { + if (intOptBuilder_ == null) { + intOpt_ = null; + onChanged(); + } else { + intOpt_ = null; + intOptBuilder_ = null; + } + + return this; + } + /** + * .google.protobuf.Int32Value int_Opt = 7; + */ + public com.google.protobuf.Int32Value.Builder getIntOptBuilder() { + + onChanged(); + return getIntOptFieldBuilder().getBuilder(); + } + /** + * .google.protobuf.Int32Value int_Opt = 7; + */ + public com.google.protobuf.Int32ValueOrBuilder getIntOptOrBuilder() { + if (intOptBuilder_ != null) { + return intOptBuilder_.getMessageOrBuilder(); + } else { + return intOpt_ == null ? + com.google.protobuf.Int32Value.getDefaultInstance() : intOpt_; + } + } + /** + * .google.protobuf.Int32Value int_Opt = 7; + */ + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.Int32Value, com.google.protobuf.Int32Value.Builder, com.google.protobuf.Int32ValueOrBuilder> + getIntOptFieldBuilder() { + if (intOptBuilder_ == null) { + intOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.Int32Value, com.google.protobuf.Int32Value.Builder, com.google.protobuf.Int32ValueOrBuilder>( + getIntOpt(), + getParentForChildren(), + isClean()); + intOpt_ = null; + } + return intOptBuilder_; + } + + private com.google.protobuf.Int64Value longOpt_; + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.Int64Value, com.google.protobuf.Int64Value.Builder, com.google.protobuf.Int64ValueOrBuilder> longOptBuilder_; + /** + * .google.protobuf.Int64Value long_Opt = 8; + * @return Whether the longOpt field is set. + */ + public boolean hasLongOpt() { + return longOptBuilder_ != null || longOpt_ != null; + } + /** + * .google.protobuf.Int64Value long_Opt = 8; + * @return The longOpt. + */ + public com.google.protobuf.Int64Value getLongOpt() { + if (longOptBuilder_ == null) { + return longOpt_ == null ? com.google.protobuf.Int64Value.getDefaultInstance() : longOpt_; + } else { + return longOptBuilder_.getMessage(); + } + } + /** + * .google.protobuf.Int64Value long_Opt = 8; + */ + public Builder setLongOpt(com.google.protobuf.Int64Value value) { + if (longOptBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + longOpt_ = value; + onChanged(); + } else { + longOptBuilder_.setMessage(value); + } + + return this; + } + /** + * .google.protobuf.Int64Value long_Opt = 8; + */ + public Builder setLongOpt( + com.google.protobuf.Int64Value.Builder builderForValue) { + if (longOptBuilder_ == null) { + longOpt_ = builderForValue.build(); + onChanged(); + } else { + longOptBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + * .google.protobuf.Int64Value long_Opt = 8; + */ + public Builder mergeLongOpt(com.google.protobuf.Int64Value value) { + if (longOptBuilder_ == null) { + if (longOpt_ != null) { + longOpt_ = + com.google.protobuf.Int64Value.newBuilder(longOpt_).mergeFrom(value).buildPartial(); + } else { + longOpt_ = value; + } + onChanged(); + } else { + longOptBuilder_.mergeFrom(value); + } + + return this; + } + /** + * .google.protobuf.Int64Value long_Opt = 8; + */ + public Builder clearLongOpt() { + if (longOptBuilder_ == null) { + longOpt_ = null; + onChanged(); + } else { + longOpt_ = null; + longOptBuilder_ = null; + } + + return this; + } + /** + * .google.protobuf.Int64Value long_Opt = 8; + */ + public com.google.protobuf.Int64Value.Builder getLongOptBuilder() { + + onChanged(); + return getLongOptFieldBuilder().getBuilder(); + } + /** + * .google.protobuf.Int64Value long_Opt = 8; + */ + public com.google.protobuf.Int64ValueOrBuilder getLongOptOrBuilder() { + if (longOptBuilder_ != null) { + return longOptBuilder_.getMessageOrBuilder(); + } else { + return longOpt_ == null ? + com.google.protobuf.Int64Value.getDefaultInstance() : longOpt_; + } + } + /** + * .google.protobuf.Int64Value long_Opt = 8; + */ + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.Int64Value, com.google.protobuf.Int64Value.Builder, com.google.protobuf.Int64ValueOrBuilder> + getLongOptFieldBuilder() { + if (longOptBuilder_ == null) { + longOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.Int64Value, com.google.protobuf.Int64Value.Builder, com.google.protobuf.Int64ValueOrBuilder>( + getLongOpt(), + getParentForChildren(), + isClean()); + longOpt_ = null; + } + return longOptBuilder_; + } + + private com.google.protobuf.FloatValue floatOpt_; + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.FloatValue, com.google.protobuf.FloatValue.Builder, com.google.protobuf.FloatValueOrBuilder> floatOptBuilder_; + /** + * .google.protobuf.FloatValue float_Opt = 9; + * @return Whether the floatOpt field is set. + */ + public boolean hasFloatOpt() { + return floatOptBuilder_ != null || floatOpt_ != null; + } + /** + * .google.protobuf.FloatValue float_Opt = 9; + * @return The floatOpt. + */ + public com.google.protobuf.FloatValue getFloatOpt() { + if (floatOptBuilder_ == null) { + return floatOpt_ == null ? com.google.protobuf.FloatValue.getDefaultInstance() : floatOpt_; + } else { + return floatOptBuilder_.getMessage(); + } + } + /** + * .google.protobuf.FloatValue float_Opt = 9; + */ + public Builder setFloatOpt(com.google.protobuf.FloatValue value) { + if (floatOptBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + floatOpt_ = value; + onChanged(); + } else { + floatOptBuilder_.setMessage(value); + } + + return this; + } + /** + * .google.protobuf.FloatValue float_Opt = 9; + */ + public Builder setFloatOpt( + com.google.protobuf.FloatValue.Builder builderForValue) { + if (floatOptBuilder_ == null) { + floatOpt_ = builderForValue.build(); + onChanged(); + } else { + floatOptBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + * .google.protobuf.FloatValue float_Opt = 9; + */ + public Builder mergeFloatOpt(com.google.protobuf.FloatValue value) { + if (floatOptBuilder_ == null) { + if (floatOpt_ != null) { + floatOpt_ = + com.google.protobuf.FloatValue.newBuilder(floatOpt_).mergeFrom(value).buildPartial(); + } else { + floatOpt_ = value; + } + onChanged(); + } else { + floatOptBuilder_.mergeFrom(value); + } + + return this; + } + /** + * .google.protobuf.FloatValue float_Opt = 9; + */ + public Builder clearFloatOpt() { + if (floatOptBuilder_ == null) { + floatOpt_ = null; + onChanged(); + } else { + floatOpt_ = null; + floatOptBuilder_ = null; + } + + return this; + } + /** + * .google.protobuf.FloatValue float_Opt = 9; + */ + public com.google.protobuf.FloatValue.Builder getFloatOptBuilder() { + + onChanged(); + return getFloatOptFieldBuilder().getBuilder(); + } + /** + * .google.protobuf.FloatValue float_Opt = 9; + */ + public com.google.protobuf.FloatValueOrBuilder getFloatOptOrBuilder() { + if (floatOptBuilder_ != null) { + return floatOptBuilder_.getMessageOrBuilder(); + } else { + return floatOpt_ == null ? + com.google.protobuf.FloatValue.getDefaultInstance() : floatOpt_; + } + } + /** + * .google.protobuf.FloatValue float_Opt = 9; + */ + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.FloatValue, com.google.protobuf.FloatValue.Builder, com.google.protobuf.FloatValueOrBuilder> + getFloatOptFieldBuilder() { + if (floatOptBuilder_ == null) { + floatOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.FloatValue, com.google.protobuf.FloatValue.Builder, com.google.protobuf.FloatValueOrBuilder>( + getFloatOpt(), + getParentForChildren(), + isClean()); + floatOpt_ = null; + } + return floatOptBuilder_; + } + + private com.google.protobuf.DoubleValue doubleOpt_; + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.DoubleValue, com.google.protobuf.DoubleValue.Builder, com.google.protobuf.DoubleValueOrBuilder> doubleOptBuilder_; + /** + * .google.protobuf.DoubleValue double_opt = 10; + * @return Whether the doubleOpt field is set. + */ + public boolean hasDoubleOpt() { + return doubleOptBuilder_ != null || doubleOpt_ != null; + } + /** + * .google.protobuf.DoubleValue double_opt = 10; + * @return The doubleOpt. + */ + public com.google.protobuf.DoubleValue getDoubleOpt() { + if (doubleOptBuilder_ == null) { + return doubleOpt_ == null ? com.google.protobuf.DoubleValue.getDefaultInstance() : doubleOpt_; + } else { + return doubleOptBuilder_.getMessage(); + } + } + /** + * .google.protobuf.DoubleValue double_opt = 10; + */ + public Builder setDoubleOpt(com.google.protobuf.DoubleValue value) { + if (doubleOptBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + doubleOpt_ = value; + onChanged(); + } else { + doubleOptBuilder_.setMessage(value); + } + + return this; + } + /** + * .google.protobuf.DoubleValue double_opt = 10; + */ + public Builder setDoubleOpt( + com.google.protobuf.DoubleValue.Builder builderForValue) { + if (doubleOptBuilder_ == null) { + doubleOpt_ = builderForValue.build(); + onChanged(); + } else { + doubleOptBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + * .google.protobuf.DoubleValue double_opt = 10; + */ + public Builder mergeDoubleOpt(com.google.protobuf.DoubleValue value) { + if (doubleOptBuilder_ == null) { + if (doubleOpt_ != null) { + doubleOpt_ = + com.google.protobuf.DoubleValue.newBuilder(doubleOpt_).mergeFrom(value).buildPartial(); + } else { + doubleOpt_ = value; + } + onChanged(); + } else { + doubleOptBuilder_.mergeFrom(value); + } + + return this; + } + /** + * .google.protobuf.DoubleValue double_opt = 10; + */ + public Builder clearDoubleOpt() { + if (doubleOptBuilder_ == null) { + doubleOpt_ = null; + onChanged(); + } else { + doubleOpt_ = null; + doubleOptBuilder_ = null; + } + + return this; + } + /** + * .google.protobuf.DoubleValue double_opt = 10; + */ + public com.google.protobuf.DoubleValue.Builder getDoubleOptBuilder() { + + onChanged(); + return getDoubleOptFieldBuilder().getBuilder(); + } + /** + * .google.protobuf.DoubleValue double_opt = 10; + */ + public com.google.protobuf.DoubleValueOrBuilder getDoubleOptOrBuilder() { + if (doubleOptBuilder_ != null) { + return doubleOptBuilder_.getMessageOrBuilder(); + } else { + return doubleOpt_ == null ? + com.google.protobuf.DoubleValue.getDefaultInstance() : doubleOpt_; + } + } + /** + * .google.protobuf.DoubleValue double_opt = 10; + */ + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.DoubleValue, com.google.protobuf.DoubleValue.Builder, com.google.protobuf.DoubleValueOrBuilder> + getDoubleOptFieldBuilder() { + if (doubleOptBuilder_ == null) { + doubleOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.DoubleValue, com.google.protobuf.DoubleValue.Builder, com.google.protobuf.DoubleValueOrBuilder>( + getDoubleOpt(), + getParentForChildren(), + isClean()); + doubleOpt_ = null; + } + return doubleOptBuilder_; + } + + private com.google.protobuf.BoolValue boolOpt_; + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.BoolValue, com.google.protobuf.BoolValue.Builder, com.google.protobuf.BoolValueOrBuilder> boolOptBuilder_; + /** + * .google.protobuf.BoolValue bool_opt = 11; + * @return Whether the boolOpt field is set. + */ + public boolean hasBoolOpt() { + return boolOptBuilder_ != null || boolOpt_ != null; + } + /** + * .google.protobuf.BoolValue bool_opt = 11; + * @return The boolOpt. + */ + public com.google.protobuf.BoolValue getBoolOpt() { + if (boolOptBuilder_ == null) { + return boolOpt_ == null ? com.google.protobuf.BoolValue.getDefaultInstance() : boolOpt_; + } else { + return boolOptBuilder_.getMessage(); + } + } + /** + * .google.protobuf.BoolValue bool_opt = 11; + */ + public Builder setBoolOpt(com.google.protobuf.BoolValue value) { + if (boolOptBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + boolOpt_ = value; + onChanged(); + } else { + boolOptBuilder_.setMessage(value); + } + + return this; + } + /** + * .google.protobuf.BoolValue bool_opt = 11; + */ + public Builder setBoolOpt( + com.google.protobuf.BoolValue.Builder builderForValue) { + if (boolOptBuilder_ == null) { + boolOpt_ = builderForValue.build(); + onChanged(); + } else { + boolOptBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + * .google.protobuf.BoolValue bool_opt = 11; + */ + public Builder mergeBoolOpt(com.google.protobuf.BoolValue value) { + if (boolOptBuilder_ == null) { + if (boolOpt_ != null) { + boolOpt_ = + com.google.protobuf.BoolValue.newBuilder(boolOpt_).mergeFrom(value).buildPartial(); + } else { + boolOpt_ = value; + } + onChanged(); + } else { + boolOptBuilder_.mergeFrom(value); + } + + return this; + } + /** + * .google.protobuf.BoolValue bool_opt = 11; + */ + public Builder clearBoolOpt() { + if (boolOptBuilder_ == null) { + boolOpt_ = null; + onChanged(); + } else { + boolOpt_ = null; + boolOptBuilder_ = null; + } + + return this; + } + /** + * .google.protobuf.BoolValue bool_opt = 11; + */ + public com.google.protobuf.BoolValue.Builder getBoolOptBuilder() { + + onChanged(); + return getBoolOptFieldBuilder().getBuilder(); + } + /** + * .google.protobuf.BoolValue bool_opt = 11; + */ + public com.google.protobuf.BoolValueOrBuilder getBoolOptOrBuilder() { + if (boolOptBuilder_ != null) { + return boolOptBuilder_.getMessageOrBuilder(); + } else { + return boolOpt_ == null ? + com.google.protobuf.BoolValue.getDefaultInstance() : boolOpt_; + } + } + /** + * .google.protobuf.BoolValue bool_opt = 11; + */ + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.BoolValue, com.google.protobuf.BoolValue.Builder, com.google.protobuf.BoolValueOrBuilder> + getBoolOptFieldBuilder() { + if (boolOptBuilder_ == null) { + boolOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.BoolValue, com.google.protobuf.BoolValue.Builder, com.google.protobuf.BoolValueOrBuilder>( + getBoolOpt(), + getParentForChildren(), + isClean()); + boolOpt_ = null; + } + return boolOptBuilder_; + } + + private com.google.protobuf.StringValue stringOpt_; + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.StringValue, com.google.protobuf.StringValue.Builder, com.google.protobuf.StringValueOrBuilder> stringOptBuilder_; + /** + * .google.protobuf.StringValue string_opt = 12; + * @return Whether the stringOpt field is set. + */ + public boolean hasStringOpt() { + return stringOptBuilder_ != null || stringOpt_ != null; + } + /** + * .google.protobuf.StringValue string_opt = 12; + * @return The stringOpt. + */ + public com.google.protobuf.StringValue getStringOpt() { + if (stringOptBuilder_ == null) { + return stringOpt_ == null ? com.google.protobuf.StringValue.getDefaultInstance() : stringOpt_; + } else { + return stringOptBuilder_.getMessage(); + } + } + /** + * .google.protobuf.StringValue string_opt = 12; + */ + public Builder setStringOpt(com.google.protobuf.StringValue value) { + if (stringOptBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + stringOpt_ = value; + onChanged(); + } else { + stringOptBuilder_.setMessage(value); + } + + return this; + } + /** + * .google.protobuf.StringValue string_opt = 12; + */ + public Builder setStringOpt( + com.google.protobuf.StringValue.Builder builderForValue) { + if (stringOptBuilder_ == null) { + stringOpt_ = builderForValue.build(); + onChanged(); + } else { + stringOptBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + * .google.protobuf.StringValue string_opt = 12; + */ + public Builder mergeStringOpt(com.google.protobuf.StringValue value) { + if (stringOptBuilder_ == null) { + if (stringOpt_ != null) { + stringOpt_ = + com.google.protobuf.StringValue.newBuilder(stringOpt_).mergeFrom(value).buildPartial(); + } else { + stringOpt_ = value; + } + onChanged(); + } else { + stringOptBuilder_.mergeFrom(value); + } + + return this; + } + /** + * .google.protobuf.StringValue string_opt = 12; + */ + public Builder clearStringOpt() { + if (stringOptBuilder_ == null) { + stringOpt_ = null; + onChanged(); + } else { + stringOpt_ = null; + stringOptBuilder_ = null; + } + + return this; + } + /** + * .google.protobuf.StringValue string_opt = 12; + */ + public com.google.protobuf.StringValue.Builder getStringOptBuilder() { + + onChanged(); + return getStringOptFieldBuilder().getBuilder(); + } + /** + * .google.protobuf.StringValue string_opt = 12; + */ + public com.google.protobuf.StringValueOrBuilder getStringOptOrBuilder() { + if (stringOptBuilder_ != null) { + return stringOptBuilder_.getMessageOrBuilder(); + } else { + return stringOpt_ == null ? + com.google.protobuf.StringValue.getDefaultInstance() : stringOpt_; + } + } + /** + * .google.protobuf.StringValue string_opt = 12; + */ + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.StringValue, com.google.protobuf.StringValue.Builder, com.google.protobuf.StringValueOrBuilder> + getStringOptFieldBuilder() { + if (stringOptBuilder_ == null) { + stringOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.StringValue, com.google.protobuf.StringValue.Builder, com.google.protobuf.StringValueOrBuilder>( + getStringOpt(), + getParentForChildren(), + isClean()); + stringOpt_ = null; + } + return stringOptBuilder_; + } + + private com.google.protobuf.Timestamp time_; + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> timeBuilder_; + /** + * .google.protobuf.Timestamp time = 13; + * @return Whether the time field is set. + */ + public boolean hasTime() { + return timeBuilder_ != null || time_ != null; + } + /** + * .google.protobuf.Timestamp time = 13; + * @return The time. + */ + public com.google.protobuf.Timestamp getTime() { + if (timeBuilder_ == null) { + return time_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : time_; + } else { + return timeBuilder_.getMessage(); + } + } + /** + * .google.protobuf.Timestamp time = 13; + */ + public Builder setTime(com.google.protobuf.Timestamp value) { + if (timeBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + time_ = value; + onChanged(); + } else { + timeBuilder_.setMessage(value); + } + + return this; + } + /** + * .google.protobuf.Timestamp time = 13; + */ + public Builder setTime( + com.google.protobuf.Timestamp.Builder builderForValue) { + if (timeBuilder_ == null) { + time_ = builderForValue.build(); + onChanged(); + } else { + timeBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + * .google.protobuf.Timestamp time = 13; + */ + public Builder mergeTime(com.google.protobuf.Timestamp value) { + if (timeBuilder_ == null) { + if (time_ != null) { + time_ = + com.google.protobuf.Timestamp.newBuilder(time_).mergeFrom(value).buildPartial(); + } else { + time_ = value; + } + onChanged(); + } else { + timeBuilder_.mergeFrom(value); + } + + return this; + } + /** + * .google.protobuf.Timestamp time = 13; + */ + public Builder clearTime() { + if (timeBuilder_ == null) { + time_ = null; + onChanged(); + } else { + time_ = null; + timeBuilder_ = null; + } + + return this; + } + /** + * .google.protobuf.Timestamp time = 13; + */ + public com.google.protobuf.Timestamp.Builder getTimeBuilder() { + + onChanged(); + return getTimeFieldBuilder().getBuilder(); + } + /** + * .google.protobuf.Timestamp time = 13; + */ + public com.google.protobuf.TimestampOrBuilder getTimeOrBuilder() { + if (timeBuilder_ != null) { + return timeBuilder_.getMessageOrBuilder(); + } else { + return time_ == null ? + com.google.protobuf.Timestamp.getDefaultInstance() : time_; + } + } + /** + * .google.protobuf.Timestamp time = 13; + */ + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> + getTimeFieldBuilder() { + if (timeBuilder_ == null) { + timeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( + getTime(), + getParentForChildren(), + isClean()); + time_ = null; + } + return timeBuilder_; + } + + private com.google.protobuf.Timestamp timeOpt_; + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> timeOptBuilder_; + /** + * .google.protobuf.Timestamp time_opt = 14; + * @return Whether the timeOpt field is set. + */ + public boolean hasTimeOpt() { + return timeOptBuilder_ != null || timeOpt_ != null; + } + /** + * .google.protobuf.Timestamp time_opt = 14; + * @return The timeOpt. + */ + public com.google.protobuf.Timestamp getTimeOpt() { + if (timeOptBuilder_ == null) { + return timeOpt_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : timeOpt_; + } else { + return timeOptBuilder_.getMessage(); + } + } + /** + * .google.protobuf.Timestamp time_opt = 14; + */ + public Builder setTimeOpt(com.google.protobuf.Timestamp value) { + if (timeOptBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + timeOpt_ = value; + onChanged(); + } else { + timeOptBuilder_.setMessage(value); + } + + return this; + } + /** + * .google.protobuf.Timestamp time_opt = 14; + */ + public Builder setTimeOpt( + com.google.protobuf.Timestamp.Builder builderForValue) { + if (timeOptBuilder_ == null) { + timeOpt_ = builderForValue.build(); + onChanged(); + } else { + timeOptBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + * .google.protobuf.Timestamp time_opt = 14; + */ + public Builder mergeTimeOpt(com.google.protobuf.Timestamp value) { + if (timeOptBuilder_ == null) { + if (timeOpt_ != null) { + timeOpt_ = + com.google.protobuf.Timestamp.newBuilder(timeOpt_).mergeFrom(value).buildPartial(); + } else { + timeOpt_ = value; + } + onChanged(); + } else { + timeOptBuilder_.mergeFrom(value); + } + + return this; + } + /** + * .google.protobuf.Timestamp time_opt = 14; + */ + public Builder clearTimeOpt() { + if (timeOptBuilder_ == null) { + timeOpt_ = null; + onChanged(); + } else { + timeOpt_ = null; + timeOptBuilder_ = null; + } + + return this; + } + /** + * .google.protobuf.Timestamp time_opt = 14; + */ + public com.google.protobuf.Timestamp.Builder getTimeOptBuilder() { + + onChanged(); + return getTimeOptFieldBuilder().getBuilder(); + } + /** + * .google.protobuf.Timestamp time_opt = 14; + */ + public com.google.protobuf.TimestampOrBuilder getTimeOptOrBuilder() { + if (timeOptBuilder_ != null) { + return timeOptBuilder_.getMessageOrBuilder(); + } else { + return timeOpt_ == null ? + com.google.protobuf.Timestamp.getDefaultInstance() : timeOpt_; + } + } + /** + * .google.protobuf.Timestamp time_opt = 14; + */ + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> + getTimeOptFieldBuilder() { + if (timeOptBuilder_ == null) { + timeOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( + getTimeOpt(), + getParentForChildren(), + isClean()); + timeOpt_ = null; + } + return timeOptBuilder_; + } + + private com.google.protobuf.Internal.IntList intArray_ = emptyIntList(); + private void ensureIntArrayIsMutable() { + if (!((bitField0_ & 0x00000001) != 0)) { + intArray_ = mutableCopy(intArray_); + bitField0_ |= 0x00000001; + } + } + /** + * repeated int32 int_array = 15; + * @return A list containing the intArray. + */ + public java.util.List + getIntArrayList() { + return ((bitField0_ & 0x00000001) != 0) ? + java.util.Collections.unmodifiableList(intArray_) : intArray_; + } + /** + * repeated int32 int_array = 15; + * @return The count of intArray. + */ + public int getIntArrayCount() { + return intArray_.size(); + } + /** + * repeated int32 int_array = 15; + * @param index The index of the element to return. + * @return The intArray at the given index. + */ + public int getIntArray(int index) { + return intArray_.getInt(index); + } + /** + * repeated int32 int_array = 15; + * @param index The index to set the value at. + * @param value The intArray to set. + * @return This builder for chaining. + */ + public Builder setIntArray( + int index, int value) { + ensureIntArrayIsMutable(); + intArray_.setInt(index, value); + onChanged(); + return this; + } + /** + * repeated int32 int_array = 15; + * @param value The intArray to add. + * @return This builder for chaining. + */ + public Builder addIntArray(int value) { + ensureIntArrayIsMutable(); + intArray_.addInt(value); + onChanged(); + return this; + } + /** + * repeated int32 int_array = 15; + * @param values The intArray to add. + * @return This builder for chaining. + */ + public Builder addAllIntArray( + Iterable values) { + ensureIntArrayIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll( + values, intArray_); + onChanged(); + return this; + } + /** + * repeated int32 int_array = 15; + * @return This builder for chaining. + */ + public Builder clearIntArray() { + intArray_ = emptyIntList(); + bitField0_ = (bitField0_ & ~0x00000001); + onChanged(); + return this; + } + + private com.google.protobuf.LazyStringList stringArray_ = com.google.protobuf.LazyStringArrayList.EMPTY; + private void ensureStringArrayIsMutable() { + if (!((bitField0_ & 0x00000002) != 0)) { + stringArray_ = new com.google.protobuf.LazyStringArrayList(stringArray_); + bitField0_ |= 0x00000002; + } + } + /** + * repeated string string_array = 16; + * @return A list containing the stringArray. + */ + public com.google.protobuf.ProtocolStringList + getStringArrayList() { + return stringArray_.getUnmodifiableView(); + } + /** + * repeated string string_array = 16; + * @return The count of stringArray. + */ + public int getStringArrayCount() { + return stringArray_.size(); + } + /** + * repeated string string_array = 16; + * @param index The index of the element to return. + * @return The stringArray at the given index. + */ + public String getStringArray(int index) { + return stringArray_.get(index); + } + /** + * repeated string string_array = 16; + * @param index The index of the value to return. + * @return The bytes of the stringArray at the given index. + */ + public com.google.protobuf.ByteString + getStringArrayBytes(int index) { + return stringArray_.getByteString(index); + } + /** + * repeated string string_array = 16; + * @param index The index to set the value at. + * @param value The stringArray to set. + * @return This builder for chaining. + */ + public Builder setStringArray( + int index, String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureStringArrayIsMutable(); + stringArray_.set(index, value); + onChanged(); + return this; + } + /** + * repeated string string_array = 16; + * @param value The stringArray to add. + * @return This builder for chaining. + */ + public Builder addStringArray( + String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureStringArrayIsMutable(); + stringArray_.add(value); + onChanged(); + return this; + } + /** + * repeated string string_array = 16; + * @param values The stringArray to add. + * @return This builder for chaining. + */ + public Builder addAllStringArray( + Iterable values) { + ensureStringArrayIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll( + values, stringArray_); + onChanged(); + return this; + } + /** + * repeated string string_array = 16; + * @return This builder for chaining. + */ + public Builder clearStringArray() { + stringArray_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000002); + onChanged(); + return this; + } + /** + * repeated string string_array = 16; + * @param value The bytes of the stringArray to add. + * @return This builder for chaining. + */ + public Builder addStringArrayBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureStringArrayIsMutable(); + stringArray_.add(value); + onChanged(); + return this; + } + + private java.util.List personArray_ = + java.util.Collections.emptyList(); + private void ensurePersonArrayIsMutable() { + if (!((bitField0_ & 0x00000004) != 0)) { + personArray_ = new java.util.ArrayList(personArray_); + bitField0_ |= 0x00000004; + } + } + + private com.google.protobuf.RepeatedFieldBuilderV3< + PBPerson, PBPerson.Builder, PBPersonOrBuilder> personArrayBuilder_; + + /** + * repeated .PBPerson person_array = 17; + */ + public java.util.List getPersonArrayList() { + if (personArrayBuilder_ == null) { + return java.util.Collections.unmodifiableList(personArray_); + } else { + return personArrayBuilder_.getMessageList(); + } + } + /** + * repeated .PBPerson person_array = 17; + */ + public int getPersonArrayCount() { + if (personArrayBuilder_ == null) { + return personArray_.size(); + } else { + return personArrayBuilder_.getCount(); + } + } + /** + * repeated .PBPerson person_array = 17; + */ + public PBPerson getPersonArray(int index) { + if (personArrayBuilder_ == null) { + return personArray_.get(index); + } else { + return personArrayBuilder_.getMessage(index); + } + } + /** + * repeated .PBPerson person_array = 17; + */ + public Builder setPersonArray( + int index, PBPerson value) { + if (personArrayBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePersonArrayIsMutable(); + personArray_.set(index, value); + onChanged(); + } else { + personArrayBuilder_.setMessage(index, value); + } + return this; + } + /** + * repeated .PBPerson person_array = 17; + */ + public Builder setPersonArray( + int index, PBPerson.Builder builderForValue) { + if (personArrayBuilder_ == null) { + ensurePersonArrayIsMutable(); + personArray_.set(index, builderForValue.build()); + onChanged(); + } else { + personArrayBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + * repeated .PBPerson person_array = 17; + */ + public Builder addPersonArray(PBPerson value) { + if (personArrayBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePersonArrayIsMutable(); + personArray_.add(value); + onChanged(); + } else { + personArrayBuilder_.addMessage(value); + } + return this; + } + /** + * repeated .PBPerson person_array = 17; + */ + public Builder addPersonArray( + int index, PBPerson value) { + if (personArrayBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePersonArrayIsMutable(); + personArray_.add(index, value); + onChanged(); + } else { + personArrayBuilder_.addMessage(index, value); + } + return this; + } + /** + * repeated .PBPerson person_array = 17; + */ + public Builder addPersonArray( + PBPerson.Builder builderForValue) { + if (personArrayBuilder_ == null) { + ensurePersonArrayIsMutable(); + personArray_.add(builderForValue.build()); + onChanged(); + } else { + personArrayBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + * repeated .PBPerson person_array = 17; + */ + public Builder addPersonArray( + int index, PBPerson.Builder builderForValue) { + if (personArrayBuilder_ == null) { + ensurePersonArrayIsMutable(); + personArray_.add(index, builderForValue.build()); + onChanged(); + } else { + personArrayBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + * repeated .PBPerson person_array = 17; + */ + public Builder addAllPersonArray( + Iterable values) { + if (personArrayBuilder_ == null) { + ensurePersonArrayIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll( + values, personArray_); + onChanged(); + } else { + personArrayBuilder_.addAllMessages(values); + } + return this; + } + /** + * repeated .PBPerson person_array = 17; + */ + public Builder clearPersonArray() { + if (personArrayBuilder_ == null) { + personArray_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000004); + onChanged(); + } else { + personArrayBuilder_.clear(); + } + return this; + } + /** + * repeated .PBPerson person_array = 17; + */ + public Builder removePersonArray(int index) { + if (personArrayBuilder_ == null) { + ensurePersonArrayIsMutable(); + personArray_.remove(index); + onChanged(); + } else { + personArrayBuilder_.remove(index); + } + return this; + } + /** + * repeated .PBPerson person_array = 17; + */ + public PBPerson.Builder getPersonArrayBuilder( + int index) { + return getPersonArrayFieldBuilder().getBuilder(index); + } + /** + * repeated .PBPerson person_array = 17; + */ + public PBPersonOrBuilder getPersonArrayOrBuilder( + int index) { + if (personArrayBuilder_ == null) { + return personArray_.get(index); } else { + return personArrayBuilder_.getMessageOrBuilder(index); + } + } + /** + * repeated .PBPerson person_array = 17; + */ + public java.util.List + getPersonArrayOrBuilderList() { + if (personArrayBuilder_ != null) { + return personArrayBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(personArray_); + } + } + /** + * repeated .PBPerson person_array = 17; + */ + public PBPerson.Builder addPersonArrayBuilder() { + return getPersonArrayFieldBuilder().addBuilder( + PBPerson.getDefaultInstance()); + } + /** + * repeated .PBPerson person_array = 17; + */ + public PBPerson.Builder addPersonArrayBuilder( + int index) { + return getPersonArrayFieldBuilder().addBuilder( + index, PBPerson.getDefaultInstance()); + } + /** + * repeated .PBPerson person_array = 17; + */ + public java.util.List + getPersonArrayBuilderList() { + return getPersonArrayFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilderV3< + PBPerson, PBPerson.Builder, PBPersonOrBuilder> + getPersonArrayFieldBuilder() { + if (personArrayBuilder_ == null) { + personArrayBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< + PBPerson, PBPerson.Builder, PBPersonOrBuilder>( + personArray_, + ((bitField0_ & 0x00000004) != 0), + getParentForChildren(), + isClean()); + personArray_ = null; + } + return personArrayBuilder_; + } + + private com.google.protobuf.Internal.DoubleList seq_ = emptyDoubleList(); + private void ensureSeqIsMutable() { + if (!((bitField0_ & 0x00000008) != 0)) { + seq_ = mutableCopy(seq_); + bitField0_ |= 0x00000008; + } + } + /** + * repeated double seq = 18; + * @return A list containing the seq. + */ + public java.util.List + getSeqList() { + return ((bitField0_ & 0x00000008) != 0) ? + java.util.Collections.unmodifiableList(seq_) : seq_; + } + /** + * repeated double seq = 18; + * @return The count of seq. + */ + public int getSeqCount() { + return seq_.size(); + } + /** + * repeated double seq = 18; + * @param index The index of the element to return. + * @return The seq at the given index. + */ + public double getSeq(int index) { + return seq_.getDouble(index); + } + /** + * repeated double seq = 18; + * @param index The index to set the value at. + * @param value The seq to set. + * @return This builder for chaining. + */ + public Builder setSeq( + int index, double value) { + ensureSeqIsMutable(); + seq_.setDouble(index, value); + onChanged(); + return this; + } + /** + * repeated double seq = 18; + * @param value The seq to add. + * @return This builder for chaining. + */ + public Builder addSeq(double value) { + ensureSeqIsMutable(); + seq_.addDouble(value); + onChanged(); + return this; + } + /** + * repeated double seq = 18; + * @param values The seq to add. + * @return This builder for chaining. + */ + public Builder addAllSeq( + Iterable values) { + ensureSeqIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll( + values, seq_); + onChanged(); + return this; + } + /** + * repeated double seq = 18; + * @return This builder for chaining. + */ + public Builder clearSeq() { + seq_ = emptyDoubleList(); + bitField0_ = (bitField0_ & ~0x00000008); + onChanged(); + return this; + } + + private com.google.protobuf.MapField< + String, String> stringStringKV_; + private com.google.protobuf.MapField + internalGetStringStringKV() { + if (stringStringKV_ == null) { + return com.google.protobuf.MapField.emptyMapField( + StringStringKVDefaultEntryHolder.defaultEntry); + } + return stringStringKV_; + } + private com.google.protobuf.MapField + internalGetMutableStringStringKV() { + onChanged();; + if (stringStringKV_ == null) { + stringStringKV_ = com.google.protobuf.MapField.newMapField( + StringStringKVDefaultEntryHolder.defaultEntry); + } + if (!stringStringKV_.isMutable()) { + stringStringKV_ = stringStringKV_.copy(); + } + return stringStringKV_; + } + + public int getStringStringKVCount() { + return internalGetStringStringKV().getMap().size(); + } + /** + * map<string, string> string_string_k_v = 19; + */ + + @Override + public boolean containsStringStringKV( + String key) { + if (key == null) { throw new NullPointerException(); } + return internalGetStringStringKV().getMap().containsKey(key); + } + /** + * Use {@link #getStringStringKVMap()} instead. + */ + @Override + @Deprecated + public java.util.Map getStringStringKV() { + return getStringStringKVMap(); + } + /** + * map<string, string> string_string_k_v = 19; + */ + @Override + + public java.util.Map getStringStringKVMap() { + return internalGetStringStringKV().getMap(); + } + /** + * map<string, string> string_string_k_v = 19; + */ + @Override + + public String getStringStringKVOrDefault( + String key, + String defaultValue) { + if (key == null) { throw new NullPointerException(); } + java.util.Map map = + internalGetStringStringKV().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + * map<string, string> string_string_k_v = 19; + */ + @Override + + public String getStringStringKVOrThrow( + String key) { + if (key == null) { throw new NullPointerException(); } + java.util.Map map = + internalGetStringStringKV().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); + } + + public Builder clearStringStringKV() { + internalGetMutableStringStringKV().getMutableMap() + .clear(); + return this; + } + /** + * map<string, string> string_string_k_v = 19; + */ + + public Builder removeStringStringKV( + String key) { + if (key == null) { throw new NullPointerException(); } + internalGetMutableStringStringKV().getMutableMap() + .remove(key); + return this; + } + /** + * Use alternate mutation accessors instead. + */ + @Deprecated + public java.util.Map + getMutableStringStringKV() { + return internalGetMutableStringStringKV().getMutableMap(); + } + /** + * map<string, string> string_string_k_v = 19; + */ + public Builder putStringStringKV( + String key, + String value) { + if (key == null) { throw new NullPointerException(); } + if (value == null) { throw new NullPointerException(); } + internalGetMutableStringStringKV().getMutableMap() + .put(key, value); + return this; + } + /** + * map<string, string> string_string_k_v = 19; + */ + + public Builder putAllStringStringKV( + java.util.Map values) { + internalGetMutableStringStringKV().getMutableMap() + .putAll(values); + return this; + } + + private com.google.protobuf.MapField< + Long, String> longStringKV_; + private com.google.protobuf.MapField + internalGetLongStringKV() { + if (longStringKV_ == null) { + return com.google.protobuf.MapField.emptyMapField( + LongStringKVDefaultEntryHolder.defaultEntry); + } + return longStringKV_; + } + private com.google.protobuf.MapField + internalGetMutableLongStringKV() { + onChanged();; + if (longStringKV_ == null) { + longStringKV_ = com.google.protobuf.MapField.newMapField( + LongStringKVDefaultEntryHolder.defaultEntry); + } + if (!longStringKV_.isMutable()) { + longStringKV_ = longStringKV_.copy(); + } + return longStringKV_; + } + + public int getLongStringKVCount() { + return internalGetLongStringKV().getMap().size(); + } + /** + * map<int64, string> long_string_k_v = 20; + */ + + @Override + public boolean containsLongStringKV( + long key) { + + return internalGetLongStringKV().getMap().containsKey(key); + } + /** + * Use {@link #getLongStringKVMap()} instead. + */ + @Override + @Deprecated + public java.util.Map getLongStringKV() { + return getLongStringKVMap(); + } + /** + * map<int64, string> long_string_k_v = 20; + */ + @Override + + public java.util.Map getLongStringKVMap() { + return internalGetLongStringKV().getMap(); + } + /** + * map<int64, string> long_string_k_v = 20; + */ + @Override + + public String getLongStringKVOrDefault( + long key, + String defaultValue) { + + java.util.Map map = + internalGetLongStringKV().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + * map<int64, string> long_string_k_v = 20; + */ + @Override + + public String getLongStringKVOrThrow( + long key) { + + java.util.Map map = + internalGetLongStringKV().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); + } + + public Builder clearLongStringKV() { + internalGetMutableLongStringKV().getMutableMap() + .clear(); + return this; + } + /** + * map<int64, string> long_string_k_v = 20; + */ + + public Builder removeLongStringKV( + long key) { + + internalGetMutableLongStringKV().getMutableMap() + .remove(key); + return this; + } + /** + * Use alternate mutation accessors instead. + */ + @Deprecated + public java.util.Map + getMutableLongStringKV() { + return internalGetMutableLongStringKV().getMutableMap(); + } + /** + * map<int64, string> long_string_k_v = 20; + */ + public Builder putLongStringKV( + long key, + String value) { + + if (value == null) { throw new NullPointerException(); } + internalGetMutableLongStringKV().getMutableMap() + .put(key, value); + return this; + } + /** + * map<int64, string> long_string_k_v = 20; + */ + + public Builder putAllLongStringKV( + java.util.Map values) { + internalGetMutableLongStringKV().getMutableMap() + .putAll(values); + return this; + } + + private com.google.protobuf.MapField< + String, Integer> stringIntKV_; + private com.google.protobuf.MapField + internalGetStringIntKV() { + if (stringIntKV_ == null) { + return com.google.protobuf.MapField.emptyMapField( + StringIntKVDefaultEntryHolder.defaultEntry); + } + return stringIntKV_; + } + private com.google.protobuf.MapField + internalGetMutableStringIntKV() { + onChanged();; + if (stringIntKV_ == null) { + stringIntKV_ = com.google.protobuf.MapField.newMapField( + StringIntKVDefaultEntryHolder.defaultEntry); + } + if (!stringIntKV_.isMutable()) { + stringIntKV_ = stringIntKV_.copy(); + } + return stringIntKV_; + } + + public int getStringIntKVCount() { + return internalGetStringIntKV().getMap().size(); + } + /** + * map<string, int32> string_int_k_v = 21; + */ + + @Override + public boolean containsStringIntKV( + String key) { + if (key == null) { throw new NullPointerException(); } + return internalGetStringIntKV().getMap().containsKey(key); + } + /** + * Use {@link #getStringIntKVMap()} instead. + */ + @Override + @Deprecated + public java.util.Map getStringIntKV() { + return getStringIntKVMap(); + } + /** + * map<string, int32> string_int_k_v = 21; + */ + @Override + + public java.util.Map getStringIntKVMap() { + return internalGetStringIntKV().getMap(); + } + /** + * map<string, int32> string_int_k_v = 21; + */ + @Override + + public int getStringIntKVOrDefault( + String key, + int defaultValue) { + if (key == null) { throw new NullPointerException(); } + java.util.Map map = + internalGetStringIntKV().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + * map<string, int32> string_int_k_v = 21; + */ + @Override + + public int getStringIntKVOrThrow( + String key) { + if (key == null) { throw new NullPointerException(); } + java.util.Map map = + internalGetStringIntKV().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); + } + + public Builder clearStringIntKV() { + internalGetMutableStringIntKV().getMutableMap() + .clear(); + return this; + } + /** + * map<string, int32> string_int_k_v = 21; + */ + + public Builder removeStringIntKV( + String key) { + if (key == null) { throw new NullPointerException(); } + internalGetMutableStringIntKV().getMutableMap() + .remove(key); + return this; + } + /** + * Use alternate mutation accessors instead. + */ + @Deprecated + public java.util.Map + getMutableStringIntKV() { + return internalGetMutableStringIntKV().getMutableMap(); + } + /** + * map<string, int32> string_int_k_v = 21; + */ + public Builder putStringIntKV( + String key, + int value) { + if (key == null) { throw new NullPointerException(); } + + internalGetMutableStringIntKV().getMutableMap() + .put(key, value); + return this; + } + /** + * map<string, int32> string_int_k_v = 21; + */ + + public Builder putAllStringIntKV( + java.util.Map values) { + internalGetMutableStringIntKV().getMutableMap() + .putAll(values); + return this; + } + + private com.google.protobuf.MapField< + Long, Integer> longIntKV_; + private com.google.protobuf.MapField + internalGetLongIntKV() { + if (longIntKV_ == null) { + return com.google.protobuf.MapField.emptyMapField( + LongIntKVDefaultEntryHolder.defaultEntry); + } + return longIntKV_; + } + private com.google.protobuf.MapField + internalGetMutableLongIntKV() { + onChanged();; + if (longIntKV_ == null) { + longIntKV_ = com.google.protobuf.MapField.newMapField( + LongIntKVDefaultEntryHolder.defaultEntry); + } + if (!longIntKV_.isMutable()) { + longIntKV_ = longIntKV_.copy(); + } + return longIntKV_; + } + + public int getLongIntKVCount() { + return internalGetLongIntKV().getMap().size(); + } + /** + * map<int64, int32> long_int_k_v = 22; + */ + + @Override + public boolean containsLongIntKV( + long key) { + + return internalGetLongIntKV().getMap().containsKey(key); + } + /** + * Use {@link #getLongIntKVMap()} instead. + */ + @Override + @Deprecated + public java.util.Map getLongIntKV() { + return getLongIntKVMap(); + } + /** + * map<int64, int32> long_int_k_v = 22; + */ + @Override + + public java.util.Map getLongIntKVMap() { + return internalGetLongIntKV().getMap(); + } + /** + * map<int64, int32> long_int_k_v = 22; + */ + @Override + + public int getLongIntKVOrDefault( + long key, + int defaultValue) { + + java.util.Map map = + internalGetLongIntKV().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + * map<int64, int32> long_int_k_v = 22; + */ + @Override + + public int getLongIntKVOrThrow( + long key) { + + java.util.Map map = + internalGetLongIntKV().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); + } + + public Builder clearLongIntKV() { + internalGetMutableLongIntKV().getMutableMap() + .clear(); + return this; + } + /** + * map<int64, int32> long_int_k_v = 22; + */ + + public Builder removeLongIntKV( + long key) { + + internalGetMutableLongIntKV().getMutableMap() + .remove(key); + return this; + } + /** + * Use alternate mutation accessors instead. + */ + @Deprecated + public java.util.Map + getMutableLongIntKV() { + return internalGetMutableLongIntKV().getMutableMap(); + } + /** + * map<int64, int32> long_int_k_v = 22; + */ + public Builder putLongIntKV( + long key, + int value) { + + + internalGetMutableLongIntKV().getMutableMap() + .put(key, value); + return this; + } + /** + * map<int64, int32> long_int_k_v = 22; + */ + + public Builder putAllLongIntKV( + java.util.Map values) { + internalGetMutableLongIntKV().getMutableMap() + .putAll(values); + return this; + } + @Override + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + @Override + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:PBTestMessage) + } + + // @@protoc_insertion_point(class_scope:PBTestMessage) + private static final PBTestMessage DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new PBTestMessage(); + } + + public static PBTestMessage getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + @Override + public PBTestMessage parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new PBTestMessage(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + @Override + public PBTestMessage getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface PBPersonOrBuilder extends + // @@protoc_insertion_point(interface_extends:PBPerson) + com.google.protobuf.MessageOrBuilder { + + /** + * int64 id = 1; + * @return The id. + */ + long getId(); + + /** + * string name = 2; + * @return The name. + */ + String getName(); + /** + * string name = 2; + * @return The bytes for name. + */ + com.google.protobuf.ByteString + getNameBytes(); + + /** + * .google.protobuf.StringValue phone = 3; + * @return Whether the phone field is set. + */ + boolean hasPhone(); + /** + * .google.protobuf.StringValue phone = 3; + * @return The phone. + */ + com.google.protobuf.StringValue getPhone(); + /** + * .google.protobuf.StringValue phone = 3; + */ + com.google.protobuf.StringValueOrBuilder getPhoneOrBuilder(); + + /** + * repeated string hobbies = 4; + * @return A list containing the hobbies. + */ + java.util.List + getHobbiesList(); + /** + * repeated string hobbies = 4; + * @return The count of hobbies. + */ + int getHobbiesCount(); + /** + * repeated string hobbies = 4; + * @param index The index of the element to return. + * @return The hobbies at the given index. + */ + String getHobbies(int index); + /** + * repeated string hobbies = 4; + * @param index The index of the value to return. + * @return The bytes of the hobbies at the given index. + */ + com.google.protobuf.ByteString + getHobbiesBytes(int index); + } + /** + * Protobuf type {@code PBPerson} + */ + public static final class PBPerson extends + GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:PBPerson) + PBPersonOrBuilder { + private static final long serialVersionUID = 0L; + // Use PBPerson.newBuilder() to construct. + private PBPerson(GeneratedMessageV3.Builder builder) { + super(builder); + } + private PBPerson() { + name_ = ""; + hobbies_ = com.google.protobuf.LazyStringArrayList.EMPTY; + } + + @Override + @SuppressWarnings({"unused"}) + protected Object newInstance( + UnusedPrivateParameter unused) { + return new PBPerson(); + } + + @Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private PBPerson( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + case 8: { + + id_ = input.readInt64(); + break; + } + case 18: { + String s = input.readStringRequireUtf8(); + + name_ = s; + break; + } + case 26: { + com.google.protobuf.StringValue.Builder subBuilder = null; + if (phone_ != null) { + subBuilder = phone_.toBuilder(); + } + phone_ = input.readMessage(com.google.protobuf.StringValue.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(phone_); + phone_ = subBuilder.buildPartial(); + } + + break; + } + case 34: { + String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000001) != 0)) { + hobbies_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000001; + } + hobbies_.add(s); + break; + } + default: { + if (!parseUnknownField( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) != 0)) { + hobbies_ = hobbies_.getUnmodifiableView(); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ConversionTest.internal_static_PBPerson_descriptor; + } + + @Override + protected GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return ConversionTest.internal_static_PBPerson_fieldAccessorTable + .ensureFieldAccessorsInitialized( + PBPerson.class, Builder.class); + } + + public static final int ID_FIELD_NUMBER = 1; + private long id_; + /** + * int64 id = 1; + * @return The id. + */ + @Override + public long getId() { + return id_; + } + + public static final int NAME_FIELD_NUMBER = 2; + private volatile Object name_; + /** + * string name = 2; + * @return The name. + */ + @Override + public String getName() { + Object ref = name_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + name_ = s; + return s; + } + } + /** + * string name = 2; + * @return The bytes for name. + */ + @Override + public com.google.protobuf.ByteString + getNameBytes() { + Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int PHONE_FIELD_NUMBER = 3; + private com.google.protobuf.StringValue phone_; + /** + * .google.protobuf.StringValue phone = 3; + * @return Whether the phone field is set. + */ + @Override + public boolean hasPhone() { + return phone_ != null; + } + /** + * .google.protobuf.StringValue phone = 3; + * @return The phone. + */ + @Override + public com.google.protobuf.StringValue getPhone() { + return phone_ == null ? com.google.protobuf.StringValue.getDefaultInstance() : phone_; + } + /** + * .google.protobuf.StringValue phone = 3; + */ + @Override + public com.google.protobuf.StringValueOrBuilder getPhoneOrBuilder() { + return getPhone(); + } + + public static final int HOBBIES_FIELD_NUMBER = 4; + private com.google.protobuf.LazyStringList hobbies_; + /** + * repeated string hobbies = 4; + * @return A list containing the hobbies. + */ + public com.google.protobuf.ProtocolStringList + getHobbiesList() { + return hobbies_; + } + /** + * repeated string hobbies = 4; + * @return The count of hobbies. + */ + public int getHobbiesCount() { + return hobbies_.size(); + } + /** + * repeated string hobbies = 4; + * @param index The index of the element to return. + * @return The hobbies at the given index. + */ + public String getHobbies(int index) { + return hobbies_.get(index); + } + /** + * repeated string hobbies = 4; + * @param index The index of the value to return. + * @return The bytes of the hobbies at the given index. + */ + public com.google.protobuf.ByteString + getHobbiesBytes(int index) { + return hobbies_.getByteString(index); + } + + private byte memoizedIsInitialized = -1; + @Override + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + @Override + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (id_ != 0L) { + output.writeInt64(1, id_); + } + if (!getNameBytes().isEmpty()) { + GeneratedMessageV3.writeString(output, 2, name_); + } + if (phone_ != null) { + output.writeMessage(3, getPhone()); + } + for (int i = 0; i < hobbies_.size(); i++) { + GeneratedMessageV3.writeString(output, 4, hobbies_.getRaw(i)); + } + unknownFields.writeTo(output); + } + + @Override + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (id_ != 0L) { + size += com.google.protobuf.CodedOutputStream + .computeInt64Size(1, id_); + } + if (!getNameBytes().isEmpty()) { + size += GeneratedMessageV3.computeStringSize(2, name_); + } + if (phone_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, getPhone()); + } + { + int dataSize = 0; + for (int i = 0; i < hobbies_.size(); i++) { + dataSize += computeStringSizeNoTag(hobbies_.getRaw(i)); + } + size += dataSize; + size += 1 * getHobbiesList().size(); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof PBPerson)) { + return super.equals(obj); + } + PBPerson other = (PBPerson) obj; + + if (getId() + != other.getId()) return false; + if (!getName() + .equals(other.getName())) return false; + if (hasPhone() != other.hasPhone()) return false; + if (hasPhone()) { + if (!getPhone() + .equals(other.getPhone())) return false; + } + if (!getHobbiesList() + .equals(other.getHobbiesList())) return false; + if (!unknownFields.equals(other.unknownFields)) return false; + return true; + } + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + ID_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashLong( + getId()); + hash = (37 * hash) + NAME_FIELD_NUMBER; + hash = (53 * hash) + getName().hashCode(); + if (hasPhone()) { + hash = (37 * hash) + PHONE_FIELD_NUMBER; + hash = (53 * hash) + getPhone().hashCode(); + } + if (getHobbiesCount() > 0) { + hash = (37 * hash) + HOBBIES_FIELD_NUMBER; + hash = (53 * hash) + getHobbiesList().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static PBPerson parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static PBPerson parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static PBPerson parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static PBPerson parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static PBPerson parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static PBPerson parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static PBPerson parseFrom(java.io.InputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static PBPerson parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static PBPerson parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static PBPerson parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static PBPerson parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static PBPerson parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + @Override + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(PBPerson prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + @Override + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @Override + protected Builder newBuilderForType( + GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code PBPerson} + */ + public static final class Builder extends + GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:PBPerson) + PBPersonOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ConversionTest.internal_static_PBPerson_descriptor; + } + + @Override + protected GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return ConversionTest.internal_static_PBPerson_fieldAccessorTable + .ensureFieldAccessorsInitialized( + PBPerson.class, Builder.class); + } + + // Construct using pbconverts.ConversionTest.PBPerson.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + @Override + public Builder clear() { + super.clear(); + id_ = 0L; + + name_ = ""; + + if (phoneBuilder_ == null) { + phone_ = null; + } else { + phone_ = null; + phoneBuilder_ = null; + } + hobbies_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + return this; + } + + @Override + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return ConversionTest.internal_static_PBPerson_descriptor; + } + + @Override + public PBPerson getDefaultInstanceForType() { + return PBPerson.getDefaultInstance(); + } + + @Override + public PBPerson build() { + PBPerson result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + @Override + public PBPerson buildPartial() { + PBPerson result = new PBPerson(this); + int from_bitField0_ = bitField0_; + result.id_ = id_; + result.name_ = name_; + if (phoneBuilder_ == null) { + result.phone_ = phone_; + } else { + result.phone_ = phoneBuilder_.build(); + } + if (((bitField0_ & 0x00000001) != 0)) { + hobbies_ = hobbies_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000001); + } + result.hobbies_ = hobbies_; + onBuilt(); + return result; + } + + @Override + public Builder clone() { + return super.clone(); + } + @Override + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return super.setField(field, value); + } + @Override + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return super.clearField(field); + } + @Override + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return super.clearOneof(oneof); + } + @Override + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, Object value) { + return super.setRepeatedField(field, index, value); + } + @Override + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return super.addRepeatedField(field, value); + } + @Override + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof PBPerson) { + return mergeFrom((PBPerson)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(PBPerson other) { + if (other == PBPerson.getDefaultInstance()) return this; + if (other.getId() != 0L) { + setId(other.getId()); + } + if (!other.getName().isEmpty()) { + name_ = other.name_; + onChanged(); + } + if (other.hasPhone()) { + mergePhone(other.getPhone()); + } + if (!other.hobbies_.isEmpty()) { + if (hobbies_.isEmpty()) { + hobbies_ = other.hobbies_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureHobbiesIsMutable(); + hobbies_.addAll(other.hobbies_); + } + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + @Override + public final boolean isInitialized() { + return true; + } + + @Override + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + PBPerson parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (PBPerson) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + private long id_ ; + /** + * int64 id = 1; + * @return The id. + */ + @Override + public long getId() { + return id_; + } + /** + * int64 id = 1; + * @param value The id to set. + * @return This builder for chaining. + */ + public Builder setId(long value) { + + id_ = value; + onChanged(); + return this; + } + /** + * int64 id = 1; + * @return This builder for chaining. + */ + public Builder clearId() { + + id_ = 0L; + onChanged(); + return this; + } + + private Object name_ = ""; + /** + * string name = 2; + * @return The name. + */ + public String getName() { + Object ref = name_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + name_ = s; + return s; + } else { + return (String) ref; + } + } + /** + * string name = 2; + * @return The bytes for name. + */ + public com.google.protobuf.ByteString + getNameBytes() { + Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * string name = 2; + * @param value The name to set. + * @return This builder for chaining. + */ + public Builder setName( + String value) { + if (value == null) { + throw new NullPointerException(); + } + + name_ = value; + onChanged(); + return this; + } + /** + * string name = 2; + * @return This builder for chaining. + */ + public Builder clearName() { + + name_ = getDefaultInstance().getName(); + onChanged(); + return this; + } + /** + * string name = 2; + * @param value The bytes for name to set. + * @return This builder for chaining. + */ + public Builder setNameBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + name_ = value; + onChanged(); + return this; + } + + private com.google.protobuf.StringValue phone_; + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.StringValue, com.google.protobuf.StringValue.Builder, com.google.protobuf.StringValueOrBuilder> phoneBuilder_; + /** + * .google.protobuf.StringValue phone = 3; + * @return Whether the phone field is set. + */ + public boolean hasPhone() { + return phoneBuilder_ != null || phone_ != null; + } + /** + * .google.protobuf.StringValue phone = 3; + * @return The phone. + */ + public com.google.protobuf.StringValue getPhone() { + if (phoneBuilder_ == null) { + return phone_ == null ? com.google.protobuf.StringValue.getDefaultInstance() : phone_; + } else { + return phoneBuilder_.getMessage(); + } + } + /** + * .google.protobuf.StringValue phone = 3; + */ + public Builder setPhone(com.google.protobuf.StringValue value) { + if (phoneBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + phone_ = value; + onChanged(); + } else { + phoneBuilder_.setMessage(value); + } + + return this; + } + /** + * .google.protobuf.StringValue phone = 3; + */ + public Builder setPhone( + com.google.protobuf.StringValue.Builder builderForValue) { + if (phoneBuilder_ == null) { + phone_ = builderForValue.build(); + onChanged(); + } else { + phoneBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + * .google.protobuf.StringValue phone = 3; + */ + public Builder mergePhone(com.google.protobuf.StringValue value) { + if (phoneBuilder_ == null) { + if (phone_ != null) { + phone_ = + com.google.protobuf.StringValue.newBuilder(phone_).mergeFrom(value).buildPartial(); + } else { + phone_ = value; + } + onChanged(); + } else { + phoneBuilder_.mergeFrom(value); + } + + return this; + } + /** + * .google.protobuf.StringValue phone = 3; + */ + public Builder clearPhone() { + if (phoneBuilder_ == null) { + phone_ = null; + onChanged(); + } else { + phone_ = null; + phoneBuilder_ = null; + } + + return this; + } + /** + * .google.protobuf.StringValue phone = 3; + */ + public com.google.protobuf.StringValue.Builder getPhoneBuilder() { + + onChanged(); + return getPhoneFieldBuilder().getBuilder(); + } + /** + * .google.protobuf.StringValue phone = 3; + */ + public com.google.protobuf.StringValueOrBuilder getPhoneOrBuilder() { + if (phoneBuilder_ != null) { + return phoneBuilder_.getMessageOrBuilder(); + } else { + return phone_ == null ? + com.google.protobuf.StringValue.getDefaultInstance() : phone_; + } + } + /** + * .google.protobuf.StringValue phone = 3; + */ + private com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.StringValue, com.google.protobuf.StringValue.Builder, com.google.protobuf.StringValueOrBuilder> + getPhoneFieldBuilder() { + if (phoneBuilder_ == null) { + phoneBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + com.google.protobuf.StringValue, com.google.protobuf.StringValue.Builder, com.google.protobuf.StringValueOrBuilder>( + getPhone(), + getParentForChildren(), + isClean()); + phone_ = null; + } + return phoneBuilder_; + } + + private com.google.protobuf.LazyStringList hobbies_ = com.google.protobuf.LazyStringArrayList.EMPTY; + private void ensureHobbiesIsMutable() { + if (!((bitField0_ & 0x00000001) != 0)) { + hobbies_ = new com.google.protobuf.LazyStringArrayList(hobbies_); + bitField0_ |= 0x00000001; + } + } + /** + * repeated string hobbies = 4; + * @return A list containing the hobbies. + */ + public com.google.protobuf.ProtocolStringList + getHobbiesList() { + return hobbies_.getUnmodifiableView(); + } + /** + * repeated string hobbies = 4; + * @return The count of hobbies. + */ + public int getHobbiesCount() { + return hobbies_.size(); + } + /** + * repeated string hobbies = 4; + * @param index The index of the element to return. + * @return The hobbies at the given index. + */ + public String getHobbies(int index) { + return hobbies_.get(index); + } + /** + * repeated string hobbies = 4; + * @param index The index of the value to return. + * @return The bytes of the hobbies at the given index. + */ + public com.google.protobuf.ByteString + getHobbiesBytes(int index) { + return hobbies_.getByteString(index); + } + /** + * repeated string hobbies = 4; + * @param index The index to set the value at. + * @param value The hobbies to set. + * @return This builder for chaining. + */ + public Builder setHobbies( + int index, String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureHobbiesIsMutable(); + hobbies_.set(index, value); + onChanged(); + return this; + } + /** + * repeated string hobbies = 4; + * @param value The hobbies to add. + * @return This builder for chaining. + */ + public Builder addHobbies( + String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureHobbiesIsMutable(); + hobbies_.add(value); + onChanged(); + return this; + } + /** + * repeated string hobbies = 4; + * @param values The hobbies to add. + * @return This builder for chaining. + */ + public Builder addAllHobbies( + Iterable values) { + ensureHobbiesIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll( + values, hobbies_); + onChanged(); + return this; + } + /** + * repeated string hobbies = 4; + * @return This builder for chaining. + */ + public Builder clearHobbies() { + hobbies_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + onChanged(); + return this; + } + /** + * repeated string hobbies = 4; + * @param value The bytes of the hobbies to add. + * @return This builder for chaining. + */ + public Builder addHobbiesBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureHobbiesIsMutable(); + hobbies_.add(value); + onChanged(); + return this; + } + @Override + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + @Override + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:PBPerson) + } + + // @@protoc_insertion_point(class_scope:PBPerson) + private static final PBPerson DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new PBPerson(); + } + + public static PBPerson getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + @Override + public PBPerson parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new PBPerson(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + @Override + public PBPerson getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface PBTestBytesOrBuilder extends + // @@protoc_insertion_point(interface_extends:PBTestBytes) + com.google.protobuf.MessageOrBuilder { + + /** + * bytes test_bytes = 1; + * @return The testBytes. + */ + com.google.protobuf.ByteString getTestBytes(); + } + /** + * Protobuf type {@code PBTestBytes} + */ + public static final class PBTestBytes extends + GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:PBTestBytes) + PBTestBytesOrBuilder { + private static final long serialVersionUID = 0L; + // Use PBTestBytes.newBuilder() to construct. + private PBTestBytes(GeneratedMessageV3.Builder builder) { + super(builder); + } + private PBTestBytes() { + testBytes_ = com.google.protobuf.ByteString.EMPTY; + } + + @Override + @SuppressWarnings({"unused"}) + protected Object newInstance( + GeneratedMessageV3.UnusedPrivateParameter unused) { + return new PBTestBytes(); + } + + @Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private PBTestBytes( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new NullPointerException(); + } + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + case 10: { + + testBytes_ = input.readBytes(); + break; + } + default: { + if (!parseUnknownField( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ConversionTest.internal_static_PBTestBytes_descriptor; + } + + @Override + protected GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return ConversionTest.internal_static_PBTestBytes_fieldAccessorTable + .ensureFieldAccessorsInitialized( + PBTestBytes.class, Builder.class); + } + + public static final int TEST_BYTES_FIELD_NUMBER = 1; + private com.google.protobuf.ByteString testBytes_; + /** + * bytes test_bytes = 1; + * @return The testBytes. + */ + @Override + public com.google.protobuf.ByteString getTestBytes() { + return testBytes_; + } + + private byte memoizedIsInitialized = -1; + @Override + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + @Override + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (!testBytes_.isEmpty()) { + output.writeBytes(1, testBytes_); + } + unknownFields.writeTo(output); + } + + @Override + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!testBytes_.isEmpty()) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(1, testBytes_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof PBTestBytes)) { + return super.equals(obj); + } + PBTestBytes other = (PBTestBytes) obj; + + if (!getTestBytes() + .equals(other.getTestBytes())) return false; + if (!unknownFields.equals(other.unknownFields)) return false; + return true; + } + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + TEST_BYTES_FIELD_NUMBER; + hash = (53 * hash) + getTestBytes().hashCode(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static PBTestBytes parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static PBTestBytes parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static PBTestBytes parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static PBTestBytes parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static PBTestBytes parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static PBTestBytes parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static PBTestBytes parseFrom(java.io.InputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static PBTestBytes parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static PBTestBytes parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static PBTestBytes parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static PBTestBytes parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static PBTestBytes parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + @Override + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(PBTestBytes prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + @Override + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @Override + protected Builder newBuilderForType( + GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code PBTestBytes} + */ + public static final class Builder extends + GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:PBTestBytes) + PBTestBytesOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ConversionTest.internal_static_PBTestBytes_descriptor; + } + + @Override + protected GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return ConversionTest.internal_static_PBTestBytes_fieldAccessorTable + .ensureFieldAccessorsInitialized( + PBTestBytes.class, Builder.class); + } + + // Construct using pbconverts.ConversionTest.PBTestBytes.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + @Override + public Builder clear() { + super.clear(); + testBytes_ = com.google.protobuf.ByteString.EMPTY; + + return this; + } + + @Override + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return ConversionTest.internal_static_PBTestBytes_descriptor; + } + + @Override + public PBTestBytes getDefaultInstanceForType() { + return PBTestBytes.getDefaultInstance(); + } + + @Override + public PBTestBytes build() { + PBTestBytes result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + @Override + public PBTestBytes buildPartial() { + PBTestBytes result = new PBTestBytes(this); + result.testBytes_ = testBytes_; + onBuilt(); + return result; + } + + @Override + public Builder clone() { + return super.clone(); + } + @Override + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return super.setField(field, value); + } + @Override + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return super.clearField(field); + } + @Override + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return super.clearOneof(oneof); + } + @Override + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, Object value) { + return super.setRepeatedField(field, index, value); + } + @Override + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return super.addRepeatedField(field, value); + } + @Override + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof PBTestBytes) { + return mergeFrom((PBTestBytes)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(PBTestBytes other) { + if (other == PBTestBytes.getDefaultInstance()) return this; + if (other.getTestBytes() != com.google.protobuf.ByteString.EMPTY) { + setTestBytes(other.getTestBytes()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + @Override + public final boolean isInitialized() { + return true; + } + + @Override + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + PBTestBytes parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (PBTestBytes) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private com.google.protobuf.ByteString testBytes_ = com.google.protobuf.ByteString.EMPTY; + /** + * bytes test_bytes = 1; + * @return The testBytes. + */ + @Override + public com.google.protobuf.ByteString getTestBytes() { + return testBytes_; + } + /** + * bytes test_bytes = 1; + * @param value The testBytes to set. + * @return This builder for chaining. + */ + public Builder setTestBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + + testBytes_ = value; + onChanged(); + return this; + } + /** + * bytes test_bytes = 1; + * @return This builder for chaining. + */ + public Builder clearTestBytes() { + + testBytes_ = getDefaultInstance().getTestBytes(); + onChanged(); + return this; + } + @Override + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + @Override + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:PBTestBytes) + } + + // @@protoc_insertion_point(class_scope:PBTestBytes) + private static final PBTestBytes DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new PBTestBytes(); + } + + public static PBTestBytes getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + @Override + public PBTestBytes parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new PBTestBytes(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + @Override + public PBTestBytes getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface IntMessageOrBuilder extends + // @@protoc_insertion_point(interface_extends:IntMessage) + com.google.protobuf.MessageOrBuilder { + + /** + * int32 value = 1; + * @return The value. + */ + int getValue(); + } + /** + * Protobuf type {@code IntMessage} + */ + public static final class IntMessage extends + GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:IntMessage) + IntMessageOrBuilder { + private static final long serialVersionUID = 0L; + // Use IntMessage.newBuilder() to construct. + private IntMessage(GeneratedMessageV3.Builder builder) { + super(builder); + } + private IntMessage() { + } + + @Override + @SuppressWarnings({"unused"}) + protected Object newInstance( + UnusedPrivateParameter unused) { + return new IntMessage(); + } + + @Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private IntMessage( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new NullPointerException(); + } + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + case 8: { + + value_ = input.readInt32(); + break; + } + default: { + if (!parseUnknownField( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ConversionTest.internal_static_IntMessage_descriptor; + } + + @Override + protected FieldAccessorTable + internalGetFieldAccessorTable() { + return ConversionTest.internal_static_IntMessage_fieldAccessorTable + .ensureFieldAccessorsInitialized( + IntMessage.class, Builder.class); + } + + public static final int VALUE_FIELD_NUMBER = 1; + private int value_; + /** + * int32 value = 1; + * @return The value. + */ + @Override + public int getValue() { + return value_; + } + + private byte memoizedIsInitialized = -1; + @Override + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + @Override + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (value_ != 0) { + output.writeInt32(1, value_); + } + unknownFields.writeTo(output); + } + + @Override + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (value_ != 0) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, value_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof IntMessage)) { + return super.equals(obj); + } + IntMessage other = (IntMessage) obj; + + if (getValue() + != other.getValue()) return false; + if (!unknownFields.equals(other.unknownFields)) return false; + return true; + } + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + VALUE_FIELD_NUMBER; + hash = (53 * hash) + getValue(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static IntMessage parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static IntMessage parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static IntMessage parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static IntMessage parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static IntMessage parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static IntMessage parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static IntMessage parseFrom(java.io.InputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static IntMessage parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static IntMessage parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static IntMessage parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static IntMessage parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static IntMessage parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + @Override + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(IntMessage prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + @Override + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @Override + protected Builder newBuilderForType( + BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code IntMessage} + */ + public static final class Builder extends + GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:IntMessage) + IntMessageOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ConversionTest.internal_static_IntMessage_descriptor; + } + + @Override + protected FieldAccessorTable + internalGetFieldAccessorTable() { + return ConversionTest.internal_static_IntMessage_fieldAccessorTable + .ensureFieldAccessorsInitialized( + IntMessage.class, Builder.class); + } + + // Construct using pbconverts.ConversionTest.IntMessage.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + @Override + public Builder clear() { + super.clear(); + value_ = 0; + + return this; + } + + @Override + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return ConversionTest.internal_static_IntMessage_descriptor; + } + + @Override + public IntMessage getDefaultInstanceForType() { + return IntMessage.getDefaultInstance(); + } + + @Override + public IntMessage build() { + IntMessage result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + @Override + public IntMessage buildPartial() { + IntMessage result = new IntMessage(this); + result.value_ = value_; + onBuilt(); + return result; + } + + @Override + public Builder clone() { + return super.clone(); + } + @Override + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return super.setField(field, value); + } + @Override + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return super.clearField(field); + } + @Override + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return super.clearOneof(oneof); + } + @Override + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, Object value) { + return super.setRepeatedField(field, index, value); + } + @Override + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return super.addRepeatedField(field, value); + } + @Override + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof IntMessage) { + return mergeFrom((IntMessage)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(IntMessage other) { + if (other == IntMessage.getDefaultInstance()) return this; + if (other.getValue() != 0) { + setValue(other.getValue()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + @Override + public final boolean isInitialized() { + return true; + } + + @Override + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + IntMessage parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (IntMessage) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int value_ ; + /** + * int32 value = 1; + * @return The value. + */ + @Override + public int getValue() { + return value_; + } + /** + * int32 value = 1; + * @param value The value to set. + * @return This builder for chaining. + */ + public Builder setValue(int value) { + + value_ = value; + onChanged(); + return this; + } + /** + * int32 value = 1; + * @return This builder for chaining. + */ + public Builder clearValue() { + + value_ = 0; + onChanged(); + return this; + } + @Override + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + @Override + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:IntMessage) + } + + // @@protoc_insertion_point(class_scope:IntMessage) + private static final IntMessage DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new IntMessage(); + } + + public static IntMessage getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + @Override + public IntMessage parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new IntMessage(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + @Override + public IntMessage getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface StringMessageOrBuilder extends + // @@protoc_insertion_point(interface_extends:StringMessage) + com.google.protobuf.MessageOrBuilder { + + /** + * string value = 1; + * @return The value. + */ + String getValue(); + /** + * string value = 1; + * @return The bytes for value. + */ + com.google.protobuf.ByteString + getValueBytes(); + } + /** + * Protobuf type {@code StringMessage} + */ + public static final class StringMessage extends + GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:StringMessage) + StringMessageOrBuilder { + private static final long serialVersionUID = 0L; + // Use StringMessage.newBuilder() to construct. + private StringMessage(GeneratedMessageV3.Builder builder) { + super(builder); + } + private StringMessage() { + value_ = ""; + } + + @Override + @SuppressWarnings({"unused"}) + protected Object newInstance( + UnusedPrivateParameter unused) { + return new StringMessage(); + } + + @Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private StringMessage( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new NullPointerException(); + } + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + case 10: { + String s = input.readStringRequireUtf8(); + + value_ = s; + break; + } + default: { + if (!parseUnknownField( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ConversionTest.internal_static_StringMessage_descriptor; + } + + @Override + protected FieldAccessorTable + internalGetFieldAccessorTable() { + return ConversionTest.internal_static_StringMessage_fieldAccessorTable + .ensureFieldAccessorsInitialized( + StringMessage.class, Builder.class); + } + + public static final int VALUE_FIELD_NUMBER = 1; + private volatile Object value_; + /** + * string value = 1; + * @return The value. + */ + @Override + public String getValue() { + Object ref = value_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + value_ = s; + return s; + } + } + /** + * string value = 1; + * @return The bytes for value. + */ + @Override + public com.google.protobuf.ByteString + getValueBytes() { + Object ref = value_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (String) ref); + value_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private byte memoizedIsInitialized = -1; + @Override + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + @Override + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (!getValueBytes().isEmpty()) { + GeneratedMessageV3.writeString(output, 1, value_); + } + unknownFields.writeTo(output); + } + + @Override + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!getValueBytes().isEmpty()) { + size += GeneratedMessageV3.computeStringSize(1, value_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof StringMessage)) { + return super.equals(obj); + } + StringMessage other = (StringMessage) obj; + + if (!getValue() + .equals(other.getValue())) return false; + if (!unknownFields.equals(other.unknownFields)) return false; + return true; + } + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + VALUE_FIELD_NUMBER; + hash = (53 * hash) + getValue().hashCode(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static StringMessage parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static StringMessage parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static StringMessage parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static StringMessage parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static StringMessage parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static StringMessage parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static StringMessage parseFrom(java.io.InputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static StringMessage parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static StringMessage parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static StringMessage parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static StringMessage parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static StringMessage parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + @Override + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(StringMessage prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + @Override + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @Override + protected Builder newBuilderForType( + BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code StringMessage} + */ + public static final class Builder extends + GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:StringMessage) + StringMessageOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return ConversionTest.internal_static_StringMessage_descriptor; + } + + @Override + protected FieldAccessorTable + internalGetFieldAccessorTable() { + return ConversionTest.internal_static_StringMessage_fieldAccessorTable + .ensureFieldAccessorsInitialized( + StringMessage.class, Builder.class); + } + + // Construct using pbconverts.ConversionTest.StringMessage.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + @Override + public Builder clear() { + super.clear(); + value_ = ""; + + return this; + } + + @Override + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return ConversionTest.internal_static_StringMessage_descriptor; + } + + @Override + public StringMessage getDefaultInstanceForType() { + return StringMessage.getDefaultInstance(); + } + + @Override + public StringMessage build() { + StringMessage result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + @Override + public StringMessage buildPartial() { + StringMessage result = new StringMessage(this); + result.value_ = value_; + onBuilt(); + return result; + } + + @Override + public Builder clone() { + return super.clone(); + } + @Override + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return super.setField(field, value); + } + @Override + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return super.clearField(field); + } + @Override + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return super.clearOneof(oneof); + } + @Override + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, Object value) { + return super.setRepeatedField(field, index, value); + } + @Override + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + Object value) { + return super.addRepeatedField(field, value); + } + @Override + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof StringMessage) { + return mergeFrom((StringMessage)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(StringMessage other) { + if (other == StringMessage.getDefaultInstance()) return this; + if (!other.getValue().isEmpty()) { + value_ = other.value_; + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + @Override + public final boolean isInitialized() { + return true; + } + + @Override + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + StringMessage parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (StringMessage) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private Object value_ = ""; + /** + * string value = 1; + * @return The value. + */ + public String getValue() { + Object ref = value_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + value_ = s; + return s; + } else { + return (String) ref; + } + } + /** + * string value = 1; + * @return The bytes for value. + */ + public com.google.protobuf.ByteString + getValueBytes() { + Object ref = value_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (String) ref); + value_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * string value = 1; + * @param value The value to set. + * @return This builder for chaining. + */ + public Builder setValue( + String value) { + if (value == null) { + throw new NullPointerException(); + } + + value_ = value; + onChanged(); + return this; + } + /** + * string value = 1; + * @return This builder for chaining. + */ + public Builder clearValue() { + + value_ = getDefaultInstance().getValue(); + onChanged(); + return this; + } + /** + * string value = 1; + * @param value The bytes for value to set. + * @return This builder for chaining. + */ + public Builder setValueBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + value_ = value; + onChanged(); + return this; + } + @Override + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + @Override + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:StringMessage) + } + + // @@protoc_insertion_point(class_scope:StringMessage) + private static final StringMessage DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new StringMessage(); + } + + public static StringMessage getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + @Override + public StringMessage parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new StringMessage(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + @Override + public StringMessage getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_PBTestMessage_descriptor; + private static final + GeneratedMessageV3.FieldAccessorTable + internal_static_PBTestMessage_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_PBTestMessage_StringStringKVEntry_descriptor; + private static final + GeneratedMessageV3.FieldAccessorTable + internal_static_PBTestMessage_StringStringKVEntry_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_PBTestMessage_LongStringKVEntry_descriptor; + private static final + GeneratedMessageV3.FieldAccessorTable + internal_static_PBTestMessage_LongStringKVEntry_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_PBTestMessage_StringIntKVEntry_descriptor; + private static final + GeneratedMessageV3.FieldAccessorTable + internal_static_PBTestMessage_StringIntKVEntry_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_PBTestMessage_LongIntKVEntry_descriptor; + private static final + GeneratedMessageV3.FieldAccessorTable + internal_static_PBTestMessage_LongIntKVEntry_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_PBPerson_descriptor; + private static final + GeneratedMessageV3.FieldAccessorTable + internal_static_PBPerson_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_PBTestBytes_descriptor; + private static final + GeneratedMessageV3.FieldAccessorTable + internal_static_PBTestBytes_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_IntMessage_descriptor; + private static final + GeneratedMessageV3.FieldAccessorTable + internal_static_IntMessage_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_StringMessage_descriptor; + private static final + GeneratedMessageV3.FieldAccessorTable + internal_static_StringMessage_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor + getDescriptor() { + return descriptor; + } + private static com.google.protobuf.Descriptors.FileDescriptor + descriptor; + static { + String[] descriptorData = { + "\n\025conversion_test.proto\032\036google/protobuf" + + "/wrappers.proto\032\037google/protobuf/timesta" + + "mp.proto\"\223\010\n\rPBTestMessage\022\021\n\tint_value\030" + + "\001 \001(\005\022\022\n\nlong_value\030\002 \001(\003\022\023\n\013float_value" + + "\030\003 \001(\002\022\024\n\014double_value\030\004 \001(\001\022\022\n\nbool_val" + + "ue\030\005 \001(\010\022\024\n\014string_value\030\006 \001(\t\022,\n\007int_Op" + + "t\030\007 \001(\0132\033.google.protobuf.Int32Value\022-\n\010" + + "long_Opt\030\010 \001(\0132\033.google.protobuf.Int64Va" + + "lue\022.\n\tfloat_Opt\030\t \001(\0132\033.google.protobuf" + + ".FloatValue\0220\n\ndouble_opt\030\n \001(\0132\034.google" + + ".protobuf.DoubleValue\022,\n\010bool_opt\030\013 \001(\0132" + + "\032.google.protobuf.BoolValue\0220\n\nstring_op" + + "t\030\014 \001(\0132\034.google.protobuf.StringValue\022(\n" + + "\004time\030\r \001(\0132\032.google.protobuf.Timestamp\022" + + ",\n\010time_opt\030\016 \001(\0132\032.google.protobuf.Time" + + "stamp\022\021\n\tint_array\030\017 \003(\005\022\024\n\014string_array" + + "\030\020 \003(\t\022\037\n\014person_array\030\021 \003(\0132\t.PBPerson\022" + + "\013\n\003seq\030\022 \003(\001\022=\n\021string_string_k_v\030\023 \003(\0132" + + "\".PBTestMessage.StringStringKVEntry\0229\n\017l" + + "ong_string_k_v\030\024 \003(\0132 .PBTestMessage.Lon" + + "gStringKVEntry\0227\n\016string_int_k_v\030\025 \003(\0132\037" + + ".PBTestMessage.StringIntKVEntry\0223\n\014long_" + + "int_k_v\030\026 \003(\0132\035.PBTestMessage.LongIntKVE" + + "ntry\0325\n\023StringStringKVEntry\022\013\n\003key\030\001 \001(\t" + + "\022\r\n\005value\030\002 \001(\t:\0028\001\0323\n\021LongStringKVEntry" + + "\022\013\n\003key\030\001 \001(\003\022\r\n\005value\030\002 \001(\t:\0028\001\0322\n\020Stri" + + "ngIntKVEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005value\030\002 \001(\005" + + ":\0028\001\0320\n\016LongIntKVEntry\022\013\n\003key\030\001 \001(\003\022\r\n\005v" + + "alue\030\002 \001(\005:\0028\001\"b\n\010PBPerson\022\n\n\002id\030\001 \001(\003\022\014" + + "\n\004name\030\002 \001(\t\022+\n\005phone\030\003 \001(\0132\034.google.pro" + + "tobuf.StringValue\022\017\n\007hobbies\030\004 \003(\t\"!\n\013PB" + + "TestBytes\022\022\n\ntest_bytes\030\001 \001(\014\"\033\n\nIntMess" + + "age\022\r\n\005value\030\001 \001(\005\"\036\n\rStringMessage\022\r\n\005v" + + "alue\030\001 \001(\tB\014\n\npbconvertsb\006proto3" + }; + descriptor = com.google.protobuf.Descriptors.FileDescriptor + .internalBuildGeneratedFileFrom(descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + com.google.protobuf.WrappersProto.getDescriptor(), + com.google.protobuf.TimestampProto.getDescriptor(), + }); + internal_static_PBTestMessage_descriptor = + getDescriptor().getMessageTypes().get(0); + internal_static_PBTestMessage_fieldAccessorTable = new + GeneratedMessageV3.FieldAccessorTable( + internal_static_PBTestMessage_descriptor, + new String[] { "IntValue", "LongValue", "FloatValue", "DoubleValue", "BoolValue", "StringValue", "IntOpt", "LongOpt", "FloatOpt", "DoubleOpt", "BoolOpt", "StringOpt", "Time", "TimeOpt", "IntArray", "StringArray", "PersonArray", "Seq", "StringStringKV", "LongStringKV", "StringIntKV", "LongIntKV", }); + internal_static_PBTestMessage_StringStringKVEntry_descriptor = + internal_static_PBTestMessage_descriptor.getNestedTypes().get(0); + internal_static_PBTestMessage_StringStringKVEntry_fieldAccessorTable = new + GeneratedMessageV3.FieldAccessorTable( + internal_static_PBTestMessage_StringStringKVEntry_descriptor, + new String[] { "Key", "Value", }); + internal_static_PBTestMessage_LongStringKVEntry_descriptor = + internal_static_PBTestMessage_descriptor.getNestedTypes().get(1); + internal_static_PBTestMessage_LongStringKVEntry_fieldAccessorTable = new + GeneratedMessageV3.FieldAccessorTable( + internal_static_PBTestMessage_LongStringKVEntry_descriptor, + new String[] { "Key", "Value", }); + internal_static_PBTestMessage_StringIntKVEntry_descriptor = + internal_static_PBTestMessage_descriptor.getNestedTypes().get(2); + internal_static_PBTestMessage_StringIntKVEntry_fieldAccessorTable = new + GeneratedMessageV3.FieldAccessorTable( + internal_static_PBTestMessage_StringIntKVEntry_descriptor, + new String[] { "Key", "Value", }); + internal_static_PBTestMessage_LongIntKVEntry_descriptor = + internal_static_PBTestMessage_descriptor.getNestedTypes().get(3); + internal_static_PBTestMessage_LongIntKVEntry_fieldAccessorTable = new + GeneratedMessageV3.FieldAccessorTable( + internal_static_PBTestMessage_LongIntKVEntry_descriptor, + new String[] { "Key", "Value", }); + internal_static_PBPerson_descriptor = + getDescriptor().getMessageTypes().get(1); + internal_static_PBPerson_fieldAccessorTable = new + GeneratedMessageV3.FieldAccessorTable( + internal_static_PBPerson_descriptor, + new String[] { "Id", "Name", "Phone", "Hobbies", }); + internal_static_PBTestBytes_descriptor = + getDescriptor().getMessageTypes().get(2); + internal_static_PBTestBytes_fieldAccessorTable = new + GeneratedMessageV3.FieldAccessorTable( + internal_static_PBTestBytes_descriptor, + new String[] { "TestBytes", }); + internal_static_IntMessage_descriptor = + getDescriptor().getMessageTypes().get(3); + internal_static_IntMessage_fieldAccessorTable = new + GeneratedMessageV3.FieldAccessorTable( + internal_static_IntMessage_descriptor, + new String[] { "Value", }); + internal_static_StringMessage_descriptor = + getDescriptor().getMessageTypes().get(4); + internal_static_StringMessage_fieldAccessorTable = new + GeneratedMessageV3.FieldAccessorTable( + internal_static_StringMessage_descriptor, + new String[] { "Value", }); + com.google.protobuf.WrappersProto.getDescriptor(); + com.google.protobuf.TimestampProto.getDescriptor(); + } + + // @@protoc_insertion_point(outer_class_scope) +} diff --git a/pbconverts/src/test/scala/pbconverts/MessageWithType.scala b/pbconverts/src/test/scala/pbconverts/MessageWithType.scala deleted file mode 100644 index bf81854..0000000 --- a/pbconverts/src/test/scala/pbconverts/MessageWithType.scala +++ /dev/null @@ -1,3 +0,0 @@ -package pbconverts - -case class MessageWithType[T](value: T) diff --git a/pbconverts/src/test/scala/pbconverts/Person.scala b/pbconverts/src/test/scala/pbconverts/Person.scala deleted file mode 100644 index 58970cb..0000000 --- a/pbconverts/src/test/scala/pbconverts/Person.scala +++ /dev/null @@ -1,11 +0,0 @@ -package pbconverts - -import pbconverts.ConversionTest.PBPerson - -case class Person(id: Long, name: String, phone: Option[String], hobbies: Seq[String]) - -object Person { - def default = Person(1L, "name", Some("123"), hobbies = Seq("ping pong")) - - implicit val protoScalable = ProtoScalable[Person, PBPerson] -} diff --git a/pbconverts/src/test/scala/pbconverts/TestMessage.scala b/pbconverts/src/test/scala/pbconverts/TestMessage.scala index 4340178..2f2db1b 100644 --- a/pbconverts/src/test/scala/pbconverts/TestMessage.scala +++ b/pbconverts/src/test/scala/pbconverts/TestMessage.scala @@ -3,80 +3,80 @@ package pbconverts import java.time.ZonedDateTime case class TestMessage( - intValue: Int, - longValue: Long, - floatValue: Float, - doubleValue: Double, - boolValue: Boolean, - stringValue: String, - intOpt: Option[Int], - longOpt: Option[Long], - floatOpt: Option[Float], - doubleOpt: Option[Double], - boolOpt: Option[Boolean], - stringOpt: Option[String], - time: ZonedDateTime, - timeOpt: Option[ZonedDateTime], - intArray: Array[Int], - stringArray: Array[String], - personArray: Array[Person], - seq: Seq[Double], - stringStringKV: Map[String, String], // not convert k or v - longStringKV: Map[Long, String], // convert k, but not v - stringIntKV: Map[String, Int], // convert v, but not k - longIntKV: Map[Long, Int] // convert k and v -) + intValue: Int, + longValue: Long, + floatValue: Float, + doubleValue: Double, + boolValue: Boolean, + stringValue: String, + intOpt: Option[Int], + longOpt: Option[Long], + floatOpt: Option[Float], + doubleOpt: Option[Double], + boolOpt: Option[Boolean], + stringOpt: Option[String], + time: ZonedDateTime, + timeOpt: Option[ZonedDateTime], + intArray: Array[Int], + stringArray: Array[String], +// personArray: Array[Person], + seq: Seq[Double], + stringStringKV: Map[String, String], // not convert k or v + longStringKV: Map[Long, String], // convert k, but not v + stringIntKV: Map[String, Int], // convert v, but not k + longIntKV: Map[Long, Int] // convert k and v + ) object TestMessage { - def default = - TestMessage( - intValue = 64, - longValue = 128, - floatValue = 256.0f, - doubleValue = 512.0, - boolValue = true, - stringValue = "stringValue", - intOpt = Some(64), - longOpt = Some(128), - floatOpt = Some(256.0f), - doubleOpt = Some(512.0), - boolOpt = Some(true), - stringOpt = Some("stringValue"), - time = ZonedDateTime.now(), - timeOpt = Some(ZonedDateTime.now()), - intArray = Array(100, 200, 300), - stringArray = Array("string1", "string2", "string3"), - personArray = Array(Person.default), - seq = Seq(1.0, 2.0, 3.0), - stringStringKV = Map("string1" -> "string1", "string2" -> "string2"), - longStringKV = Map(1L -> "string1", 2L -> "string2"), - stringIntKV = Map("string1" -> 1, "string2" -> 2), - longIntKV = Map(1L -> 1, 2L -> 2) - ) + def default = + TestMessage( + intValue = 64, + longValue = 128, + floatValue = 256.0f, + doubleValue = 512.0, + boolValue = true, + stringValue = "stringValue", + intOpt = Some(64), + longOpt = Some(128), + floatOpt = Some(256.0f), + doubleOpt = Some(512.0), + boolOpt = Some(true), + stringOpt = Some("stringValue"), + time = ZonedDateTime.now(), + timeOpt = Some(ZonedDateTime.now()), + intArray = Array(100, 200, 300), + stringArray = Array("string1", "string2", "string3"), +// personArray = Array(Person.default), + seq = Seq(1.0, 2.0, 3.0), + stringStringKV = Map("string1" -> "string1", "string2" -> "string2"), + longStringKV = Map(1L -> "string1", 2L -> "string2"), + stringIntKV = Map("string1" -> 1, "string2" -> 2), + longIntKV = Map(1L -> 1, 2L -> 2) + ) - def zero: TestMessage = - TestMessage( - intValue = 0, - longValue = 0, - floatValue = 0f, - doubleValue = 0.0, - boolValue = false, - stringValue = "", - intOpt = None, - longOpt = None, - floatOpt = None, - doubleOpt = None, - boolOpt = None, - stringOpt = None, - time = ZonedDateTime.now(), - timeOpt = None, - intArray = Array.empty, - stringArray = Array.empty, - personArray = Array.empty, - seq = Seq.empty, - stringStringKV = Map.empty, - longStringKV = Map.empty, - stringIntKV = Map.empty, - longIntKV = Map.empty - ) -} + def zero: TestMessage = + TestMessage( + intValue = 0, + longValue = 0, + floatValue = 0f, + doubleValue = 0.0, + boolValue = false, + stringValue = "", + intOpt = None, + longOpt = None, + floatOpt = None, + doubleOpt = None, + boolOpt = None, + stringOpt = None, + time = ZonedDateTime.now(), + timeOpt = None, + intArray = Array.empty, + stringArray = Array.empty, +// personArray = Array.empty, + seq = Seq.empty, + stringStringKV = Map.empty, + longStringKV = Map.empty, + stringIntKV = Map.empty, + longIntKV = Map.empty + ) +} \ No newline at end of file From db96fb366dd60c30e40313499954452673f74de9 Mon Sep 17 00:00:00 2001 From: changvvb Date: Wed, 21 Apr 2021 05:02:15 +0800 Subject: [PATCH 03/17] proable work --- .../scala/pbconverts/ProtoScalableMacro.scala | 198 ++++++++++-------- .../src/main/scala/pbconverts/Protoable.scala | 5 +- .../src/main/scala/pbconverts/Test.scala | 8 + .../scala/pbconverts/pbconverts/Test$.class | Bin 0 -> 694 bytes .../scala/pbconverts/pbconverts/Test.class | Bin 0 -> 145 bytes .../scala/pbconverts/pbconverts/Test.tasty | Bin 0 -> 518 bytes .../pbconverts/pbconverts/TestObj$.class | Bin 0 -> 685 bytes .../scala/pbconverts/pbconverts/TestObj.class | Bin 0 -> 303 bytes .../scala/pbconverts/pbconverts/TestObj.tasty | Bin 0 -> 519 bytes ..._test.proto => conversion_test.proto.test} | 0 .../test/scala/pbconverts/ConversionTest.java | 2 +- .../src/test/scala/pbconverts/MapSpec.scala | 35 ++-- 12 files changed, 134 insertions(+), 114 deletions(-) create mode 100644 pbconverts/src/main/scala/pbconverts/Test.scala create mode 100644 pbconverts/src/main/scala/pbconverts/pbconverts/Test$.class create mode 100644 pbconverts/src/main/scala/pbconverts/pbconverts/Test.class create mode 100644 pbconverts/src/main/scala/pbconverts/pbconverts/Test.tasty create mode 100644 pbconverts/src/main/scala/pbconverts/pbconverts/TestObj$.class create mode 100644 pbconverts/src/main/scala/pbconverts/pbconverts/TestObj.class create mode 100644 pbconverts/src/main/scala/pbconverts/pbconverts/TestObj.tasty rename pbconverts/src/test/protobuf/{conversion_test.proto => conversion_test.proto.test} (100%) diff --git a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala index 86dab71..e99ec47 100644 --- a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala +++ b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala @@ -14,29 +14,44 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ private[this] val protoClassType = quotas.reflect.TypeRepr.of[M](using typeM) private[this] val protoClassSymbol: quotas.reflect.Symbol = quotas.reflect.TypeReprMethods.classSymbol(protoClassType).get - private[this] val protoClassSymbolCompanion = quotas.reflect.SymbolMethods.companionClass(protoClassSymbol) - private[this] val builderSymbol = quotas.reflect.SymbolMethods.declaredMethod(protoClassSymbolCompanion)("newBuilder").head -// private[this] val newBuilderTree = Apply(builderSymbol.tree.asInstanceOf[Term], List.empty) - private[this] val newProtoTree = New(protoClassSymbol.tree.asInstanceOf[TypeTree]).asExprOf[M] + private[this] val protoClassSymbolClass = quotas.reflect.SymbolMethods.companionClass(protoClassSymbol) + private[this] val protoClassSymbolModule = quotas.reflect.SymbolMethods.companionModule(protoClassSymbol) + private val newBuilderMethod = quotas.reflect.SymbolMethods.memberMethod(protoClassSymbolModule)("newBuilder").last + private val builderType:TypeRepr = newBuilderMethod.tree.asInstanceOf[DefDef].returnTpt.tpe + private val builderClassSymbol:Symbol = builderType.classSymbol.get + private val builderBuildMethod = builderType.classSymbol.get.memberMethod("build").head + private val TypeRef(outer, name) = protoClassType.asInstanceOf[TypeRef] + private val protoCompanionIdent = Ident.apply(TermRef.apply(outer, name)) + private val newBuilderApply = Apply(Select.apply(protoCompanionIdent, newBuilderMethod),List.empty) + private def builderBuildeWithTerms(termsBuilder:Ident => List[Term]) = ValDef.let(Symbol.spliceOwner,"builder",newBuilderApply) { ident => + val terms = termsBuilder.apply(ident) + Block(terms,Apply(Select(ident,builderBuildMethod),Nil)) + } +// private val builderBuildExpr = Apply(ident,) +// private[this] def packageName = ???//q"_root_.pbconverts" +// private[this] def builderIdent = ???//Ident(TermRef("builder")) +// private[this] def entityIdent = ??? //Ident.apply(TermRef(,"entity")) //Ident(TermRef("entity")) +// private[this] def protoIdent = ??? //Ident(TermRef("proto")) + private[this] def implicitlyProtoable(entityType: TypeRepr, protoType: TypeRepr):Term = { + val target = TypeRepr.of[Protoable].appliedTo(List(entityType,protoType)) + Implicits.search(target) match { + case s: ImplicitSearchSuccess => s.tree + case _ => + report.error(s"implicit ${Printer.TypeReprAnsiCode.show(target)} not found") + ??? + } +} - - private val x = quotas.reflect.SymbolMethods.memberMethod(protoClassSymbolCompanion)("newBuilder").head - println(x) - - Apply(protoClassSymbol.tree) - - - private[this] def packageName = ???//q"_root_.pbconverts" - private[this] def builderIdent = ???//Ident(TermRef("builder")) - private[this] def entityIdent = ??? //Ident.apply(TermRef(,"entity")) //Ident(TermRef("entity")) - private[this] def protoIdent = ??? //Ident(TermRef("proto")) - private[this] def implicitlyProtoable(entityType: TypeRepr, protoType: TypeRepr) = ??? //q"implicitly[$packageName.Protoable[$entityType,$protoType]]" - - private[this] def implicitlyScalable(entityType: TypeRepr, protoType: TypeRepr) = ??? //q"implicitly[$packageName.Scalable[$entityType,$protoType]]" + private[this] def implicitlyScalable(entityType: TypeRepr, protoType: TypeRepr):Term = { + Implicits.search(TypeApply('{Scalable}.asTerm,List(TypeIdent(entityType.typeSymbol),TypeIdent(protoType.typeSymbol))).tpe) match { + case s:ImplicitSearchSuccess => s.tree + case _ => ??? + } + } //q"implicitly[$packageName.Scalable[$entityType,$protoType]]" private[this] def isOption(tpe: TypeRepr): Boolean = { tpe <:< TypeRepr.of[Option[_]] @@ -50,9 +65,7 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ private[this] def isMap(tpe: TypeRepr): Boolean = tpe <:< TypeRepr.of[Map[_, _]] || tpe <:< TypeRepr.of[java.util.Map[_, _]] private[this] def getBuilderType(): TypeRepr = { -// TypeReprMethods -// protoType.companion.member(TermName("newBuilder")).asTerm.alternatives.head.asMethod.returnType - ??? + builderType } private trait Processor { @@ -67,23 +80,24 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ // Convert expr (`scalaTree` in this class) to protobuf value private class ToProtoProcessor( - scalaTree: Tree, + protoBuilderIdent:Ident, + scalaTree: Term, override val scalaTreeType: TypeRepr, override val protoFieldName: String ) extends ProtoFieldAnalyst { - private[this] def toProto(t1: TypeRepr, t2: TypeRepr): Tree = { + private[this] def toProto(t1: TypeRepr, t2: TypeRepr): Term = { if (t1 <:< t2) { scalaTree } else { - ??? -// q"${implicitlyProtoable(t1, t2)}.toProto($scalaTree)" + val toProtoMethod = TypeRepr.of[Protoable[_,_]].typeSymbol.memberMethod("toProto").head + Apply(Select(implicitlyProtoable(t1,t2),toProtoMethod),List(scalaTree)) } } - override def protoValueType: TypeRepr = protoValueSetterType + override def protoValueType: TypeRepr = protoValueSetterType.getOrElse(TypeRepr.of[Unit]) - def optTree(optFieldType: TypeRepr): Tree = { + def optTree(optFieldType: TypeRepr): Term = { val tree = if (isIterable(protoValueType)) { seqTree(optFieldType) } else if (isMap(protoValueType)) { @@ -91,33 +105,32 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ } else { defaultTree(optFieldType) } - ??? + '{ if(${scalaTree.asExprOf[Option[_]]}.isDefined) ${tree.asExpr} }.asTerm // If(q"$scalaTree.isDefined", tree, EmptyTree) } - def seqTree(iterableType: TypeRepr): Tree = { -// val listType = builderType.member(addAllMethodName).asMethod.paramLists.head.head.typeSignature -// val valueTree = toProto(iterableType, listType) -// q"${builderIdent}.$addAllMethodName($valueTree)" - ??? + def seqTree(iterableType: TypeRepr): Term = { + val addAllMethod = builderClassSymbol.memberMethod(addAllMethodName).last + val listType = addAllMethod.tree.asInstanceOf[DefDef].paramss.head.params.head.asInstanceOf[ValDef].tpt.tpe + val valueTree = toProto(iterableType, listType) + Apply(Select(protoBuilderIdent, addAllMethod), List(valueTree)) } - def mapTree(mapType: TypeRepr): Tree = { -// val putAllMapType = builderType.member(putAllMethodName).asMethod.paramLists.head.head.typeSignature -// val valueTree = toProto(mapType, putAllMapType) -// q"${builderIdent}.$putAllMethodName($valueTree)" - ??? + def mapTree(mapType: TypeRepr): Term = { + val putAllMethod = builderClassSymbol.memberMethod(putAllMethodName).head + val putAllMapType = putAllMethod.tree.asInstanceOf[DefDef].paramss.head.params.head.asInstanceOf[ValDef].tpt.tpe + val valueTree = toProto(mapType, putAllMapType) + Apply(Select(protoBuilderIdent, putAllMethod), List(valueTree)) } - def defaultTree(fieldType: TypeRepr): Tree = { -// val valueTree = toProto(fieldType, protoValueType) -// q"${builderIdent}.$setField(${valueTree})" - ??? + def defaultTree(fieldType: TypeRepr): Term = { + val valueTree = toProto(fieldType, protoValueType) + val setFieldMethod = builderClassSymbol.memberMethod(setField).last + Apply(Select(protoBuilderIdent, setFieldMethod), List(valueTree)) } - override def tree: Option[Tree] = { -// if (protoValueType == NoType) { - if (protoValueType == ???) { + override def tree: Option[Term] = { + if (protoValueType == TypeRepr.of[Unit]) { None } else { val _tree = if (isOption(scalaTreeType)) { @@ -131,9 +144,9 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ } if (scalaTreeType <:< TypeRepr.of[AnyRef]) { -// val notNullCondition = q"$scalaTree ne null" -// Some(If(notNullCondition, _tree, EmptyTree)) - ??? + Some('{ + if(${scalaTree.asExprOf[AnyRef]} ne null) ${_tree.asExpr} + }.asTerm) } else { Some(_tree) } @@ -186,21 +199,20 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ private trait ProtoFieldAnalyst extends Processor { def protoFieldName: String - val builderType = getBuilderType() + def addAllMethodName: String = s"addAll$protoFieldName" + def putAllMethodName: String = s"putAll$protoFieldName" + def addField: String = s"add$protoFieldName" + def putField: String = s"put$protoFieldName" + def setField: String = s"set$protoFieldName" + def getField: String = s"get$protoFieldName" + def getMapField: String = s"get${protoFieldName}Map" + def getListField: String = s"get${protoFieldName}List" + def builderSetter: String = if (isIterable(scalaTreeType)) addAllMethodName else setField - def addAllMethodName: ByName = ???//ByName(s"addAll$protoFieldName") - def putAllMethodName: ByName = ???//ByName(s"putAll$protoFieldName") + def protoValueTree: Tree = { - def addField: ByName = ???//TermName(s"add$protoFieldName") - def putField: ByName = ???//TermName(s"put$protoFieldName") - def setField: ByName = ???//TermName(s"set$protoFieldName") - def getField: ByName = ???//TermName(s"get$protoFieldName") - def getMapField: ByName = ???//TermName(s"get${protoFieldName}Map") - def getListField: ByName = ???//TermName(s"get${protoFieldName}List") - def builderSetter: ByName = if (isIterable(scalaTreeType)) addAllMethodName else setField - val protoValueTree: Tree = { // if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 // q"$protoIdent.$getListField" // } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map @@ -210,22 +222,23 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ // } else { // q"" // } + ??? } - lazy val protoValueSetterType: TypeRepr = { -// val pbBuilderType = typeOf[com.google.protobuf.Message.Builder] -// val setterOpt = if (builderType.member(addField) != NoSymbol) { -// Some(builderType.member(addAllMethodName)) -// } else if (builderType.member(putField) != NoSymbol) { -// Some(builderType.member(putAllMethodName)) -// } else if (builderType.member(setField) != NoSymbol) { -// Some(builderType.member(setField)) -// } else { -// None -// } -// setterOpt.fold(NoType)(_.alternatives.map(_.asMethod.paramLists.head.head.typeSignature).find(t ⇒ !(t <:< pbBuilderType)).get) - ??? + lazy val protoValueSetterType: Option[TypeRepr] = { + val setters = if (builderClassSymbol.memberMethod(addField).nonEmpty) { + builderClassSymbol.memberMethod(addAllMethodName) + } else if (builderClassSymbol.memberMethod(putField).nonEmpty) { + builderClassSymbol.memberMethod(putAllMethodName) + } else if (builderClassSymbol.memberMethod(setField).nonEmpty) { + builderClassSymbol.memberMethod(setField) + } else { + Nil + } + val pbBuilderType = TypeRepr.of[com.google.protobuf.Message.Builder] + setters.map(_.tree.asInstanceOf[DefDef].paramss.head.params.head.asInstanceOf[ValDef].tpt.tpe) + .filterNot(_ <:< pbBuilderType).headOption } lazy val protoValueGetterType: TypeRepr = { @@ -246,10 +259,11 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ // Convert scala clase class field value to protobuf value - private case class ToProtoFieldProcessor(scalaEntity:Ident,accessor: Symbol) + private case class ToProtoFieldProcessor(scalaEntity:Ident,protoBuilderIdent:Ident,accessor: Symbol) extends ToProtoProcessor( - Apply(scalaEntity,List(accessor.asInstanceOf[Term])), - ??? /*accessor.returnType*/, + protoBuilderIdent:Ident, + Select(scalaEntity,accessor), + scalaClassType.memberType(accessor), accessor.name.toString.capitalize) // Convert protobuf value to case class filed value @@ -276,7 +290,7 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ private[this] def resolveFieldType(originType: TypeRepr): TypeRepr = { // originType.asSeenFrom(entityType, entityType.typeSymbol.asClass) - ??? + originType } private[this] def resolveType[T](using Type[T]): TypeRepr = { @@ -291,11 +305,12 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ quotas.reflect.SymbolMethods.caseFields(classSymbol) } - private[this] def defaultProtoableFieldConvertTrees(scalaEntity:Ident): Map[String, Tree] = { + private[this] def defaultProtoableFieldConvertTrees(scalaEntity:Ident, protoBuilderIdent:Ident): List[Tuple2[String, Term]] = { getCaseAccessors().flatMap { a ⇒ - val p = ToProtoFieldProcessor(scalaEntity,a) + val p = ToProtoFieldProcessor(scalaEntity, protoBuilderIdent,a) + p.tree.map(Printer.TreeAnsiCode.show).foreach(println(_)) p.tree.map(p.protoFieldName -> _) - }.toMap + } } private[this] def protoableBody(protoableFieldConvertTrees: Iterable[Tree]): Tree = { @@ -340,26 +355,23 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ } private def protosImpl: Expr[Protoable[T,M]] = { - protosImpl(ident => defaultProtoableFieldConvertTrees(ident).values, Nil) + protosImpl((scalaEntityIdent, protoBuilderIdent) => defaultProtoableFieldConvertTrees(scalaEntityIdent, protoBuilderIdent).map(_._2), Nil) } - private[this] inline def protosImpl(protoableFieldConvertTrees:Ident => Iterable[Tree], perTrees: Iterable[Tree]): Expr[Protoable[T,M]] = { -// q""" -// ..$perTrees -// new $packageName.Protoable[$caseClassType,$protoType] { ${protoableBody(caseClassType, protoType, protoableFieldConvertTrees)} } -// """ - '{ + private[this] def protosImpl(protoableFieldConvertTrees:(Ident, Ident) => List[Term], perTrees: Iterable[Tree]): Expr[Protoable[T,M]] = { + val expr = '{ new Protoable[T,M] { - override def toProto(scalaEntity: T): M = { - val proto:M = ${newProtoTree} - val builder = proto.toBuilder -// ..$protoableFieldConvertTrees -// builder.build() - ${quotas.reflect.TreeMethods.asExprOf(Apply('{builder}.asInstanceOf[Term],List.empty[Term]).asInstanceOf[Nothing])} + override def toProto(scalaEntity: T): M = ${ + val scalaEntityIdent = '{scalaEntity}.asTerm.asInstanceOf[Ident] + val x= builderBuildeWithTerms(protoableFieldConvertTrees(scalaEntityIdent,_)) + println(x) + x.asExprOf[M] } } } + println(expr.show) + expr } def convertsImpl[T, M](using Type[T], Type[M]): Expr[ProtoScalable[T,M]] = { @@ -487,7 +499,7 @@ object ProtoScalableMacro { ${protosImpl[T,M]} } - def protosImpl[T,M<:GeneratedMessageV3](using t:Type[T], m:Type[M],quotes: Quotes ):Expr[Protoable[T,M]] = { + def protosImpl[T,M<:GeneratedMessageV3](using t:Type[T], m:Type[M],quotes: Quotes):Expr[Protoable[T,M]] = { val protoScalableMacro = new ProtoScalableMacro(using t, m) protoScalableMacro.protosImpl } diff --git a/pbconverts/src/main/scala/pbconverts/Protoable.scala b/pbconverts/src/main/scala/pbconverts/Protoable.scala index cb9ba0a..34d5967 100644 --- a/pbconverts/src/main/scala/pbconverts/Protoable.scala +++ b/pbconverts/src/main/scala/pbconverts/Protoable.scala @@ -1,9 +1,8 @@ package pbconverts import annotation.targetName - import java.time.ZonedDateTime -import com.google.protobuf.{BoolValue, DoubleValue, FloatValue, GeneratedMessageV3, Int32Value, Int64Value, Message, StringValue, Timestamp} +import com.google.protobuf.{BoolValue, DoubleValue, FloatValue, GeneratedMessageV3, Int32Value, Int64Value, Message, MessageOrBuilder, StringValue, Timestamp} import scala.collection.JavaConverters._ @@ -13,7 +12,7 @@ trait Protoable[-T, +M] { object Protoable { - inline def apply[T <: Product, M <: GeneratedMessageV3]: Protoable[T, M] = { + inline def apply[T <: Product, M <: GeneratedMessageV3 with MessageOrBuilder]: Protoable[T, M] = { ProtoScalableMacro.protoable[T, M] } diff --git a/pbconverts/src/main/scala/pbconverts/Test.scala b/pbconverts/src/main/scala/pbconverts/Test.scala new file mode 100644 index 0000000..0cbd5ae --- /dev/null +++ b/pbconverts/src/main/scala/pbconverts/Test.scala @@ -0,0 +1,8 @@ +package pbconverts + +object Test { + + given Int = 1 + implicitly[Int].toString +} + diff --git a/pbconverts/src/main/scala/pbconverts/pbconverts/Test$.class b/pbconverts/src/main/scala/pbconverts/pbconverts/Test$.class new file mode 100644 index 0000000000000000000000000000000000000000..c70f63aac58b20f4d0d4f8f68dc4434b0d0645b3 GIT binary patch literal 694 zcmZ8e*-qO)6g}f4m<(oVfELQumXrn_YN7HL)CZt_3X2F(@i=itFleyRcnmFH#UeFQ zk@^AssH%5tL{Vhfck!8X?mhG8@2}qg*3e)WyXZtod?}4h!vmSxx(`O(GjSV>!ZXlk#|)Rwxv-*t83BG(np1XyQ3e|NNB;}Z|`m$w!YLEYOQ|uCd0tGik1D$ zP--k61>hLsC?jAf+f$V?46a8yM{sxu0t}*BrR)X6cpn>$M&ph%O!n)zKTUUZvWf}3 zqyb}jwUH^^m4^0cEVuqI*tSN+Cxo8DG$-_HhTzI5EBEDv7Ln}77lzOxOZmQ`$zrR{ zWw@PmGcBL2u_}r8O!EDQk9kM&OmS0-G;J2kzu{QGTUvfI>5|lFOT}_0JMTzy;M{c{ zCS>c8AjheGZ1Q%JnMi(B4pC`4-?2(2l|lZ}JMCPfD=txw45rQ^Ri7v_ij|cfhHokH zP^Yi+*+I+nyr(QEKp4p>su+DDSjmwaMW&Wt_VJS!X_&^c=09PoCf&c&j literal 0 HcmV?d00001 diff --git a/pbconverts/src/main/scala/pbconverts/pbconverts/Test.class b/pbconverts/src/main/scala/pbconverts/pbconverts/Test.class new file mode 100644 index 0000000000000000000000000000000000000000..811fc5e044f5adef918d51e031776371189143ce GIT binary patch literal 145 zcmX^0Z`VEs1_l!bPDTd)f~4g9yt34yl4AXk)Z!9$21Z5(fvm)`ME#t^ymWp4q^#6r zpeQpV0~bhMuQ)j|ClSaA&Mz%WPIb%7No8bU4RH((i3HNYAV~&81||j;pamen%)kaD hnHX3Z*nzYFL&EgGq48D>4BBe@HD?@TVBi2L0s!~JAol50M;2-Fa5hf&r5>>FFnz%$_KtfbWyHzq*_dr)U=gK~(lmYCs<6P{P zgfwjo4QWb$LP2C=VL)9N5gT(CCZviXBN0xSU%k)s%vvCNwrklZ&H9RruJMUX+BB1TL)W0_A@W!~O|YQaFZo$@<*KiEnjqIl(wLySdi zL0DoI8HYsMdH%W!wQ+bFl<|5Hl}yLd@m*qIh!CYFy8x%gT@ZvaY*A#${Oz91_xmaO zpbOFXp8MZjpD}GRF0nxr%yJo1X1jmfbJg=&-1J$ZdO{4snl@Ea>J$D?zk4d8fmqj^ zSdEmu$_s1-O3cF`>on9R@4U=9E#Tm3x5<5FeJn^yV z^ws^86CP^HnR0gT==e+2avNKo+w6I+FP)3v=&=3#Ac6R})@zO6{qO#>(Qqhzk7McA UaM+iA3_is>t&Ne`9=h+`e-W|Y@&Et; literal 0 HcmV?d00001 diff --git a/pbconverts/src/main/scala/pbconverts/pbconverts/TestObj$.class b/pbconverts/src/main/scala/pbconverts/pbconverts/TestObj$.class new file mode 100644 index 0000000000000000000000000000000000000000..889fa39998d2d6a9481422816e2bbd57c7c2fb42 GIT binary patch literal 685 zcmZ`$TTk0C6#ksFqz&QL0t3cn1B56NL`b}Wco=L?0VWEScyv<>j7)+Y2R42ch=)o; z+7H-|nm7&>s;VuLee6%?yZGeK-(SB0>|lkVe%p@IG7XzTORnStZ!6)U%-~!0Ru*%`8N8#D!}I9tD#KLt4})EXp*@*M zv(MnJH(CLF4Erb{U?`a@nK4xMVpVkba1aEjpjxHV1VeDIr4gs%R`FO+qV+~J7?t$b ziX@@V6C-a#c$9W>CEi0DnI_+L`s1gEDJ#*ZaG-dW?Y?FD;A0vy^tMFYf61ll2t8=n zG+HK?WJn3;Dg8m(p-^LyOvG`1(-!*7PKcovr8Jrrr>W7s2l~x4*Rl8}ZAZCjXNPTi zWeGGOTC?`q^ruRM(S!(Dq+3Xp{7~NLV&sVq4wh)Q1i-^5+JmB<=@Y;+T7<@C=|`i!H(+Hha}gpE15$+p^Ly|2|G%aE*O$AN)5sN&hGwoMQ^`~! zo4zVtywtmwIFqC+rJE`EEy+W0=W~k&gsaO1omMd82KbBE;CGf+rfmV1YU;WV$50)=5&)4@GYWY2oa?^|Hs8S&mka`V@8oCi~hbW4tg=#iP6Is z5Kf*>{%>5%=mwc|Fd#_l^Ugnik<#b_i^dW3nja}Pn_H4_Megy7d@bOC<>hJyD);YZT-hXsH9!sC2 aNIDyj`_k9ZyJ+YhZT_*OlUmgpT7LnvRo&D8 literal 0 HcmV?d00001 diff --git a/pbconverts/src/test/protobuf/conversion_test.proto b/pbconverts/src/test/protobuf/conversion_test.proto.test similarity index 100% rename from pbconverts/src/test/protobuf/conversion_test.proto rename to pbconverts/src/test/protobuf/conversion_test.proto.test diff --git a/pbconverts/src/test/scala/pbconverts/ConversionTest.java b/pbconverts/src/test/scala/pbconverts/ConversionTest.java index 5661dc8..3193468 100644 --- a/pbconverts/src/test/scala/pbconverts/ConversionTest.java +++ b/pbconverts/src/test/scala/pbconverts/ConversionTest.java @@ -1,5 +1,5 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! -// source: conversion_test.proto +// source: conversion_test.proto.test package pbconverts; diff --git a/pbconverts/src/test/scala/pbconverts/MapSpec.scala b/pbconverts/src/test/scala/pbconverts/MapSpec.scala index 4cb6e1d..a8921b2 100644 --- a/pbconverts/src/test/scala/pbconverts/MapSpec.scala +++ b/pbconverts/src/test/scala/pbconverts/MapSpec.scala @@ -2,13 +2,14 @@ package pbconverts import com.google.protobuf.ByteString import org.scalatest.funsuite.AnyFunSuite -import pbconverts.ConversionTest.{PBTestBytes, PBTestMessage} +import ConversionTest.{PBTestBytes, PBTestMessage} class MapSpec extends AnyFunSuite { test("test map") { val testMessage = TestMessage.default val pbTestMessage: PBTestMessage = Protoable[TestMessage, PBTestMessage].toProto(testMessage) + println(pbTestMessage) assert(pbTestMessage.getIntValue == testMessage.intValue) assert(pbTestMessage.getLongIntKVOrThrow(1L) == 1) assert(pbTestMessage.getLongStringKVOrThrow(1L) == "string1") @@ -16,20 +17,20 @@ class MapSpec extends AnyFunSuite { assert(pbTestMessage.getStringStringKVOrThrow("string1") == "string1") } - case class TestBytes(m: Map[String, Int]) - test("test conversion between bytes in protobuf and Map in case class") { - val pbTest1 = ProtoableBuilder[TestBytes, PBTestBytes] - .setField(_.getTestBytes, x => ByteString.copyFromUtf8(x.m.keys.mkString(","))) - .build - .toProto(TestBytes(Map("test" -> 1, "bytes" -> 1))) - - assert(pbTest1.getTestBytes.toStringUtf8 == "test,bytes") - - val test = ScalableBuilder[TestBytes, PBTestBytes] - .setField(_.m, _.getTestBytes.toStringUtf8.split(",").map(_ -> 1).toMap) - .build - .toScala(PBTestBytes.newBuilder().setTestBytes(ByteString.copyFromUtf8("test,bytes")).build()) - - assert(test.m == Map("test" -> 1, "bytes" -> 1)) - } +// case class TestBytes(m: Map[String, Int]) +// test("test conversion between bytes in protobuf and Map in case class") { +// val pbTest1 = ProtoableBuilder[TestBytes, PBTestBytes] +// .setField(_.getTestBytes, x => ByteString.copyFromUtf8(x.m.keys.mkString(","))) +// .build +// .toProto(TestBytes(Map("test" -> 1, "bytes" -> 1))) +// +// assert(pbTest1.getTestBytes.toStringUtf8 == "test,bytes") +// +// val test = ScalableBuilder[TestBytes, PBTestBytes] +// .setField(_.m, _.getTestBytes.toStringUtf8.split(",").map(_ -> 1).toMap) +// .build +// .toScala(PBTestBytes.newBuilder().setTestBytes(ByteString.copyFromUtf8("test,bytes")).build()) +// +// assert(test.m == Map("test" -> 1, "bytes" -> 1)) +// } } From f5a1196debbd52a52febf9fd56c846e130fc47d9 Mon Sep 17 00:00:00 2001 From: changvvb Date: Wed, 12 May 2021 21:13:14 +0800 Subject: [PATCH 04/17] wip --- .../scala/pbconverts/ProtoScalableMacro.scala | 232 +++++++++++------- .../src/main/scala/pbconverts/Protoable.scala | 3 +- .../src/main/scala/pbconverts/Scalable.scala | 2 +- .../src/test/resources/MessageWithType.java | 1 - pbconverts/src/test/resources/Person.java | 1 - .../src/test/scala/pbconverts/MapSpec.scala | 1 - .../scala/pbconverts/MessageWithType.scala | 2 + .../src/test/scala/pbconverts/Person.scala | 2 + .../pbconverts}/ScalableSpec.scala | 58 ++--- 9 files changed, 176 insertions(+), 126 deletions(-) delete mode 100644 pbconverts/src/test/resources/MessageWithType.java delete mode 100644 pbconverts/src/test/resources/Person.java create mode 100644 pbconverts/src/test/scala/pbconverts/MessageWithType.scala create mode 100644 pbconverts/src/test/scala/pbconverts/Person.scala rename pbconverts/src/test/{resources => scala/pbconverts}/ScalableSpec.scala (55%) diff --git a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala index e99ec47..bcf50c3 100644 --- a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala +++ b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala @@ -7,12 +7,13 @@ import quoted.{Expr, Quotes, Type} import scala.collection.mutable // scalastyle:off number.of.methods -class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Type[M])(using quotas:Quotes) { +class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Quotes) { import quotas.reflect._ - private[this] val scalaClassType = quotas.reflect.TypeRepr.of[T](using typeT) - private[this] val protoClassType = quotas.reflect.TypeRepr.of[M](using typeM) + private[this] val scalaClassType = quotas.reflect.TypeRepr.of[T](using typeT).dealias + private[this] val protoClassType = quotas.reflect.TypeRepr.of[M](using typeM).dealias + private[this] val scalaClassSymbol = scalaClassType.typeSymbol private[this] val protoClassSymbol: quotas.reflect.Symbol = quotas.reflect.TypeReprMethods.classSymbol(protoClassType).get private[this] val protoClassSymbolClass = quotas.reflect.SymbolMethods.companionClass(protoClassSymbol) private[this] val protoClassSymbolModule = quotas.reflect.SymbolMethods.companionModule(protoClassSymbol) @@ -31,27 +32,25 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ } -// private val builderBuildExpr = Apply(ident,) -// private[this] def packageName = ???//q"_root_.pbconverts" -// private[this] def builderIdent = ???//Ident(TermRef("builder")) -// private[this] def entityIdent = ??? //Ident.apply(TermRef(,"entity")) //Ident(TermRef("entity")) -// private[this] def protoIdent = ??? //Ident(TermRef("proto")) private[this] def implicitlyProtoable(entityType: TypeRepr, protoType: TypeRepr):Term = { - val target = TypeRepr.of[Protoable].appliedTo(List(entityType,protoType)) - Implicits.search(target) match { - case s: ImplicitSearchSuccess => s.tree - case _ => - report.error(s"implicit ${Printer.TypeReprAnsiCode.show(target)} not found") - ??? + val target = TypeRepr.of[Protoable].appliedTo(List(entityType,protoType)) + Implicits.search(target) match { + case s: ImplicitSearchSuccess => s.tree + case _ => + report.error(s"implicit ${Printer.TypeReprAnsiCode.show(target)} not found") + ??? } } private[this] def implicitlyScalable(entityType: TypeRepr, protoType: TypeRepr):Term = { - Implicits.search(TypeApply('{Scalable}.asTerm,List(TypeIdent(entityType.typeSymbol),TypeIdent(protoType.typeSymbol))).tpe) match { - case s:ImplicitSearchSuccess => s.tree - case _ => ??? - } - } //q"implicitly[$packageName.Scalable[$entityType,$protoType]]" + val target = TypeRepr.of[Scalable].appliedTo(List(entityType, protoType)) + Implicits.search(target) match { + case s: ImplicitSearchSuccess => s.tree + case _ => + report.error(s"implicit ${Printer.TypeReprAnsiCode.show(target)} not found") + ??? + } //q"implicitly[$packageName.Scalable[$entityType,$protoType]]" + } private[this] def isOption(tpe: TypeRepr): Boolean = { tpe <:< TypeRepr.of[Option[_]] @@ -75,7 +74,7 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ def resolvedCaseClassFieldType: TypeRepr = resolveFieldType(scalaTreeType) - def tree: Option[Tree] + def tree: Option[Term] } // Convert expr (`scalaTree` in this class) to protobuf value @@ -86,6 +85,9 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ override val protoFieldName: String ) extends ProtoFieldAnalyst { + + override def protoIdent: ProtoScalableMacro.this.quotas.reflect.Ident = ??? + private[this] def toProto(t1: TypeRepr, t2: TypeRepr): Term = { if (t1 <:< t2) { scalaTree @@ -155,36 +157,35 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ } // Convert expr (`protoValueTree` in this class) to case class filed value - private case class ToScalaProcessor(caseClassSelector: Symbol, protoValueTree: Tree, protoValueType: TypeRepr) + private case class ToScalaProcessor(caseClassSelector: Symbol, protoValueTree: Term, protoValueType: TypeRepr) extends AbstractToScalaProcessor private trait AbstractToScalaProcessor extends Processor { def caseClassSelector: Symbol - def protoValueTree: Tree + def protoValueTree: Term - override def scalaTreeType: TypeRepr = ???//caseClassSelector.returnType + override def scalaTreeType: TypeRepr = caseClassSelector.tree.asInstanceOf[ValDef].tpt.tpe - protected def toScala(t1: TypeRepr, t2: TypeRepr, value: Tree) = { + protected def toScala(t1: TypeRepr, t2: TypeRepr, value: Term):Term = { if (t2 <:< t1) { value } else { -// q"${implicitlyScalable(t1, t2)}.toScala($value)" - ??? + val toScalaMethod = TypeRepr.of[Scalable[_,_]].typeSymbol.memberMethod("toScala").head + Apply(Select(implicitlyScalable(t1,t2),toScalaMethod),List(value)) } } - def optTree(optType: TypeRepr): Tree = defaultTree(optType) + def optTree(optType: TypeRepr): Term = defaultTree(optType) - def defaultTree(fieldType: TypeRepr): Tree = { + def defaultTree(fieldType: TypeRepr): Term = { // q"$caseClassSelector = ${toScala(fieldType, protoValueType, protoValueTree)}" - ??? + Assign(caseClassSelector.tree.asInstanceOf[Term],toScala(fieldType,protoValueType,protoValueTree)) } - override def tree: Option[Tree] = - if (protoValueType == ???) { -// if (protoValueType == NoType) { + override def tree: Option[Term] = + if (protoValueType == TypeRepr.of[Unit]) { None } else { if (isOption(scalaTreeType)) { @@ -197,6 +198,9 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ // Contain some methods and vals to analyze Protobuf fields private trait ProtoFieldAnalyst extends Processor { + + def protoIdent:Ident + def protoFieldName: String def addAllMethodName: String = s"addAll$protoFieldName" @@ -210,20 +214,16 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ def getListField: String = s"get${protoFieldName}List" def builderSetter: String = if (isIterable(scalaTreeType)) addAllMethodName else setField - def protoValueTree: Tree = { - - -// if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 -// q"$protoIdent.$getListField" -// } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map -// q"$protoIdent.$getMapField" -// } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 -// q"$protoIdent.$getField" -// } else { -// q"" -// } - - ??? + def protoValueTree: Term = { + if (builderClassSymbol.memberMethod(addField).nonEmpty) { + Apply(Select(protoIdent,builderClassSymbol.memberMethod(getListField).head),Nil) + } else if (builderClassSymbol.memberMethod(putField).nonEmpty) { + Apply(Select(protoIdent,builderClassSymbol.memberMethod(getMapField).head),Nil) + } else if (builderClassSymbol.memberMethod(setField).nonEmpty) { + Apply(Select(protoIdent,builderClassSymbol.memberMethod(getField).head),Nil) + } else { + '{}.asTerm + } } lazy val protoValueSetterType: Option[TypeRepr] = { @@ -241,33 +241,34 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ .filterNot(_ <:< pbBuilderType).headOption } - lazy val protoValueGetterType: TypeRepr = { -// if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 -// protoType.member(getListField).typeSignature.resultType -// } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map -// protoType.member(getMapField).typeSignature.resultType -// } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 -// protoType.member(getField).typeSignature.resultType -// } else { -// NoType -// } - ??? + lazy val protoValueGetterType: Option[TypeRepr] = { + val getters = if (builderClassSymbol.memberMethod(addField).nonEmpty) { + builderClassSymbol.memberMethod(getListField) + } else if (builderClassSymbol.memberMethod(putField).nonEmpty) { + builderClassSymbol.memberMethod(getMapField) + } else if (builderClassSymbol.memberMethod(setField).nonEmpty) { + builderClassSymbol.memberMethod(getField) + } else { + Nil + } + getters.headOption.map(_.tree.asInstanceOf[DefDef].returnTpt.tpe) } } - // Convert scala clase class field value to protobuf value private case class ToProtoFieldProcessor(scalaEntity:Ident,protoBuilderIdent:Ident,accessor: Symbol) extends ToProtoProcessor( protoBuilderIdent:Ident, Select(scalaEntity,accessor), scalaClassType.memberType(accessor), - accessor.name.toString.capitalize) + accessor.name.toString.capitalize) { + override def protoIdent: ProtoScalableMacro.this.quotas.reflect.Ident = ??? + } // Convert protobuf value to case class filed value - private case class ToScalaFieldProcessor(accessor: Symbol) + private case class ToScalaFieldProcessor(protoIdent:Ident, accessor: Symbol) extends AbstractToScalaProcessor with ProtoFieldAnalyst { @@ -275,22 +276,60 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ override def protoFieldName: String = accessor.name.toString.capitalize - override def protoValueType: TypeRepr = protoValueGetterType - - override def optTree(optType: TypeRepr): Tree = { - val hasProtoField = ByName( ??? /*s"has$protoFieldName"*/) -// if (protoType.member(hasProtoField) == NoSymbol) { -// defaultTree(optType) -// } else { -// q"$caseClassSelector = if (${protoIdent}.$hasProtoField) ${toScala(optType, protoValueType, protoValueTree)} else None" -// } - ??? + override def protoValueType: TypeRepr = protoValueGetterType.getOrElse(TypeRepr.of[Unit]) + + override def optTree(optType: TypeRepr): Term = { + val hasProtoField = s"has$protoFieldName" + val hasProtoFieldMethod = protoClassSymbol.memberMethod(hasProtoField).headOption + hasProtoFieldMethod match { + case Some(method) => + val optExpr = '{ + if(${Apply(Select(protoIdent,method),Nil).asExprOf[Boolean]}) { + Some(${toScala(optType, protoValueType, protoValueTree).asExpr}) + } else { + None + } + } + Assign(accessor.tree.asInstanceOf[Term],optExpr.asTerm) + case None => defaultTree(optType) + } } } private[this] def resolveFieldType(originType: TypeRepr): TypeRepr = { + val typeTree = scalaClassType.typeSymbol.tree.asInstanceOf[TypeDef] +// println(quotas.reflect.TypeReprMethods.widen(originType)) +// println(typeTree.rhs) + + + +// val types = (entityType.typeSymbol.asType.typeParams zip entityType.typeArgs).toMap +// def resolve(tpe: Type): Type = { +// if (tpe.typeArgs.isEmpty) { +// types.getOrElse(tpe.typeSymbol, tpe) +// } else { +// appliedType(tpe.typeConstructor, tpe.typeArgs.map(resolve)) +// } +// } +// originType match { +// case t: Type if isOption(t) ⇒ +// appliedType(typeOf[Option[_]].typeConstructor, resolve(t.typeArgs.head)) +// case t: Type if isIterable(t) ⇒ +// appliedType(t.typeConstructor, resolve(t.typeArgs.head)) +// case t: Type if isMap(t) ⇒ +// appliedType(t.typeConstructor, resolve(t.typeArgs.head), resolve(t.typeArgs.last)) +// case t: Type ⇒ +// resolve(t) +// } + + println(Printer.TreeAnsiCode.show(typeTree)) + // originType.asSeenFrom(entityType, entityType.typeSymbol.asClass) - originType +// TypeReprMethods.asType(originType) +// originType.select(scalaClassSymbol) +// originType + + originType } private[this] def resolveType[T](using Type[T]): TypeRepr = { @@ -308,7 +347,6 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ private[this] def defaultProtoableFieldConvertTrees(scalaEntity:Ident, protoBuilderIdent:Ident): List[Tuple2[String, Term]] = { getCaseAccessors().flatMap { a ⇒ val p = ToProtoFieldProcessor(scalaEntity, protoBuilderIdent,a) - p.tree.map(Printer.TreeAnsiCode.show).foreach(println(_)) p.tree.map(p.protoFieldName -> _) } } @@ -324,8 +362,8 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ ??? } - private def defalutScalableFieldConvertTrees(): Map[String, Tree] = { - getCaseAccessors().flatMap(accessor ⇒ ToScalaFieldProcessor(accessor).tree.map(accessor.name.toString -> _)).toMap + private def defalutScalableFieldConvertTrees(protoIdent:Ident): Map[String, Term] = { + getCaseAccessors().flatMap(accessor ⇒ ToScalaFieldProcessor(protoIdent,accessor).tree.map(accessor.name.toString -> _)).toMap } private def scalableBody(scalableFieldConvertTrees: Iterable[Tree]): Tree = { @@ -339,19 +377,30 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ ??? } - def scalasImpl[T, M](using Type[T], Type[M]): Expr[Scalable[T,M]] = { - val scalableFieldConvertTrees = defalutScalableFieldConvertTrees().values - - quotas.reflect.TreeMethods - .asExpr(scalasImpl(scalableFieldConvertTrees, Nil)).asInstanceOf[Expr[Scalable[T,M]]] + def scalasImpl: Expr[Scalable[T,M]] = { + scalasImpl(defalutScalableFieldConvertTrees(_).values, Nil) } - private[this] def scalasImpl(scalableFieldConvertTrees: Iterable[Tree], perTrees: Iterable[Tree]): Tree = { + private[this] def scalasImpl(scalableFieldConvertTrees: Ident => Iterable[Term], perTrees: Iterable[Tree]): Expr[Scalable[T,M]] = { // q""" // ..$perTrees // new $packageName.Scalable[$caseClassType, $protoType] { ${scalableBody(caseClassType, protoType, scalableFieldConvertTrees)} } // """ - ??? + + val res = '{ + new Scalable[T,M] { + override def toScala(proto: M): T = ${ + val protoIdent = '{proto}.asTerm.asInstanceOf[Ident] + val x= scalableFieldConvertTrees(protoIdent) + x.foreach { t => +// println(Printer.TreeAnsiCode.show(t)) + } + New(TypeTree.of[T]).asExprOf[T] + } + } + } + quotas.show(res) + res } private def protosImpl: Expr[Protoable[T,M]] = { @@ -360,18 +409,14 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ private[this] def protosImpl(protoableFieldConvertTrees:(Ident, Ident) => List[Term], perTrees: Iterable[Tree]): Expr[Protoable[T,M]] = { - val expr = '{ + '{ new Protoable[T,M] { override def toProto(scalaEntity: T): M = ${ val scalaEntityIdent = '{scalaEntity}.asTerm.asInstanceOf[Ident] - val x= builderBuildeWithTerms(protoableFieldConvertTrees(scalaEntityIdent,_)) - println(x) - x.asExprOf[M] + builderBuildeWithTerms(protoableFieldConvertTrees(scalaEntityIdent,_)).asExprOf[M] } } } - println(expr.show) - expr } def convertsImpl[T, M](using Type[T], Type[M]): Expr[ProtoScalable[T,M]] = { @@ -495,12 +540,17 @@ class ProtoScalableMacro[T,M<:GeneratedMessageV3](using typeT:Type[T], typeM:Typ object ProtoScalableMacro { - inline def protoable[T,M<:GeneratedMessageV3]:Protoable[T,M] = { - ${protosImpl[T,M]} - } + inline def protoable[T,M]:Protoable[T,M] = ${protosImpl[T,M]} - def protosImpl[T,M<:GeneratedMessageV3](using t:Type[T], m:Type[M],quotes: Quotes):Expr[Protoable[T,M]] = { + def protosImpl[T,M](using t:Type[T], m:Type[M],quotes: Quotes):Expr[Protoable[T,M]] = { val protoScalableMacro = new ProtoScalableMacro(using t, m) protoScalableMacro.protosImpl } + + inline def scalable[T,M]:Scalable[T,M] = ${scalasImpl[T,M]} + + def scalasImpl[T,M](using t:Type[T], m:Type[M],quotes: Quotes):Expr[Scalable[T,M]] = { + val protoScalableMacro = new ProtoScalableMacro(using t, m) + protoScalableMacro.scalasImpl + } } \ No newline at end of file diff --git a/pbconverts/src/main/scala/pbconverts/Protoable.scala b/pbconverts/src/main/scala/pbconverts/Protoable.scala index 34d5967..d35e2cc 100644 --- a/pbconverts/src/main/scala/pbconverts/Protoable.scala +++ b/pbconverts/src/main/scala/pbconverts/Protoable.scala @@ -12,9 +12,8 @@ trait Protoable[-T, +M] { object Protoable { - inline def apply[T <: Product, M <: GeneratedMessageV3 with MessageOrBuilder]: Protoable[T, M] = { + inline def apply[T <: Product, M <: GeneratedMessageV3 with MessageOrBuilder]: Protoable[T, M] = ProtoScalableMacro.protoable[T, M] - } def apply[T, M](f: T ⇒ M): Protoable[T, M] = new Protoable[T, M] { diff --git a/pbconverts/src/main/scala/pbconverts/Scalable.scala b/pbconverts/src/main/scala/pbconverts/Scalable.scala index 02a0471..a65c8f8 100644 --- a/pbconverts/src/main/scala/pbconverts/Scalable.scala +++ b/pbconverts/src/main/scala/pbconverts/Scalable.scala @@ -13,7 +13,7 @@ trait Scalable[+T, -M] { object Scalable extends ScalableImplicits { - def apply[T <: Product, M]: Scalable[T, M] = ??? // macro ProtoScalableMacro.scalasImpl[T, M] + inline def apply[T <: Product, M]: Scalable[T, M] = ProtoScalableMacro.scalable[T, M] def apply[T, M](convert: M ⇒ T): Scalable[T, M] = new Scalable[T, M] { diff --git a/pbconverts/src/test/resources/MessageWithType.java b/pbconverts/src/test/resources/MessageWithType.java deleted file mode 100644 index 54c3882..0000000 --- a/pbconverts/src/test/resources/MessageWithType.java +++ /dev/null @@ -1 +0,0 @@ -package pbconverts;case class MessageWithType[T](value: T) diff --git a/pbconverts/src/test/resources/Person.java b/pbconverts/src/test/resources/Person.java deleted file mode 100644 index c5f770e..0000000 --- a/pbconverts/src/test/resources/Person.java +++ /dev/null @@ -1 +0,0 @@ -package pbconverts;case class Person(id: Long, name: String, phone: Option[String], hobbies: Seq[String]) diff --git a/pbconverts/src/test/scala/pbconverts/MapSpec.scala b/pbconverts/src/test/scala/pbconverts/MapSpec.scala index a8921b2..0d29c13 100644 --- a/pbconverts/src/test/scala/pbconverts/MapSpec.scala +++ b/pbconverts/src/test/scala/pbconverts/MapSpec.scala @@ -9,7 +9,6 @@ class MapSpec extends AnyFunSuite { val testMessage = TestMessage.default val pbTestMessage: PBTestMessage = Protoable[TestMessage, PBTestMessage].toProto(testMessage) - println(pbTestMessage) assert(pbTestMessage.getIntValue == testMessage.intValue) assert(pbTestMessage.getLongIntKVOrThrow(1L) == 1) assert(pbTestMessage.getLongStringKVOrThrow(1L) == "string1") diff --git a/pbconverts/src/test/scala/pbconverts/MessageWithType.scala b/pbconverts/src/test/scala/pbconverts/MessageWithType.scala new file mode 100644 index 0000000..757a0e1 --- /dev/null +++ b/pbconverts/src/test/scala/pbconverts/MessageWithType.scala @@ -0,0 +1,2 @@ +package pbconverts +case class MessageWithType[T](value: T) diff --git a/pbconverts/src/test/scala/pbconverts/Person.scala b/pbconverts/src/test/scala/pbconverts/Person.scala new file mode 100644 index 0000000..ad00e67 --- /dev/null +++ b/pbconverts/src/test/scala/pbconverts/Person.scala @@ -0,0 +1,2 @@ +package pbconverts +case class Person(id: Long, name: String, phone: Option[String], hobbies: Seq[String]) diff --git a/pbconverts/src/test/resources/ScalableSpec.scala b/pbconverts/src/test/scala/pbconverts/ScalableSpec.scala similarity index 55% rename from pbconverts/src/test/resources/ScalableSpec.scala rename to pbconverts/src/test/scala/pbconverts/ScalableSpec.scala index 6c7cee9..323a0f6 100644 --- a/pbconverts/src/test/resources/ScalableSpec.scala +++ b/pbconverts/src/test/scala/pbconverts/ScalableSpec.scala @@ -28,33 +28,33 @@ class ScalableSpec extends AnyFunSuite { assert(person1 == person2) } - test("type alias") { - val pbPerson = PBPerson.newBuilder().setId(1L).build() - - locally { - type PPP = Person - val p = Scalable[PPP, PBPerson].toScala(pbPerson) - assert(p.id == 1L) - } - - locally { - type PBP = PBPerson - val p = Scalable[Person, PBP].toScala(pbPerson) - assert(p.id == 1L) - } - - locally { - type PPP = Person - type PBP = PBPerson - val p = Scalable[PPP, PBP].toScala(pbPerson) - assert(p.id == 1L) - } - - locally { - type IM = IntMessage - type MTI = MessageWithType[Int] - val p = Scalable[MTI, IM].toScala(IntMessage.newBuilder().setValue(1).build()) - assert(p.value == 1L) - } - } +// test("type alias") { +// val pbPerson = PBPerson.newBuilder().setId(1L).build() +// +// locally { +// type PPP = Person +// val p = Scalable[PPP, PBPerson].toScala(pbPerson) +// assert(p.id == 1L) +// } +// +// locally { +// type PBP = PBPerson +// val p = Scalable[Person, PBP].toScala(pbPerson) +// assert(p.id == 1L) +// } +// +// locally { +// type PPP = Person +// type PBP = PBPerson +// val p = Scalable[PPP, PBP].toScala(pbPerson) +// assert(p.id == 1L) +// } +// +// locally { +// type IM = IntMessage +// type MTI = MessageWithType[Int] +// val p = Scalable[MTI, IM].toScala(IntMessage.newBuilder().setValue(1).build()) +// assert(p.value == 1L) +// } +// } } From 95472ef685c4103ba268bc9675fc5b0a3ac2df45 Mon Sep 17 00:00:00 2001 From: changvvb Date: Tue, 22 Jun 2021 01:10:25 +0800 Subject: [PATCH 05/17] wip --- build.sbt | 104 +- .../scala/pbconverts/ProtoScalableMacro.scala | 3 +- .../src/test/protobuf/conversion_test.proto | 50 + .../test/protobuf/conversion_test.proto.test | 50 - .../test/scala/pbconverts/ConversionTest.java | 7492 ----------------- .../test/scala/pbconverts/ScalableSpec.scala | 106 +- project/build.properties | 2 +- 7 files changed, 157 insertions(+), 7650 deletions(-) create mode 100644 pbconverts/src/test/protobuf/conversion_test.proto delete mode 100644 pbconverts/src/test/protobuf/conversion_test.proto.test delete mode 100644 pbconverts/src/test/scala/pbconverts/ConversionTest.java diff --git a/build.sbt b/build.sbt index bbb0d41..c020aee 100644 --- a/build.sbt +++ b/build.sbt @@ -2,7 +2,7 @@ import sbt._ //lazy val scala213 = "2.13.4" //lazy val scala212 = "2.12.12" -lazy val scala3 = "3.0.0-RC2" +lazy val scala3 = "3.0.2-RC1-bin-SNAPSHOT" //lazy val supportedScalaVersions = List(scala212, scala213) @@ -14,66 +14,66 @@ val commonSettings = Seq( releasePublishArtifactsAction := PgpKeys.publishSigned.value ) -lazy val `scala-protobuf-java-macro` = project.in(file("pbconverts-macro")) -// .settings(libraryDependencies ++= Seq("org.scala-lang" % "scala-reflect" % scalaVersion.value)) - .settings(commonSettings) - .enablePlugins(ProtobufPlugin) +// lazy val `scala-protobuf-java-macro` = project.in(file("pbconverts-macro")) +// // .settings(libraryDependencies ++= Seq("org.scala-lang" % "scala-reflect" % scalaVersion.value)) +// .settings(commonSettings) +// .enablePlugins(ProtobufPlugin) lazy val `scala-protobuf-java` = project.in(file("pbconverts")) - .settings(libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.7" % "test") + .settings(libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.9" % "test") .settings(commonSettings) - .dependsOn(`scala-protobuf-java-macro`) + // .dependsOn(`scala-protobuf-java-macro`) .enablePlugins(ProtobufTestPlugin) lazy val root = project.in(file(".")).withId("root") - .aggregate(`scala-protobuf-java`, `scala-protobuf-java-macro`) + .aggregate(`scala-protobuf-java`) .settings(publishArtifact := false) //scalafmtOnCompile in ThisBuild := true // publish -releasePublishArtifactsAction in ThisBuild := releaseStepCommandAndRemaining("+publishSigned") - -publishTo in ThisBuild := { - val nexus = "https://oss.sonatype.org/" - if (version.value.trim.endsWith("SNAPSHOT")) - Some("snapshots" at nexus + "content/repositories/snapshots") - else - Some("releases" at nexus + "service/local/staging/deploy/maven2") -} - -publishMavenStyle in ThisBuild := true - -credentials in ThisBuild += Credentials(Path.userHome / ".ivy2" / ".credentials_sonatype") - -publishArtifact in Test := false - -pomIncludeRepository in ThisBuild := { _ => false } - -homepage in ThisBuild := Some(url("https://github.com/changvvb/scala-protobuf-java")) - -pomExtra in ThisBuild := { - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - scm:git:git@github.com:changvvb/scala-protobuf-java.git - scm:git:git@github.com:changvvb/scala-protobuf-java.git - https://github.com/changvvb/scala-protobuf-java - - - - changvvb - Weiwei Chang - changvvb@gmail.com - - -} - -publishConfiguration in ThisBuild := publishConfiguration.value.withOverwrite(true) -publishLocalConfiguration in ThisBuild := publishLocalConfiguration.value.withOverwrite(true) +// releasePublishArtifactsAction in ThisBuild := releaseStepCommandAndRemaining("+publishSigned") + +// publishTo in ThisBuild := { +// val nexus = "https://oss.sonatype.org/" +// if (version.value.trim.endsWith("SNAPSHOT")) +// Some("snapshots" at nexus + "content/repositories/snapshots") +// else +// Some("releases" at nexus + "service/local/staging/deploy/maven2") +// } + +// publishMavenStyle in ThisBuild := true + +// credentials in ThisBuild += Credentials(Path.userHome / ".ivy2" / ".credentials_sonatype") + +// publishArtifact in Test := false + +// pomIncludeRepository in ThisBuild := { _ => false } + +// homepage in ThisBuild := Some(url("https://github.com/changvvb/scala-protobuf-java")) + +// pomExtra in ThisBuild := { +// +// +// The Apache Software License, Version 2.0 +// http://www.apache.org/licenses/LICENSE-2.0.txt +// repo +// +// +// +// scm:git:git@github.com:changvvb/scala-protobuf-java.git +// scm:git:git@github.com:changvvb/scala-protobuf-java.git +// https://github.com/changvvb/scala-protobuf-java +// +// +// +// changvvb +// Weiwei Chang +// changvvb@gmail.com +// +// +// } + +// publishConfiguration in ThisBuild := publishConfiguration.value.withOverwrite(true) +// publishLocalConfiguration in ThisBuild := publishLocalConfiguration.value.withOverwrite(true) diff --git a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala index bcf50c3..449bf3d 100644 --- a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala +++ b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala @@ -27,9 +27,8 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q private val protoCompanionIdent = Ident.apply(TermRef.apply(outer, name)) private val newBuilderApply = Apply(Select.apply(protoCompanionIdent, newBuilderMethod),List.empty) private def builderBuildeWithTerms(termsBuilder:Ident => List[Term]) = ValDef.let(Symbol.spliceOwner,"builder",newBuilderApply) { ident => - val terms = termsBuilder.apply(ident) + val terms = termsBuilder(ident.asInstanceOf[Ident]) Block(terms,Apply(Select(ident,builderBuildMethod),Nil)) - } private[this] def implicitlyProtoable(entityType: TypeRepr, protoType: TypeRepr):Term = { diff --git a/pbconverts/src/test/protobuf/conversion_test.proto b/pbconverts/src/test/protobuf/conversion_test.proto new file mode 100644 index 0000000..4dc9e38 --- /dev/null +++ b/pbconverts/src/test/protobuf/conversion_test.proto @@ -0,0 +1,50 @@ +syntax = "proto3"; + +option java_package = "pbconverts"; + +import "google/protobuf/wrappers.proto"; +import "google/protobuf/timestamp.proto"; + +message PBTestMessage { + int32 int_value = 1; + int64 long_value = 2; + float float_value = 3; + double double_value = 4; + bool bool_value = 5; + string string_value = 6; + google.protobuf.Int32Value int_Opt = 7; + google.protobuf.Int64Value long_Opt = 8; + google.protobuf.FloatValue float_Opt = 9; + google.protobuf.DoubleValue double_opt = 10; + google.protobuf.BoolValue bool_opt = 11; + google.protobuf.StringValue string_opt = 12; + google.protobuf.Timestamp time = 13; + google.protobuf.Timestamp time_opt = 14; + repeated int32 int_array = 15; + repeated string string_array = 16; + repeated PBPerson person_array = 17; + repeated double seq = 18; + map string_string_k_v = 19; + map long_string_k_v = 20; + map string_int_k_v = 21; + map long_int_k_v = 22; +} + +message PBPerson { + int64 id = 1; + string name = 2; + google.protobuf.StringValue phone = 3; + repeated string hobbies = 4; +} + +message PBTestBytes { + bytes test_bytes = 1; +} + +message IntMessage { + int32 value = 1; +} + +message StringMessage { + string value = 1; +} diff --git a/pbconverts/src/test/protobuf/conversion_test.proto.test b/pbconverts/src/test/protobuf/conversion_test.proto.test deleted file mode 100644 index 2b3fc84..0000000 --- a/pbconverts/src/test/protobuf/conversion_test.proto.test +++ /dev/null @@ -1,50 +0,0 @@ -//syntax = "proto3"; -// -//option java_package = "pbconverts"; -// -//import "google/protobuf/wrappers.proto"; -//import "google/protobuf/timestamp.proto"; -// -//message PBTestMessage { -// int32 int_value = 1; -// int64 long_value = 2; -// float float_value = 3; -// double double_value = 4; -// bool bool_value = 5; -// string string_value = 6; -// google.protobuf.Int32Value int_Opt = 7; -// google.protobuf.Int64Value long_Opt = 8; -// google.protobuf.FloatValue float_Opt = 9; -// google.protobuf.DoubleValue double_opt = 10; -// google.protobuf.BoolValue bool_opt = 11; -// google.protobuf.StringValue string_opt = 12; -// google.protobuf.Timestamp time = 13; -// google.protobuf.Timestamp time_opt = 14; -// repeated int32 int_array = 15; -// repeated string string_array = 16; -// repeated PBPerson person_array = 17; -// repeated double seq = 18; -// map string_string_k_v = 19; -// map long_string_k_v = 20; -// map string_int_k_v = 21; -// map long_int_k_v = 22; -//} -// -//message PBPerson { -// int64 id = 1; -// string name = 2; -// google.protobuf.StringValue phone = 3; -// repeated string hobbies = 4; -//} -// -//message PBTestBytes { -// bytes test_bytes = 1; -//} -// -//message IntMessage { -// int32 value = 1; -//} -// -//message StringMessage { -// string value = 1; -//} diff --git a/pbconverts/src/test/scala/pbconverts/ConversionTest.java b/pbconverts/src/test/scala/pbconverts/ConversionTest.java deleted file mode 100644 index 3193468..0000000 --- a/pbconverts/src/test/scala/pbconverts/ConversionTest.java +++ /dev/null @@ -1,7492 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: conversion_test.proto.test - -package pbconverts; - -import com.google.protobuf.GeneratedMessageV3; -import com.google.protobuf.GeneratedMessageV3.*; - -public final class ConversionTest { - private ConversionTest() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } - - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions( - (com.google.protobuf.ExtensionRegistryLite) registry); - } - public interface PBTestMessageOrBuilder extends - // @@protoc_insertion_point(interface_extends:PBTestMessage) - com.google.protobuf.MessageOrBuilder { - - /** - * int32 int_value = 1; - * @return The intValue. - */ - int getIntValue(); - - /** - * int64 long_value = 2; - * @return The longValue. - */ - long getLongValue(); - - /** - * float float_value = 3; - * @return The floatValue. - */ - float getFloatValue(); - - /** - * double double_value = 4; - * @return The doubleValue. - */ - double getDoubleValue(); - - /** - * bool bool_value = 5; - * @return The boolValue. - */ - boolean getBoolValue(); - - /** - * string string_value = 6; - * @return The stringValue. - */ - String getStringValue(); - /** - * string string_value = 6; - * @return The bytes for stringValue. - */ - com.google.protobuf.ByteString - getStringValueBytes(); - - /** - * .google.protobuf.Int32Value int_Opt = 7; - * @return Whether the intOpt field is set. - */ - boolean hasIntOpt(); - /** - * .google.protobuf.Int32Value int_Opt = 7; - * @return The intOpt. - */ - com.google.protobuf.Int32Value getIntOpt(); - /** - * .google.protobuf.Int32Value int_Opt = 7; - */ - com.google.protobuf.Int32ValueOrBuilder getIntOptOrBuilder(); - - /** - * .google.protobuf.Int64Value long_Opt = 8; - * @return Whether the longOpt field is set. - */ - boolean hasLongOpt(); - /** - * .google.protobuf.Int64Value long_Opt = 8; - * @return The longOpt. - */ - com.google.protobuf.Int64Value getLongOpt(); - /** - * .google.protobuf.Int64Value long_Opt = 8; - */ - com.google.protobuf.Int64ValueOrBuilder getLongOptOrBuilder(); - - /** - * .google.protobuf.FloatValue float_Opt = 9; - * @return Whether the floatOpt field is set. - */ - boolean hasFloatOpt(); - /** - * .google.protobuf.FloatValue float_Opt = 9; - * @return The floatOpt. - */ - com.google.protobuf.FloatValue getFloatOpt(); - /** - * .google.protobuf.FloatValue float_Opt = 9; - */ - com.google.protobuf.FloatValueOrBuilder getFloatOptOrBuilder(); - - /** - * .google.protobuf.DoubleValue double_opt = 10; - * @return Whether the doubleOpt field is set. - */ - boolean hasDoubleOpt(); - /** - * .google.protobuf.DoubleValue double_opt = 10; - * @return The doubleOpt. - */ - com.google.protobuf.DoubleValue getDoubleOpt(); - /** - * .google.protobuf.DoubleValue double_opt = 10; - */ - com.google.protobuf.DoubleValueOrBuilder getDoubleOptOrBuilder(); - - /** - * .google.protobuf.BoolValue bool_opt = 11; - * @return Whether the boolOpt field is set. - */ - boolean hasBoolOpt(); - /** - * .google.protobuf.BoolValue bool_opt = 11; - * @return The boolOpt. - */ - com.google.protobuf.BoolValue getBoolOpt(); - /** - * .google.protobuf.BoolValue bool_opt = 11; - */ - com.google.protobuf.BoolValueOrBuilder getBoolOptOrBuilder(); - - /** - * .google.protobuf.StringValue string_opt = 12; - * @return Whether the stringOpt field is set. - */ - boolean hasStringOpt(); - /** - * .google.protobuf.StringValue string_opt = 12; - * @return The stringOpt. - */ - com.google.protobuf.StringValue getStringOpt(); - /** - * .google.protobuf.StringValue string_opt = 12; - */ - com.google.protobuf.StringValueOrBuilder getStringOptOrBuilder(); - - /** - * .google.protobuf.Timestamp time = 13; - * @return Whether the time field is set. - */ - boolean hasTime(); - /** - * .google.protobuf.Timestamp time = 13; - * @return The time. - */ - com.google.protobuf.Timestamp getTime(); - /** - * .google.protobuf.Timestamp time = 13; - */ - com.google.protobuf.TimestampOrBuilder getTimeOrBuilder(); - - /** - * .google.protobuf.Timestamp time_opt = 14; - * @return Whether the timeOpt field is set. - */ - boolean hasTimeOpt(); - /** - * .google.protobuf.Timestamp time_opt = 14; - * @return The timeOpt. - */ - com.google.protobuf.Timestamp getTimeOpt(); - /** - * .google.protobuf.Timestamp time_opt = 14; - */ - com.google.protobuf.TimestampOrBuilder getTimeOptOrBuilder(); - - /** - * repeated int32 int_array = 15; - * @return A list containing the intArray. - */ - java.util.List getIntArrayList(); - /** - * repeated int32 int_array = 15; - * @return The count of intArray. - */ - int getIntArrayCount(); - /** - * repeated int32 int_array = 15; - * @param index The index of the element to return. - * @return The intArray at the given index. - */ - int getIntArray(int index); - - /** - * repeated string string_array = 16; - * @return A list containing the stringArray. - */ - java.util.List - getStringArrayList(); - /** - * repeated string string_array = 16; - * @return The count of stringArray. - */ - int getStringArrayCount(); - /** - * repeated string string_array = 16; - * @param index The index of the element to return. - * @return The stringArray at the given index. - */ - String getStringArray(int index); - /** - * repeated string string_array = 16; - * @param index The index of the value to return. - * @return The bytes of the stringArray at the given index. - */ - com.google.protobuf.ByteString - getStringArrayBytes(int index); - - /** - * repeated .PBPerson person_array = 17; - */ - java.util.List - getPersonArrayList(); - /** - * repeated .PBPerson person_array = 17; - */ - PBPerson getPersonArray(int index); - /** - * repeated .PBPerson person_array = 17; - */ - int getPersonArrayCount(); - /** - * repeated .PBPerson person_array = 17; - */ - java.util.List - getPersonArrayOrBuilderList(); - /** - * repeated .PBPerson person_array = 17; - */ - PBPersonOrBuilder getPersonArrayOrBuilder( - int index); - - /** - * repeated double seq = 18; - * @return A list containing the seq. - */ - java.util.List getSeqList(); - /** - * repeated double seq = 18; - * @return The count of seq. - */ - int getSeqCount(); - /** - * repeated double seq = 18; - * @param index The index of the element to return. - * @return The seq at the given index. - */ - double getSeq(int index); - - /** - * map<string, string> string_string_k_v = 19; - */ - int getStringStringKVCount(); - /** - * map<string, string> string_string_k_v = 19; - */ - boolean containsStringStringKV( - String key); - /** - * Use {@link #getStringStringKVMap()} instead. - */ - @Deprecated - java.util.Map - getStringStringKV(); - /** - * map<string, string> string_string_k_v = 19; - */ - java.util.Map - getStringStringKVMap(); - /** - * map<string, string> string_string_k_v = 19; - */ - - String getStringStringKVOrDefault( - String key, - String defaultValue); - /** - * map<string, string> string_string_k_v = 19; - */ - - String getStringStringKVOrThrow( - String key); - - /** - * map<int64, string> long_string_k_v = 20; - */ - int getLongStringKVCount(); - /** - * map<int64, string> long_string_k_v = 20; - */ - boolean containsLongStringKV( - long key); - /** - * Use {@link #getLongStringKVMap()} instead. - */ - @Deprecated - java.util.Map - getLongStringKV(); - /** - * map<int64, string> long_string_k_v = 20; - */ - java.util.Map - getLongStringKVMap(); - /** - * map<int64, string> long_string_k_v = 20; - */ - - String getLongStringKVOrDefault( - long key, - String defaultValue); - /** - * map<int64, string> long_string_k_v = 20; - */ - - String getLongStringKVOrThrow( - long key); - - /** - * map<string, int32> string_int_k_v = 21; - */ - int getStringIntKVCount(); - /** - * map<string, int32> string_int_k_v = 21; - */ - boolean containsStringIntKV( - String key); - /** - * Use {@link #getStringIntKVMap()} instead. - */ - @Deprecated - java.util.Map - getStringIntKV(); - /** - * map<string, int32> string_int_k_v = 21; - */ - java.util.Map - getStringIntKVMap(); - /** - * map<string, int32> string_int_k_v = 21; - */ - - int getStringIntKVOrDefault( - String key, - int defaultValue); - /** - * map<string, int32> string_int_k_v = 21; - */ - - int getStringIntKVOrThrow( - String key); - - /** - * map<int64, int32> long_int_k_v = 22; - */ - int getLongIntKVCount(); - /** - * map<int64, int32> long_int_k_v = 22; - */ - boolean containsLongIntKV( - long key); - /** - * Use {@link #getLongIntKVMap()} instead. - */ - @Deprecated - java.util.Map - getLongIntKV(); - /** - * map<int64, int32> long_int_k_v = 22; - */ - java.util.Map - getLongIntKVMap(); - /** - * map<int64, int32> long_int_k_v = 22; - */ - - int getLongIntKVOrDefault( - long key, - int defaultValue); - /** - * map<int64, int32> long_int_k_v = 22; - */ - - int getLongIntKVOrThrow( - long key); - } - /** - * Protobuf type {@code PBTestMessage} - */ - public static final class PBTestMessage extends - GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:PBTestMessage) - PBTestMessageOrBuilder { - private static final long serialVersionUID = 0L; - // Use PBTestMessage.newBuilder() to construct. - private PBTestMessage(GeneratedMessageV3.Builder builder) { - super(builder); - } - private PBTestMessage() { - stringValue_ = ""; - intArray_ = emptyIntList(); - stringArray_ = com.google.protobuf.LazyStringArrayList.EMPTY; - personArray_ = java.util.Collections.emptyList(); - seq_ = emptyDoubleList(); - } - - @Override - @SuppressWarnings({"unused"}) - protected Object newInstance( - UnusedPrivateParameter unused) { - return new PBTestMessage(); - } - - @Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private PBTestMessage( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - case 8: { - - intValue_ = input.readInt32(); - break; - } - case 16: { - - longValue_ = input.readInt64(); - break; - } - case 29: { - - floatValue_ = input.readFloat(); - break; - } - case 33: { - - doubleValue_ = input.readDouble(); - break; - } - case 40: { - - boolValue_ = input.readBool(); - break; - } - case 50: { - String s = input.readStringRequireUtf8(); - - stringValue_ = s; - break; - } - case 58: { - com.google.protobuf.Int32Value.Builder subBuilder = null; - if (intOpt_ != null) { - subBuilder = intOpt_.toBuilder(); - } - intOpt_ = input.readMessage(com.google.protobuf.Int32Value.parser(), extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(intOpt_); - intOpt_ = subBuilder.buildPartial(); - } - - break; - } - case 66: { - com.google.protobuf.Int64Value.Builder subBuilder = null; - if (longOpt_ != null) { - subBuilder = longOpt_.toBuilder(); - } - longOpt_ = input.readMessage(com.google.protobuf.Int64Value.parser(), extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(longOpt_); - longOpt_ = subBuilder.buildPartial(); - } - - break; - } - case 74: { - com.google.protobuf.FloatValue.Builder subBuilder = null; - if (floatOpt_ != null) { - subBuilder = floatOpt_.toBuilder(); - } - floatOpt_ = input.readMessage(com.google.protobuf.FloatValue.parser(), extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(floatOpt_); - floatOpt_ = subBuilder.buildPartial(); - } - - break; - } - case 82: { - com.google.protobuf.DoubleValue.Builder subBuilder = null; - if (doubleOpt_ != null) { - subBuilder = doubleOpt_.toBuilder(); - } - doubleOpt_ = input.readMessage(com.google.protobuf.DoubleValue.parser(), extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(doubleOpt_); - doubleOpt_ = subBuilder.buildPartial(); - } - - break; - } - case 90: { - com.google.protobuf.BoolValue.Builder subBuilder = null; - if (boolOpt_ != null) { - subBuilder = boolOpt_.toBuilder(); - } - boolOpt_ = input.readMessage(com.google.protobuf.BoolValue.parser(), extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(boolOpt_); - boolOpt_ = subBuilder.buildPartial(); - } - - break; - } - case 98: { - com.google.protobuf.StringValue.Builder subBuilder = null; - if (stringOpt_ != null) { - subBuilder = stringOpt_.toBuilder(); - } - stringOpt_ = input.readMessage(com.google.protobuf.StringValue.parser(), extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(stringOpt_); - stringOpt_ = subBuilder.buildPartial(); - } - - break; - } - case 106: { - com.google.protobuf.Timestamp.Builder subBuilder = null; - if (time_ != null) { - subBuilder = time_.toBuilder(); - } - time_ = input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(time_); - time_ = subBuilder.buildPartial(); - } - - break; - } - case 114: { - com.google.protobuf.Timestamp.Builder subBuilder = null; - if (timeOpt_ != null) { - subBuilder = timeOpt_.toBuilder(); - } - timeOpt_ = input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(timeOpt_); - timeOpt_ = subBuilder.buildPartial(); - } - - break; - } - case 120: { - if (!((mutable_bitField0_ & 0x00000001) != 0)) { - intArray_ = newIntList(); - mutable_bitField0_ |= 0x00000001; - } - intArray_.addInt(input.readInt32()); - break; - } - case 122: { - int length = input.readRawVarint32(); - int limit = input.pushLimit(length); - if (!((mutable_bitField0_ & 0x00000001) != 0) && input.getBytesUntilLimit() > 0) { - intArray_ = newIntList(); - mutable_bitField0_ |= 0x00000001; - } - while (input.getBytesUntilLimit() > 0) { - intArray_.addInt(input.readInt32()); - } - input.popLimit(limit); - break; - } - case 130: { - String s = input.readStringRequireUtf8(); - if (!((mutable_bitField0_ & 0x00000002) != 0)) { - stringArray_ = new com.google.protobuf.LazyStringArrayList(); - mutable_bitField0_ |= 0x00000002; - } - stringArray_.add(s); - break; - } - case 138: { - if (!((mutable_bitField0_ & 0x00000004) != 0)) { - personArray_ = new java.util.ArrayList(); - mutable_bitField0_ |= 0x00000004; - } - personArray_.add( - input.readMessage(PBPerson.parser(), extensionRegistry)); - break; - } - case 145: { - if (!((mutable_bitField0_ & 0x00000008) != 0)) { - seq_ = newDoubleList(); - mutable_bitField0_ |= 0x00000008; - } - seq_.addDouble(input.readDouble()); - break; - } - case 146: { - int length = input.readRawVarint32(); - int limit = input.pushLimit(length); - if (!((mutable_bitField0_ & 0x00000008) != 0) && input.getBytesUntilLimit() > 0) { - seq_ = newDoubleList(); - mutable_bitField0_ |= 0x00000008; - } - while (input.getBytesUntilLimit() > 0) { - seq_.addDouble(input.readDouble()); - } - input.popLimit(limit); - break; - } - case 154: { - if (!((mutable_bitField0_ & 0x00000010) != 0)) { - stringStringKV_ = com.google.protobuf.MapField.newMapField( - StringStringKVDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000010; - } - com.google.protobuf.MapEntry - stringStringKV__ = input.readMessage( - StringStringKVDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); - stringStringKV_.getMutableMap().put( - stringStringKV__.getKey(), stringStringKV__.getValue()); - break; - } - case 162: { - if (!((mutable_bitField0_ & 0x00000020) != 0)) { - longStringKV_ = com.google.protobuf.MapField.newMapField( - LongStringKVDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000020; - } - com.google.protobuf.MapEntry - longStringKV__ = input.readMessage( - LongStringKVDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); - longStringKV_.getMutableMap().put( - longStringKV__.getKey(), longStringKV__.getValue()); - break; - } - case 170: { - if (!((mutable_bitField0_ & 0x00000040) != 0)) { - stringIntKV_ = com.google.protobuf.MapField.newMapField( - StringIntKVDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000040; - } - com.google.protobuf.MapEntry - stringIntKV__ = input.readMessage( - StringIntKVDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); - stringIntKV_.getMutableMap().put( - stringIntKV__.getKey(), stringIntKV__.getValue()); - break; - } - case 178: { - if (!((mutable_bitField0_ & 0x00000080) != 0)) { - longIntKV_ = com.google.protobuf.MapField.newMapField( - LongIntKVDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000080; - } - com.google.protobuf.MapEntry - longIntKV__ = input.readMessage( - LongIntKVDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); - longIntKV_.getMutableMap().put( - longIntKV__.getKey(), longIntKV__.getValue()); - break; - } - default: { - if (!parseUnknownField( - input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e).setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000001) != 0)) { - intArray_.makeImmutable(); // C - } - if (((mutable_bitField0_ & 0x00000002) != 0)) { - stringArray_ = stringArray_.getUnmodifiableView(); - } - if (((mutable_bitField0_ & 0x00000004) != 0)) { - personArray_ = java.util.Collections.unmodifiableList(personArray_); - } - if (((mutable_bitField0_ & 0x00000008) != 0)) { - seq_.makeImmutable(); // C - } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ConversionTest.internal_static_PBTestMessage_descriptor; - } - - @SuppressWarnings({"rawtypes"}) - @Override - protected com.google.protobuf.MapField internalGetMapField( - int number) { - switch (number) { - case 19: - return internalGetStringStringKV(); - case 20: - return internalGetLongStringKV(); - case 21: - return internalGetStringIntKV(); - case 22: - return internalGetLongIntKV(); - default: - throw new RuntimeException( - "Invalid map field number: " + number); - } - } - @Override - protected GeneratedMessageV3.FieldAccessorTable - internalGetFieldAccessorTable() { - return ConversionTest.internal_static_PBTestMessage_fieldAccessorTable - .ensureFieldAccessorsInitialized( - PBTestMessage.class, Builder.class); - } - - public static final int INT_VALUE_FIELD_NUMBER = 1; - private int intValue_; - /** - * int32 int_value = 1; - * @return The intValue. - */ - @Override - public int getIntValue() { - return intValue_; - } - - public static final int LONG_VALUE_FIELD_NUMBER = 2; - private long longValue_; - /** - * int64 long_value = 2; - * @return The longValue. - */ - @Override - public long getLongValue() { - return longValue_; - } - - public static final int FLOAT_VALUE_FIELD_NUMBER = 3; - private float floatValue_; - /** - * float float_value = 3; - * @return The floatValue. - */ - @Override - public float getFloatValue() { - return floatValue_; - } - - public static final int DOUBLE_VALUE_FIELD_NUMBER = 4; - private double doubleValue_; - /** - * double double_value = 4; - * @return The doubleValue. - */ - @Override - public double getDoubleValue() { - return doubleValue_; - } - - public static final int BOOL_VALUE_FIELD_NUMBER = 5; - private boolean boolValue_; - /** - * bool bool_value = 5; - * @return The boolValue. - */ - @Override - public boolean getBoolValue() { - return boolValue_; - } - - public static final int STRING_VALUE_FIELD_NUMBER = 6; - private volatile Object stringValue_; - /** - * string string_value = 6; - * @return The stringValue. - */ - @Override - public String getStringValue() { - Object ref = stringValue_; - if (ref instanceof String) { - return (String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - stringValue_ = s; - return s; - } - } - /** - * string string_value = 6; - * @return The bytes for stringValue. - */ - @Override - public com.google.protobuf.ByteString - getStringValueBytes() { - Object ref = stringValue_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - stringValue_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - public static final int INT_OPT_FIELD_NUMBER = 7; - private com.google.protobuf.Int32Value intOpt_; - /** - * .google.protobuf.Int32Value int_Opt = 7; - * @return Whether the intOpt field is set. - */ - @Override - public boolean hasIntOpt() { - return intOpt_ != null; - } - /** - * .google.protobuf.Int32Value int_Opt = 7; - * @return The intOpt. - */ - @Override - public com.google.protobuf.Int32Value getIntOpt() { - return intOpt_ == null ? com.google.protobuf.Int32Value.getDefaultInstance() : intOpt_; - } - /** - * .google.protobuf.Int32Value int_Opt = 7; - */ - @Override - public com.google.protobuf.Int32ValueOrBuilder getIntOptOrBuilder() { - return getIntOpt(); - } - - public static final int LONG_OPT_FIELD_NUMBER = 8; - private com.google.protobuf.Int64Value longOpt_; - /** - * .google.protobuf.Int64Value long_Opt = 8; - * @return Whether the longOpt field is set. - */ - @Override - public boolean hasLongOpt() { - return longOpt_ != null; - } - /** - * .google.protobuf.Int64Value long_Opt = 8; - * @return The longOpt. - */ - @Override - public com.google.protobuf.Int64Value getLongOpt() { - return longOpt_ == null ? com.google.protobuf.Int64Value.getDefaultInstance() : longOpt_; - } - /** - * .google.protobuf.Int64Value long_Opt = 8; - */ - @Override - public com.google.protobuf.Int64ValueOrBuilder getLongOptOrBuilder() { - return getLongOpt(); - } - - public static final int FLOAT_OPT_FIELD_NUMBER = 9; - private com.google.protobuf.FloatValue floatOpt_; - /** - * .google.protobuf.FloatValue float_Opt = 9; - * @return Whether the floatOpt field is set. - */ - @Override - public boolean hasFloatOpt() { - return floatOpt_ != null; - } - /** - * .google.protobuf.FloatValue float_Opt = 9; - * @return The floatOpt. - */ - @Override - public com.google.protobuf.FloatValue getFloatOpt() { - return floatOpt_ == null ? com.google.protobuf.FloatValue.getDefaultInstance() : floatOpt_; - } - /** - * .google.protobuf.FloatValue float_Opt = 9; - */ - @Override - public com.google.protobuf.FloatValueOrBuilder getFloatOptOrBuilder() { - return getFloatOpt(); - } - - public static final int DOUBLE_OPT_FIELD_NUMBER = 10; - private com.google.protobuf.DoubleValue doubleOpt_; - /** - * .google.protobuf.DoubleValue double_opt = 10; - * @return Whether the doubleOpt field is set. - */ - @Override - public boolean hasDoubleOpt() { - return doubleOpt_ != null; - } - /** - * .google.protobuf.DoubleValue double_opt = 10; - * @return The doubleOpt. - */ - @Override - public com.google.protobuf.DoubleValue getDoubleOpt() { - return doubleOpt_ == null ? com.google.protobuf.DoubleValue.getDefaultInstance() : doubleOpt_; - } - /** - * .google.protobuf.DoubleValue double_opt = 10; - */ - @Override - public com.google.protobuf.DoubleValueOrBuilder getDoubleOptOrBuilder() { - return getDoubleOpt(); - } - - public static final int BOOL_OPT_FIELD_NUMBER = 11; - private com.google.protobuf.BoolValue boolOpt_; - /** - * .google.protobuf.BoolValue bool_opt = 11; - * @return Whether the boolOpt field is set. - */ - @Override - public boolean hasBoolOpt() { - return boolOpt_ != null; - } - /** - * .google.protobuf.BoolValue bool_opt = 11; - * @return The boolOpt. - */ - @Override - public com.google.protobuf.BoolValue getBoolOpt() { - return boolOpt_ == null ? com.google.protobuf.BoolValue.getDefaultInstance() : boolOpt_; - } - /** - * .google.protobuf.BoolValue bool_opt = 11; - */ - @Override - public com.google.protobuf.BoolValueOrBuilder getBoolOptOrBuilder() { - return getBoolOpt(); - } - - public static final int STRING_OPT_FIELD_NUMBER = 12; - private com.google.protobuf.StringValue stringOpt_; - /** - * .google.protobuf.StringValue string_opt = 12; - * @return Whether the stringOpt field is set. - */ - @Override - public boolean hasStringOpt() { - return stringOpt_ != null; - } - /** - * .google.protobuf.StringValue string_opt = 12; - * @return The stringOpt. - */ - @Override - public com.google.protobuf.StringValue getStringOpt() { - return stringOpt_ == null ? com.google.protobuf.StringValue.getDefaultInstance() : stringOpt_; - } - /** - * .google.protobuf.StringValue string_opt = 12; - */ - @Override - public com.google.protobuf.StringValueOrBuilder getStringOptOrBuilder() { - return getStringOpt(); - } - - public static final int TIME_FIELD_NUMBER = 13; - private com.google.protobuf.Timestamp time_; - /** - * .google.protobuf.Timestamp time = 13; - * @return Whether the time field is set. - */ - @Override - public boolean hasTime() { - return time_ != null; - } - /** - * .google.protobuf.Timestamp time = 13; - * @return The time. - */ - @Override - public com.google.protobuf.Timestamp getTime() { - return time_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : time_; - } - /** - * .google.protobuf.Timestamp time = 13; - */ - @Override - public com.google.protobuf.TimestampOrBuilder getTimeOrBuilder() { - return getTime(); - } - - public static final int TIME_OPT_FIELD_NUMBER = 14; - private com.google.protobuf.Timestamp timeOpt_; - /** - * .google.protobuf.Timestamp time_opt = 14; - * @return Whether the timeOpt field is set. - */ - @Override - public boolean hasTimeOpt() { - return timeOpt_ != null; - } - /** - * .google.protobuf.Timestamp time_opt = 14; - * @return The timeOpt. - */ - @Override - public com.google.protobuf.Timestamp getTimeOpt() { - return timeOpt_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : timeOpt_; - } - /** - * .google.protobuf.Timestamp time_opt = 14; - */ - @Override - public com.google.protobuf.TimestampOrBuilder getTimeOptOrBuilder() { - return getTimeOpt(); - } - - public static final int INT_ARRAY_FIELD_NUMBER = 15; - private com.google.protobuf.Internal.IntList intArray_; - /** - * repeated int32 int_array = 15; - * @return A list containing the intArray. - */ - @Override - public java.util.List - getIntArrayList() { - return intArray_; - } - /** - * repeated int32 int_array = 15; - * @return The count of intArray. - */ - public int getIntArrayCount() { - return intArray_.size(); - } - /** - * repeated int32 int_array = 15; - * @param index The index of the element to return. - * @return The intArray at the given index. - */ - public int getIntArray(int index) { - return intArray_.getInt(index); - } - private int intArrayMemoizedSerializedSize = -1; - - public static final int STRING_ARRAY_FIELD_NUMBER = 16; - private com.google.protobuf.LazyStringList stringArray_; - /** - * repeated string string_array = 16; - * @return A list containing the stringArray. - */ - public com.google.protobuf.ProtocolStringList - getStringArrayList() { - return stringArray_; - } - /** - * repeated string string_array = 16; - * @return The count of stringArray. - */ - public int getStringArrayCount() { - return stringArray_.size(); - } - /** - * repeated string string_array = 16; - * @param index The index of the element to return. - * @return The stringArray at the given index. - */ - public String getStringArray(int index) { - return stringArray_.get(index); - } - /** - * repeated string string_array = 16; - * @param index The index of the value to return. - * @return The bytes of the stringArray at the given index. - */ - public com.google.protobuf.ByteString - getStringArrayBytes(int index) { - return stringArray_.getByteString(index); - } - - public static final int PERSON_ARRAY_FIELD_NUMBER = 17; - private java.util.List personArray_; - /** - * repeated .PBPerson person_array = 17; - */ - @Override - public java.util.List getPersonArrayList() { - return personArray_; - } - /** - * repeated .PBPerson person_array = 17; - */ - @Override - public java.util.List - getPersonArrayOrBuilderList() { - return personArray_; - } - /** - * repeated .PBPerson person_array = 17; - */ - @Override - public int getPersonArrayCount() { - return personArray_.size(); - } - /** - * repeated .PBPerson person_array = 17; - */ - @Override - public PBPerson getPersonArray(int index) { - return personArray_.get(index); - } - /** - * repeated .PBPerson person_array = 17; - */ - @Override - public PBPersonOrBuilder getPersonArrayOrBuilder( - int index) { - return personArray_.get(index); - } - - public static final int SEQ_FIELD_NUMBER = 18; - private com.google.protobuf.Internal.DoubleList seq_; - /** - * repeated double seq = 18; - * @return A list containing the seq. - */ - @Override - public java.util.List - getSeqList() { - return seq_; - } - /** - * repeated double seq = 18; - * @return The count of seq. - */ - public int getSeqCount() { - return seq_.size(); - } - /** - * repeated double seq = 18; - * @param index The index of the element to return. - * @return The seq at the given index. - */ - public double getSeq(int index) { - return seq_.getDouble(index); - } - private int seqMemoizedSerializedSize = -1; - - public static final int STRING_STRING_K_V_FIELD_NUMBER = 19; - private static final class StringStringKVDefaultEntryHolder { - static final com.google.protobuf.MapEntry< - String, String> defaultEntry = - com.google.protobuf.MapEntry - .newDefaultInstance( - ConversionTest.internal_static_PBTestMessage_StringStringKVEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.STRING, - "", - com.google.protobuf.WireFormat.FieldType.STRING, - ""); - } - private com.google.protobuf.MapField< - String, String> stringStringKV_; - private com.google.protobuf.MapField - internalGetStringStringKV() { - if (stringStringKV_ == null) { - return com.google.protobuf.MapField.emptyMapField( - StringStringKVDefaultEntryHolder.defaultEntry); - } - return stringStringKV_; - } - - public int getStringStringKVCount() { - return internalGetStringStringKV().getMap().size(); - } - /** - * map<string, string> string_string_k_v = 19; - */ - - @Override - public boolean containsStringStringKV( - String key) { - if (key == null) { throw new NullPointerException(); } - return internalGetStringStringKV().getMap().containsKey(key); - } - /** - * Use {@link #getStringStringKVMap()} instead. - */ - @Override - @Deprecated - public java.util.Map getStringStringKV() { - return getStringStringKVMap(); - } - /** - * map<string, string> string_string_k_v = 19; - */ - @Override - - public java.util.Map getStringStringKVMap() { - return internalGetStringStringKV().getMap(); - } - /** - * map<string, string> string_string_k_v = 19; - */ - @Override - - public String getStringStringKVOrDefault( - String key, - String defaultValue) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetStringStringKV().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<string, string> string_string_k_v = 19; - */ - @Override - - public String getStringStringKVOrThrow( - String key) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetStringStringKV().getMap(); - if (!map.containsKey(key)) { - throw new IllegalArgumentException(); - } - return map.get(key); - } - - public static final int LONG_STRING_K_V_FIELD_NUMBER = 20; - private static final class LongStringKVDefaultEntryHolder { - static final com.google.protobuf.MapEntry< - Long, String> defaultEntry = - com.google.protobuf.MapEntry - .newDefaultInstance( - ConversionTest.internal_static_PBTestMessage_LongStringKVEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.INT64, - 0L, - com.google.protobuf.WireFormat.FieldType.STRING, - ""); - } - private com.google.protobuf.MapField< - Long, String> longStringKV_; - private com.google.protobuf.MapField - internalGetLongStringKV() { - if (longStringKV_ == null) { - return com.google.protobuf.MapField.emptyMapField( - LongStringKVDefaultEntryHolder.defaultEntry); - } - return longStringKV_; - } - - public int getLongStringKVCount() { - return internalGetLongStringKV().getMap().size(); - } - /** - * map<int64, string> long_string_k_v = 20; - */ - - @Override - public boolean containsLongStringKV( - long key) { - - return internalGetLongStringKV().getMap().containsKey(key); - } - /** - * Use {@link #getLongStringKVMap()} instead. - */ - @Override - @Deprecated - public java.util.Map getLongStringKV() { - return getLongStringKVMap(); - } - /** - * map<int64, string> long_string_k_v = 20; - */ - @Override - - public java.util.Map getLongStringKVMap() { - return internalGetLongStringKV().getMap(); - } - /** - * map<int64, string> long_string_k_v = 20; - */ - @Override - - public String getLongStringKVOrDefault( - long key, - String defaultValue) { - - java.util.Map map = - internalGetLongStringKV().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<int64, string> long_string_k_v = 20; - */ - @Override - - public String getLongStringKVOrThrow( - long key) { - - java.util.Map map = - internalGetLongStringKV().getMap(); - if (!map.containsKey(key)) { - throw new IllegalArgumentException(); - } - return map.get(key); - } - - public static final int STRING_INT_K_V_FIELD_NUMBER = 21; - private static final class StringIntKVDefaultEntryHolder { - static final com.google.protobuf.MapEntry< - String, Integer> defaultEntry = - com.google.protobuf.MapEntry - .newDefaultInstance( - ConversionTest.internal_static_PBTestMessage_StringIntKVEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.STRING, - "", - com.google.protobuf.WireFormat.FieldType.INT32, - 0); - } - private com.google.protobuf.MapField< - String, Integer> stringIntKV_; - private com.google.protobuf.MapField - internalGetStringIntKV() { - if (stringIntKV_ == null) { - return com.google.protobuf.MapField.emptyMapField( - StringIntKVDefaultEntryHolder.defaultEntry); - } - return stringIntKV_; - } - - public int getStringIntKVCount() { - return internalGetStringIntKV().getMap().size(); - } - /** - * map<string, int32> string_int_k_v = 21; - */ - - @Override - public boolean containsStringIntKV( - String key) { - if (key == null) { throw new NullPointerException(); } - return internalGetStringIntKV().getMap().containsKey(key); - } - /** - * Use {@link #getStringIntKVMap()} instead. - */ - @Override - @Deprecated - public java.util.Map getStringIntKV() { - return getStringIntKVMap(); - } - /** - * map<string, int32> string_int_k_v = 21; - */ - @Override - - public java.util.Map getStringIntKVMap() { - return internalGetStringIntKV().getMap(); - } - /** - * map<string, int32> string_int_k_v = 21; - */ - @Override - - public int getStringIntKVOrDefault( - String key, - int defaultValue) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetStringIntKV().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<string, int32> string_int_k_v = 21; - */ - @Override - - public int getStringIntKVOrThrow( - String key) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetStringIntKV().getMap(); - if (!map.containsKey(key)) { - throw new IllegalArgumentException(); - } - return map.get(key); - } - - public static final int LONG_INT_K_V_FIELD_NUMBER = 22; - private static final class LongIntKVDefaultEntryHolder { - static final com.google.protobuf.MapEntry< - Long, Integer> defaultEntry = - com.google.protobuf.MapEntry - .newDefaultInstance( - ConversionTest.internal_static_PBTestMessage_LongIntKVEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.INT64, - 0L, - com.google.protobuf.WireFormat.FieldType.INT32, - 0); - } - private com.google.protobuf.MapField< - Long, Integer> longIntKV_; - private com.google.protobuf.MapField - internalGetLongIntKV() { - if (longIntKV_ == null) { - return com.google.protobuf.MapField.emptyMapField( - LongIntKVDefaultEntryHolder.defaultEntry); - } - return longIntKV_; - } - - public int getLongIntKVCount() { - return internalGetLongIntKV().getMap().size(); - } - /** - * map<int64, int32> long_int_k_v = 22; - */ - - @Override - public boolean containsLongIntKV( - long key) { - - return internalGetLongIntKV().getMap().containsKey(key); - } - /** - * Use {@link #getLongIntKVMap()} instead. - */ - @Override - @Deprecated - public java.util.Map getLongIntKV() { - return getLongIntKVMap(); - } - /** - * map<int64, int32> long_int_k_v = 22; - */ - @Override - - public java.util.Map getLongIntKVMap() { - return internalGetLongIntKV().getMap(); - } - /** - * map<int64, int32> long_int_k_v = 22; - */ - @Override - - public int getLongIntKVOrDefault( - long key, - int defaultValue) { - - java.util.Map map = - internalGetLongIntKV().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<int64, int32> long_int_k_v = 22; - */ - @Override - - public int getLongIntKVOrThrow( - long key) { - - java.util.Map map = - internalGetLongIntKV().getMap(); - if (!map.containsKey(key)) { - throw new IllegalArgumentException(); - } - return map.get(key); - } - - private byte memoizedIsInitialized = -1; - @Override - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - @Override - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - getSerializedSize(); - if (intValue_ != 0) { - output.writeInt32(1, intValue_); - } - if (longValue_ != 0L) { - output.writeInt64(2, longValue_); - } - if (floatValue_ != 0F) { - output.writeFloat(3, floatValue_); - } - if (doubleValue_ != 0D) { - output.writeDouble(4, doubleValue_); - } - if (boolValue_ != false) { - output.writeBool(5, boolValue_); - } - if (!getStringValueBytes().isEmpty()) { - GeneratedMessageV3.writeString(output, 6, stringValue_); - } - if (intOpt_ != null) { - output.writeMessage(7, getIntOpt()); - } - if (longOpt_ != null) { - output.writeMessage(8, getLongOpt()); - } - if (floatOpt_ != null) { - output.writeMessage(9, getFloatOpt()); - } - if (doubleOpt_ != null) { - output.writeMessage(10, getDoubleOpt()); - } - if (boolOpt_ != null) { - output.writeMessage(11, getBoolOpt()); - } - if (stringOpt_ != null) { - output.writeMessage(12, getStringOpt()); - } - if (time_ != null) { - output.writeMessage(13, getTime()); - } - if (timeOpt_ != null) { - output.writeMessage(14, getTimeOpt()); - } - if (getIntArrayList().size() > 0) { - output.writeUInt32NoTag(122); - output.writeUInt32NoTag(intArrayMemoizedSerializedSize); - } - for (int i = 0; i < intArray_.size(); i++) { - output.writeInt32NoTag(intArray_.getInt(i)); - } - for (int i = 0; i < stringArray_.size(); i++) { - GeneratedMessageV3.writeString(output, 16, stringArray_.getRaw(i)); - } - for (int i = 0; i < personArray_.size(); i++) { - output.writeMessage(17, personArray_.get(i)); - } - if (getSeqList().size() > 0) { - output.writeUInt32NoTag(146); - output.writeUInt32NoTag(seqMemoizedSerializedSize); - } - for (int i = 0; i < seq_.size(); i++) { - output.writeDoubleNoTag(seq_.getDouble(i)); - } - GeneratedMessageV3 - .serializeStringMapTo( - output, - internalGetStringStringKV(), - StringStringKVDefaultEntryHolder.defaultEntry, - 19); - GeneratedMessageV3 - .serializeLongMapTo( - output, - internalGetLongStringKV(), - LongStringKVDefaultEntryHolder.defaultEntry, - 20); - GeneratedMessageV3 - .serializeStringMapTo( - output, - internalGetStringIntKV(), - StringIntKVDefaultEntryHolder.defaultEntry, - 21); - GeneratedMessageV3 - .serializeLongMapTo( - output, - internalGetLongIntKV(), - LongIntKVDefaultEntryHolder.defaultEntry, - 22); - unknownFields.writeTo(output); - } - - @Override - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; - - size = 0; - if (intValue_ != 0) { - size += com.google.protobuf.CodedOutputStream - .computeInt32Size(1, intValue_); - } - if (longValue_ != 0L) { - size += com.google.protobuf.CodedOutputStream - .computeInt64Size(2, longValue_); - } - if (floatValue_ != 0F) { - size += com.google.protobuf.CodedOutputStream - .computeFloatSize(3, floatValue_); - } - if (doubleValue_ != 0D) { - size += com.google.protobuf.CodedOutputStream - .computeDoubleSize(4, doubleValue_); - } - if (boolValue_ != false) { - size += com.google.protobuf.CodedOutputStream - .computeBoolSize(5, boolValue_); - } - if (!getStringValueBytes().isEmpty()) { - size += GeneratedMessageV3.computeStringSize(6, stringValue_); - } - if (intOpt_ != null) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(7, getIntOpt()); - } - if (longOpt_ != null) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(8, getLongOpt()); - } - if (floatOpt_ != null) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(9, getFloatOpt()); - } - if (doubleOpt_ != null) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(10, getDoubleOpt()); - } - if (boolOpt_ != null) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(11, getBoolOpt()); - } - if (stringOpt_ != null) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(12, getStringOpt()); - } - if (time_ != null) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(13, getTime()); - } - if (timeOpt_ != null) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(14, getTimeOpt()); - } - { - int dataSize = 0; - for (int i = 0; i < intArray_.size(); i++) { - dataSize += com.google.protobuf.CodedOutputStream - .computeInt32SizeNoTag(intArray_.getInt(i)); - } - size += dataSize; - if (!getIntArrayList().isEmpty()) { - size += 1; - size += com.google.protobuf.CodedOutputStream - .computeInt32SizeNoTag(dataSize); - } - intArrayMemoizedSerializedSize = dataSize; - } - { - int dataSize = 0; - for (int i = 0; i < stringArray_.size(); i++) { - dataSize += computeStringSizeNoTag(stringArray_.getRaw(i)); - } - size += dataSize; - size += 2 * getStringArrayList().size(); - } - for (int i = 0; i < personArray_.size(); i++) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(17, personArray_.get(i)); - } - { - int dataSize = 0; - dataSize = 8 * getSeqList().size(); - size += dataSize; - if (!getSeqList().isEmpty()) { - size += 2; - size += com.google.protobuf.CodedOutputStream - .computeInt32SizeNoTag(dataSize); - } - seqMemoizedSerializedSize = dataSize; - } - for (java.util.Map.Entry entry - : internalGetStringStringKV().getMap().entrySet()) { - com.google.protobuf.MapEntry - stringStringKV__ = StringStringKVDefaultEntryHolder.defaultEntry.newBuilderForType() - .setKey(entry.getKey()) - .setValue(entry.getValue()) - .build(); - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(19, stringStringKV__); - } - for (java.util.Map.Entry entry - : internalGetLongStringKV().getMap().entrySet()) { - com.google.protobuf.MapEntry - longStringKV__ = LongStringKVDefaultEntryHolder.defaultEntry.newBuilderForType() - .setKey(entry.getKey()) - .setValue(entry.getValue()) - .build(); - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(20, longStringKV__); - } - for (java.util.Map.Entry entry - : internalGetStringIntKV().getMap().entrySet()) { - com.google.protobuf.MapEntry - stringIntKV__ = StringIntKVDefaultEntryHolder.defaultEntry.newBuilderForType() - .setKey(entry.getKey()) - .setValue(entry.getValue()) - .build(); - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(21, stringIntKV__); - } - for (java.util.Map.Entry entry - : internalGetLongIntKV().getMap().entrySet()) { - com.google.protobuf.MapEntry - longIntKV__ = LongIntKVDefaultEntryHolder.defaultEntry.newBuilderForType() - .setKey(entry.getKey()) - .setValue(entry.getValue()) - .build(); - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(22, longIntKV__); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof PBTestMessage)) { - return super.equals(obj); - } - PBTestMessage other = (PBTestMessage) obj; - - if (getIntValue() - != other.getIntValue()) return false; - if (getLongValue() - != other.getLongValue()) return false; - if (Float.floatToIntBits(getFloatValue()) - != Float.floatToIntBits( - other.getFloatValue())) return false; - if (Double.doubleToLongBits(getDoubleValue()) - != Double.doubleToLongBits( - other.getDoubleValue())) return false; - if (getBoolValue() - != other.getBoolValue()) return false; - if (!getStringValue() - .equals(other.getStringValue())) return false; - if (hasIntOpt() != other.hasIntOpt()) return false; - if (hasIntOpt()) { - if (!getIntOpt() - .equals(other.getIntOpt())) return false; - } - if (hasLongOpt() != other.hasLongOpt()) return false; - if (hasLongOpt()) { - if (!getLongOpt() - .equals(other.getLongOpt())) return false; - } - if (hasFloatOpt() != other.hasFloatOpt()) return false; - if (hasFloatOpt()) { - if (!getFloatOpt() - .equals(other.getFloatOpt())) return false; - } - if (hasDoubleOpt() != other.hasDoubleOpt()) return false; - if (hasDoubleOpt()) { - if (!getDoubleOpt() - .equals(other.getDoubleOpt())) return false; - } - if (hasBoolOpt() != other.hasBoolOpt()) return false; - if (hasBoolOpt()) { - if (!getBoolOpt() - .equals(other.getBoolOpt())) return false; - } - if (hasStringOpt() != other.hasStringOpt()) return false; - if (hasStringOpt()) { - if (!getStringOpt() - .equals(other.getStringOpt())) return false; - } - if (hasTime() != other.hasTime()) return false; - if (hasTime()) { - if (!getTime() - .equals(other.getTime())) return false; - } - if (hasTimeOpt() != other.hasTimeOpt()) return false; - if (hasTimeOpt()) { - if (!getTimeOpt() - .equals(other.getTimeOpt())) return false; - } - if (!getIntArrayList() - .equals(other.getIntArrayList())) return false; - if (!getStringArrayList() - .equals(other.getStringArrayList())) return false; - if (!getPersonArrayList() - .equals(other.getPersonArrayList())) return false; - if (!getSeqList() - .equals(other.getSeqList())) return false; - if (!internalGetStringStringKV().equals( - other.internalGetStringStringKV())) return false; - if (!internalGetLongStringKV().equals( - other.internalGetLongStringKV())) return false; - if (!internalGetStringIntKV().equals( - other.internalGetStringIntKV())) return false; - if (!internalGetLongIntKV().equals( - other.internalGetLongIntKV())) return false; - if (!unknownFields.equals(other.unknownFields)) return false; - return true; - } - - @Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + INT_VALUE_FIELD_NUMBER; - hash = (53 * hash) + getIntValue(); - hash = (37 * hash) + LONG_VALUE_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashLong( - getLongValue()); - hash = (37 * hash) + FLOAT_VALUE_FIELD_NUMBER; - hash = (53 * hash) + Float.floatToIntBits( - getFloatValue()); - hash = (37 * hash) + DOUBLE_VALUE_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashLong( - Double.doubleToLongBits(getDoubleValue())); - hash = (37 * hash) + BOOL_VALUE_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( - getBoolValue()); - hash = (37 * hash) + STRING_VALUE_FIELD_NUMBER; - hash = (53 * hash) + getStringValue().hashCode(); - if (hasIntOpt()) { - hash = (37 * hash) + INT_OPT_FIELD_NUMBER; - hash = (53 * hash) + getIntOpt().hashCode(); - } - if (hasLongOpt()) { - hash = (37 * hash) + LONG_OPT_FIELD_NUMBER; - hash = (53 * hash) + getLongOpt().hashCode(); - } - if (hasFloatOpt()) { - hash = (37 * hash) + FLOAT_OPT_FIELD_NUMBER; - hash = (53 * hash) + getFloatOpt().hashCode(); - } - if (hasDoubleOpt()) { - hash = (37 * hash) + DOUBLE_OPT_FIELD_NUMBER; - hash = (53 * hash) + getDoubleOpt().hashCode(); - } - if (hasBoolOpt()) { - hash = (37 * hash) + BOOL_OPT_FIELD_NUMBER; - hash = (53 * hash) + getBoolOpt().hashCode(); - } - if (hasStringOpt()) { - hash = (37 * hash) + STRING_OPT_FIELD_NUMBER; - hash = (53 * hash) + getStringOpt().hashCode(); - } - if (hasTime()) { - hash = (37 * hash) + TIME_FIELD_NUMBER; - hash = (53 * hash) + getTime().hashCode(); - } - if (hasTimeOpt()) { - hash = (37 * hash) + TIME_OPT_FIELD_NUMBER; - hash = (53 * hash) + getTimeOpt().hashCode(); - } - if (getIntArrayCount() > 0) { - hash = (37 * hash) + INT_ARRAY_FIELD_NUMBER; - hash = (53 * hash) + getIntArrayList().hashCode(); - } - if (getStringArrayCount() > 0) { - hash = (37 * hash) + STRING_ARRAY_FIELD_NUMBER; - hash = (53 * hash) + getStringArrayList().hashCode(); - } - if (getPersonArrayCount() > 0) { - hash = (37 * hash) + PERSON_ARRAY_FIELD_NUMBER; - hash = (53 * hash) + getPersonArrayList().hashCode(); - } - if (getSeqCount() > 0) { - hash = (37 * hash) + SEQ_FIELD_NUMBER; - hash = (53 * hash) + getSeqList().hashCode(); - } - if (!internalGetStringStringKV().getMap().isEmpty()) { - hash = (37 * hash) + STRING_STRING_K_V_FIELD_NUMBER; - hash = (53 * hash) + internalGetStringStringKV().hashCode(); - } - if (!internalGetLongStringKV().getMap().isEmpty()) { - hash = (37 * hash) + LONG_STRING_K_V_FIELD_NUMBER; - hash = (53 * hash) + internalGetLongStringKV().hashCode(); - } - if (!internalGetStringIntKV().getMap().isEmpty()) { - hash = (37 * hash) + STRING_INT_K_V_FIELD_NUMBER; - hash = (53 * hash) + internalGetStringIntKV().hashCode(); - } - if (!internalGetLongIntKV().getMap().isEmpty()) { - hash = (37 * hash) + LONG_INT_K_V_FIELD_NUMBER; - hash = (53 * hash) + internalGetLongIntKV().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static PBTestMessage parseFrom( - java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static PBTestMessage parseFrom( - java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static PBTestMessage parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static PBTestMessage parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static PBTestMessage parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static PBTestMessage parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static PBTestMessage parseFrom(java.io.InputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static PBTestMessage parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - public static PBTestMessage parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - public static PBTestMessage parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - public static PBTestMessage parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static PBTestMessage parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - @Override - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - public static Builder newBuilder(PBTestMessage prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - @Override - public Builder toBuilder() { - return this == DEFAULT_INSTANCE - ? new Builder() : new Builder().mergeFrom(this); - } - - @Override - protected Builder newBuilderForType( - GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** - * Protobuf type {@code PBTestMessage} - */ - public static final class Builder extends - GeneratedMessageV3.Builder implements - // @@protoc_insertion_point(builder_implements:PBTestMessage) - PBTestMessageOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ConversionTest.internal_static_PBTestMessage_descriptor; - } - - @SuppressWarnings({"rawtypes"}) - protected com.google.protobuf.MapField internalGetMapField( - int number) { - switch (number) { - case 19: - return internalGetStringStringKV(); - case 20: - return internalGetLongStringKV(); - case 21: - return internalGetStringIntKV(); - case 22: - return internalGetLongIntKV(); - default: - throw new RuntimeException( - "Invalid map field number: " + number); - } - } - @SuppressWarnings({"rawtypes"}) - protected com.google.protobuf.MapField internalGetMutableMapField( - int number) { - switch (number) { - case 19: - return internalGetMutableStringStringKV(); - case 20: - return internalGetMutableLongStringKV(); - case 21: - return internalGetMutableStringIntKV(); - case 22: - return internalGetMutableLongIntKV(); - default: - throw new RuntimeException( - "Invalid map field number: " + number); - } - } - @Override - protected GeneratedMessageV3.FieldAccessorTable - internalGetFieldAccessorTable() { - return ConversionTest.internal_static_PBTestMessage_fieldAccessorTable - .ensureFieldAccessorsInitialized( - PBTestMessage.class, Builder.class); - } - - // Construct using pbconverts.ConversionTest.PBTestMessage.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (GeneratedMessageV3 - .alwaysUseFieldBuilders) { - getPersonArrayFieldBuilder(); - } - } - @Override - public Builder clear() { - super.clear(); - intValue_ = 0; - - longValue_ = 0L; - - floatValue_ = 0F; - - doubleValue_ = 0D; - - boolValue_ = false; - - stringValue_ = ""; - - if (intOptBuilder_ == null) { - intOpt_ = null; - } else { - intOpt_ = null; - intOptBuilder_ = null; - } - if (longOptBuilder_ == null) { - longOpt_ = null; - } else { - longOpt_ = null; - longOptBuilder_ = null; - } - if (floatOptBuilder_ == null) { - floatOpt_ = null; - } else { - floatOpt_ = null; - floatOptBuilder_ = null; - } - if (doubleOptBuilder_ == null) { - doubleOpt_ = null; - } else { - doubleOpt_ = null; - doubleOptBuilder_ = null; - } - if (boolOptBuilder_ == null) { - boolOpt_ = null; - } else { - boolOpt_ = null; - boolOptBuilder_ = null; - } - if (stringOptBuilder_ == null) { - stringOpt_ = null; - } else { - stringOpt_ = null; - stringOptBuilder_ = null; - } - if (timeBuilder_ == null) { - time_ = null; - } else { - time_ = null; - timeBuilder_ = null; - } - if (timeOptBuilder_ == null) { - timeOpt_ = null; - } else { - timeOpt_ = null; - timeOptBuilder_ = null; - } - intArray_ = emptyIntList(); - bitField0_ = (bitField0_ & ~0x00000001); - stringArray_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000002); - if (personArrayBuilder_ == null) { - personArray_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000004); - } else { - personArrayBuilder_.clear(); - } - seq_ = emptyDoubleList(); - bitField0_ = (bitField0_ & ~0x00000008); - internalGetMutableStringStringKV().clear(); - internalGetMutableLongStringKV().clear(); - internalGetMutableStringIntKV().clear(); - internalGetMutableLongIntKV().clear(); - return this; - } - - @Override - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return ConversionTest.internal_static_PBTestMessage_descriptor; - } - - @Override - public PBTestMessage getDefaultInstanceForType() { - return PBTestMessage.getDefaultInstance(); - } - - @Override - public PBTestMessage build() { - PBTestMessage result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - @Override - public PBTestMessage buildPartial() { - PBTestMessage result = new PBTestMessage(this); - int from_bitField0_ = bitField0_; - result.intValue_ = intValue_; - result.longValue_ = longValue_; - result.floatValue_ = floatValue_; - result.doubleValue_ = doubleValue_; - result.boolValue_ = boolValue_; - result.stringValue_ = stringValue_; - if (intOptBuilder_ == null) { - result.intOpt_ = intOpt_; - } else { - result.intOpt_ = intOptBuilder_.build(); - } - if (longOptBuilder_ == null) { - result.longOpt_ = longOpt_; - } else { - result.longOpt_ = longOptBuilder_.build(); - } - if (floatOptBuilder_ == null) { - result.floatOpt_ = floatOpt_; - } else { - result.floatOpt_ = floatOptBuilder_.build(); - } - if (doubleOptBuilder_ == null) { - result.doubleOpt_ = doubleOpt_; - } else { - result.doubleOpt_ = doubleOptBuilder_.build(); - } - if (boolOptBuilder_ == null) { - result.boolOpt_ = boolOpt_; - } else { - result.boolOpt_ = boolOptBuilder_.build(); - } - if (stringOptBuilder_ == null) { - result.stringOpt_ = stringOpt_; - } else { - result.stringOpt_ = stringOptBuilder_.build(); - } - if (timeBuilder_ == null) { - result.time_ = time_; - } else { - result.time_ = timeBuilder_.build(); - } - if (timeOptBuilder_ == null) { - result.timeOpt_ = timeOpt_; - } else { - result.timeOpt_ = timeOptBuilder_.build(); - } - if (((bitField0_ & 0x00000001) != 0)) { - intArray_.makeImmutable(); - bitField0_ = (bitField0_ & ~0x00000001); - } - result.intArray_ = intArray_; - if (((bitField0_ & 0x00000002) != 0)) { - stringArray_ = stringArray_.getUnmodifiableView(); - bitField0_ = (bitField0_ & ~0x00000002); - } - result.stringArray_ = stringArray_; - if (personArrayBuilder_ == null) { - if (((bitField0_ & 0x00000004) != 0)) { - personArray_ = java.util.Collections.unmodifiableList(personArray_); - bitField0_ = (bitField0_ & ~0x00000004); - } - result.personArray_ = personArray_; - } else { - result.personArray_ = personArrayBuilder_.build(); - } - if (((bitField0_ & 0x00000008) != 0)) { - seq_.makeImmutable(); - bitField0_ = (bitField0_ & ~0x00000008); - } - result.seq_ = seq_; - result.stringStringKV_ = internalGetStringStringKV(); - result.stringStringKV_.makeImmutable(); - result.longStringKV_ = internalGetLongStringKV(); - result.longStringKV_.makeImmutable(); - result.stringIntKV_ = internalGetStringIntKV(); - result.stringIntKV_.makeImmutable(); - result.longIntKV_ = internalGetLongIntKV(); - result.longIntKV_.makeImmutable(); - onBuilt(); - return result; - } - - @Override - public Builder clone() { - return super.clone(); - } - @Override - public Builder setField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.setField(field, value); - } - @Override - public Builder clearField( - com.google.protobuf.Descriptors.FieldDescriptor field) { - return super.clearField(field); - } - @Override - public Builder clearOneof( - com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return super.clearOneof(oneof); - } - @Override - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - int index, Object value) { - return super.setRepeatedField(field, index, value); - } - @Override - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.addRepeatedField(field, value); - } - @Override - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof PBTestMessage) { - return mergeFrom((PBTestMessage)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(PBTestMessage other) { - if (other == PBTestMessage.getDefaultInstance()) return this; - if (other.getIntValue() != 0) { - setIntValue(other.getIntValue()); - } - if (other.getLongValue() != 0L) { - setLongValue(other.getLongValue()); - } - if (other.getFloatValue() != 0F) { - setFloatValue(other.getFloatValue()); - } - if (other.getDoubleValue() != 0D) { - setDoubleValue(other.getDoubleValue()); - } - if (other.getBoolValue() != false) { - setBoolValue(other.getBoolValue()); - } - if (!other.getStringValue().isEmpty()) { - stringValue_ = other.stringValue_; - onChanged(); - } - if (other.hasIntOpt()) { - mergeIntOpt(other.getIntOpt()); - } - if (other.hasLongOpt()) { - mergeLongOpt(other.getLongOpt()); - } - if (other.hasFloatOpt()) { - mergeFloatOpt(other.getFloatOpt()); - } - if (other.hasDoubleOpt()) { - mergeDoubleOpt(other.getDoubleOpt()); - } - if (other.hasBoolOpt()) { - mergeBoolOpt(other.getBoolOpt()); - } - if (other.hasStringOpt()) { - mergeStringOpt(other.getStringOpt()); - } - if (other.hasTime()) { - mergeTime(other.getTime()); - } - if (other.hasTimeOpt()) { - mergeTimeOpt(other.getTimeOpt()); - } - if (!other.intArray_.isEmpty()) { - if (intArray_.isEmpty()) { - intArray_ = other.intArray_; - bitField0_ = (bitField0_ & ~0x00000001); - } else { - ensureIntArrayIsMutable(); - intArray_.addAll(other.intArray_); - } - onChanged(); - } - if (!other.stringArray_.isEmpty()) { - if (stringArray_.isEmpty()) { - stringArray_ = other.stringArray_; - bitField0_ = (bitField0_ & ~0x00000002); - } else { - ensureStringArrayIsMutable(); - stringArray_.addAll(other.stringArray_); - } - onChanged(); - } - if (personArrayBuilder_ == null) { - if (!other.personArray_.isEmpty()) { - if (personArray_.isEmpty()) { - personArray_ = other.personArray_; - bitField0_ = (bitField0_ & ~0x00000004); - } else { - ensurePersonArrayIsMutable(); - personArray_.addAll(other.personArray_); - } - onChanged(); - } - } else { - if (!other.personArray_.isEmpty()) { - if (personArrayBuilder_.isEmpty()) { - personArrayBuilder_.dispose(); - personArrayBuilder_ = null; - personArray_ = other.personArray_; - bitField0_ = (bitField0_ & ~0x00000004); - personArrayBuilder_ = - GeneratedMessageV3.alwaysUseFieldBuilders ? - getPersonArrayFieldBuilder() : null; - } else { - personArrayBuilder_.addAllMessages(other.personArray_); - } - } - } - if (!other.seq_.isEmpty()) { - if (seq_.isEmpty()) { - seq_ = other.seq_; - bitField0_ = (bitField0_ & ~0x00000008); - } else { - ensureSeqIsMutable(); - seq_.addAll(other.seq_); - } - onChanged(); - } - internalGetMutableStringStringKV().mergeFrom( - other.internalGetStringStringKV()); - internalGetMutableLongStringKV().mergeFrom( - other.internalGetLongStringKV()); - internalGetMutableStringIntKV().mergeFrom( - other.internalGetStringIntKV()); - internalGetMutableLongIntKV().mergeFrom( - other.internalGetLongIntKV()); - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - @Override - public final boolean isInitialized() { - return true; - } - - @Override - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - PBTestMessage parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (PBTestMessage) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - private int bitField0_; - - private int intValue_ ; - /** - * int32 int_value = 1; - * @return The intValue. - */ - @Override - public int getIntValue() { - return intValue_; - } - /** - * int32 int_value = 1; - * @param value The intValue to set. - * @return This builder for chaining. - */ - public Builder setIntValue(int value) { - - intValue_ = value; - onChanged(); - return this; - } - /** - * int32 int_value = 1; - * @return This builder for chaining. - */ - public Builder clearIntValue() { - - intValue_ = 0; - onChanged(); - return this; - } - - private long longValue_ ; - /** - * int64 long_value = 2; - * @return The longValue. - */ - @Override - public long getLongValue() { - return longValue_; - } - /** - * int64 long_value = 2; - * @param value The longValue to set. - * @return This builder for chaining. - */ - public Builder setLongValue(long value) { - - longValue_ = value; - onChanged(); - return this; - } - /** - * int64 long_value = 2; - * @return This builder for chaining. - */ - public Builder clearLongValue() { - - longValue_ = 0L; - onChanged(); - return this; - } - - private float floatValue_ ; - /** - * float float_value = 3; - * @return The floatValue. - */ - @Override - public float getFloatValue() { - return floatValue_; - } - /** - * float float_value = 3; - * @param value The floatValue to set. - * @return This builder for chaining. - */ - public Builder setFloatValue(float value) { - - floatValue_ = value; - onChanged(); - return this; - } - /** - * float float_value = 3; - * @return This builder for chaining. - */ - public Builder clearFloatValue() { - - floatValue_ = 0F; - onChanged(); - return this; - } - - private double doubleValue_ ; - /** - * double double_value = 4; - * @return The doubleValue. - */ - @Override - public double getDoubleValue() { - return doubleValue_; - } - /** - * double double_value = 4; - * @param value The doubleValue to set. - * @return This builder for chaining. - */ - public Builder setDoubleValue(double value) { - - doubleValue_ = value; - onChanged(); - return this; - } - /** - * double double_value = 4; - * @return This builder for chaining. - */ - public Builder clearDoubleValue() { - - doubleValue_ = 0D; - onChanged(); - return this; - } - - private boolean boolValue_ ; - /** - * bool bool_value = 5; - * @return The boolValue. - */ - @Override - public boolean getBoolValue() { - return boolValue_; - } - /** - * bool bool_value = 5; - * @param value The boolValue to set. - * @return This builder for chaining. - */ - public Builder setBoolValue(boolean value) { - - boolValue_ = value; - onChanged(); - return this; - } - /** - * bool bool_value = 5; - * @return This builder for chaining. - */ - public Builder clearBoolValue() { - - boolValue_ = false; - onChanged(); - return this; - } - - private Object stringValue_ = ""; - /** - * string string_value = 6; - * @return The stringValue. - */ - public String getStringValue() { - Object ref = stringValue_; - if (!(ref instanceof String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - stringValue_ = s; - return s; - } else { - return (String) ref; - } - } - /** - * string string_value = 6; - * @return The bytes for stringValue. - */ - public com.google.protobuf.ByteString - getStringValueBytes() { - Object ref = stringValue_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - stringValue_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * string string_value = 6; - * @param value The stringValue to set. - * @return This builder for chaining. - */ - public Builder setStringValue( - String value) { - if (value == null) { - throw new NullPointerException(); - } - - stringValue_ = value; - onChanged(); - return this; - } - /** - * string string_value = 6; - * @return This builder for chaining. - */ - public Builder clearStringValue() { - - stringValue_ = getDefaultInstance().getStringValue(); - onChanged(); - return this; - } - /** - * string string_value = 6; - * @param value The bytes for stringValue to set. - * @return This builder for chaining. - */ - public Builder setStringValueBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - stringValue_ = value; - onChanged(); - return this; - } - - private com.google.protobuf.Int32Value intOpt_; - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.Int32Value, com.google.protobuf.Int32Value.Builder, com.google.protobuf.Int32ValueOrBuilder> intOptBuilder_; - /** - * .google.protobuf.Int32Value int_Opt = 7; - * @return Whether the intOpt field is set. - */ - public boolean hasIntOpt() { - return intOptBuilder_ != null || intOpt_ != null; - } - /** - * .google.protobuf.Int32Value int_Opt = 7; - * @return The intOpt. - */ - public com.google.protobuf.Int32Value getIntOpt() { - if (intOptBuilder_ == null) { - return intOpt_ == null ? com.google.protobuf.Int32Value.getDefaultInstance() : intOpt_; - } else { - return intOptBuilder_.getMessage(); - } - } - /** - * .google.protobuf.Int32Value int_Opt = 7; - */ - public Builder setIntOpt(com.google.protobuf.Int32Value value) { - if (intOptBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - intOpt_ = value; - onChanged(); - } else { - intOptBuilder_.setMessage(value); - } - - return this; - } - /** - * .google.protobuf.Int32Value int_Opt = 7; - */ - public Builder setIntOpt( - com.google.protobuf.Int32Value.Builder builderForValue) { - if (intOptBuilder_ == null) { - intOpt_ = builderForValue.build(); - onChanged(); - } else { - intOptBuilder_.setMessage(builderForValue.build()); - } - - return this; - } - /** - * .google.protobuf.Int32Value int_Opt = 7; - */ - public Builder mergeIntOpt(com.google.protobuf.Int32Value value) { - if (intOptBuilder_ == null) { - if (intOpt_ != null) { - intOpt_ = - com.google.protobuf.Int32Value.newBuilder(intOpt_).mergeFrom(value).buildPartial(); - } else { - intOpt_ = value; - } - onChanged(); - } else { - intOptBuilder_.mergeFrom(value); - } - - return this; - } - /** - * .google.protobuf.Int32Value int_Opt = 7; - */ - public Builder clearIntOpt() { - if (intOptBuilder_ == null) { - intOpt_ = null; - onChanged(); - } else { - intOpt_ = null; - intOptBuilder_ = null; - } - - return this; - } - /** - * .google.protobuf.Int32Value int_Opt = 7; - */ - public com.google.protobuf.Int32Value.Builder getIntOptBuilder() { - - onChanged(); - return getIntOptFieldBuilder().getBuilder(); - } - /** - * .google.protobuf.Int32Value int_Opt = 7; - */ - public com.google.protobuf.Int32ValueOrBuilder getIntOptOrBuilder() { - if (intOptBuilder_ != null) { - return intOptBuilder_.getMessageOrBuilder(); - } else { - return intOpt_ == null ? - com.google.protobuf.Int32Value.getDefaultInstance() : intOpt_; - } - } - /** - * .google.protobuf.Int32Value int_Opt = 7; - */ - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.Int32Value, com.google.protobuf.Int32Value.Builder, com.google.protobuf.Int32ValueOrBuilder> - getIntOptFieldBuilder() { - if (intOptBuilder_ == null) { - intOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.Int32Value, com.google.protobuf.Int32Value.Builder, com.google.protobuf.Int32ValueOrBuilder>( - getIntOpt(), - getParentForChildren(), - isClean()); - intOpt_ = null; - } - return intOptBuilder_; - } - - private com.google.protobuf.Int64Value longOpt_; - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.Int64Value, com.google.protobuf.Int64Value.Builder, com.google.protobuf.Int64ValueOrBuilder> longOptBuilder_; - /** - * .google.protobuf.Int64Value long_Opt = 8; - * @return Whether the longOpt field is set. - */ - public boolean hasLongOpt() { - return longOptBuilder_ != null || longOpt_ != null; - } - /** - * .google.protobuf.Int64Value long_Opt = 8; - * @return The longOpt. - */ - public com.google.protobuf.Int64Value getLongOpt() { - if (longOptBuilder_ == null) { - return longOpt_ == null ? com.google.protobuf.Int64Value.getDefaultInstance() : longOpt_; - } else { - return longOptBuilder_.getMessage(); - } - } - /** - * .google.protobuf.Int64Value long_Opt = 8; - */ - public Builder setLongOpt(com.google.protobuf.Int64Value value) { - if (longOptBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - longOpt_ = value; - onChanged(); - } else { - longOptBuilder_.setMessage(value); - } - - return this; - } - /** - * .google.protobuf.Int64Value long_Opt = 8; - */ - public Builder setLongOpt( - com.google.protobuf.Int64Value.Builder builderForValue) { - if (longOptBuilder_ == null) { - longOpt_ = builderForValue.build(); - onChanged(); - } else { - longOptBuilder_.setMessage(builderForValue.build()); - } - - return this; - } - /** - * .google.protobuf.Int64Value long_Opt = 8; - */ - public Builder mergeLongOpt(com.google.protobuf.Int64Value value) { - if (longOptBuilder_ == null) { - if (longOpt_ != null) { - longOpt_ = - com.google.protobuf.Int64Value.newBuilder(longOpt_).mergeFrom(value).buildPartial(); - } else { - longOpt_ = value; - } - onChanged(); - } else { - longOptBuilder_.mergeFrom(value); - } - - return this; - } - /** - * .google.protobuf.Int64Value long_Opt = 8; - */ - public Builder clearLongOpt() { - if (longOptBuilder_ == null) { - longOpt_ = null; - onChanged(); - } else { - longOpt_ = null; - longOptBuilder_ = null; - } - - return this; - } - /** - * .google.protobuf.Int64Value long_Opt = 8; - */ - public com.google.protobuf.Int64Value.Builder getLongOptBuilder() { - - onChanged(); - return getLongOptFieldBuilder().getBuilder(); - } - /** - * .google.protobuf.Int64Value long_Opt = 8; - */ - public com.google.protobuf.Int64ValueOrBuilder getLongOptOrBuilder() { - if (longOptBuilder_ != null) { - return longOptBuilder_.getMessageOrBuilder(); - } else { - return longOpt_ == null ? - com.google.protobuf.Int64Value.getDefaultInstance() : longOpt_; - } - } - /** - * .google.protobuf.Int64Value long_Opt = 8; - */ - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.Int64Value, com.google.protobuf.Int64Value.Builder, com.google.protobuf.Int64ValueOrBuilder> - getLongOptFieldBuilder() { - if (longOptBuilder_ == null) { - longOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.Int64Value, com.google.protobuf.Int64Value.Builder, com.google.protobuf.Int64ValueOrBuilder>( - getLongOpt(), - getParentForChildren(), - isClean()); - longOpt_ = null; - } - return longOptBuilder_; - } - - private com.google.protobuf.FloatValue floatOpt_; - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.FloatValue, com.google.protobuf.FloatValue.Builder, com.google.protobuf.FloatValueOrBuilder> floatOptBuilder_; - /** - * .google.protobuf.FloatValue float_Opt = 9; - * @return Whether the floatOpt field is set. - */ - public boolean hasFloatOpt() { - return floatOptBuilder_ != null || floatOpt_ != null; - } - /** - * .google.protobuf.FloatValue float_Opt = 9; - * @return The floatOpt. - */ - public com.google.protobuf.FloatValue getFloatOpt() { - if (floatOptBuilder_ == null) { - return floatOpt_ == null ? com.google.protobuf.FloatValue.getDefaultInstance() : floatOpt_; - } else { - return floatOptBuilder_.getMessage(); - } - } - /** - * .google.protobuf.FloatValue float_Opt = 9; - */ - public Builder setFloatOpt(com.google.protobuf.FloatValue value) { - if (floatOptBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - floatOpt_ = value; - onChanged(); - } else { - floatOptBuilder_.setMessage(value); - } - - return this; - } - /** - * .google.protobuf.FloatValue float_Opt = 9; - */ - public Builder setFloatOpt( - com.google.protobuf.FloatValue.Builder builderForValue) { - if (floatOptBuilder_ == null) { - floatOpt_ = builderForValue.build(); - onChanged(); - } else { - floatOptBuilder_.setMessage(builderForValue.build()); - } - - return this; - } - /** - * .google.protobuf.FloatValue float_Opt = 9; - */ - public Builder mergeFloatOpt(com.google.protobuf.FloatValue value) { - if (floatOptBuilder_ == null) { - if (floatOpt_ != null) { - floatOpt_ = - com.google.protobuf.FloatValue.newBuilder(floatOpt_).mergeFrom(value).buildPartial(); - } else { - floatOpt_ = value; - } - onChanged(); - } else { - floatOptBuilder_.mergeFrom(value); - } - - return this; - } - /** - * .google.protobuf.FloatValue float_Opt = 9; - */ - public Builder clearFloatOpt() { - if (floatOptBuilder_ == null) { - floatOpt_ = null; - onChanged(); - } else { - floatOpt_ = null; - floatOptBuilder_ = null; - } - - return this; - } - /** - * .google.protobuf.FloatValue float_Opt = 9; - */ - public com.google.protobuf.FloatValue.Builder getFloatOptBuilder() { - - onChanged(); - return getFloatOptFieldBuilder().getBuilder(); - } - /** - * .google.protobuf.FloatValue float_Opt = 9; - */ - public com.google.protobuf.FloatValueOrBuilder getFloatOptOrBuilder() { - if (floatOptBuilder_ != null) { - return floatOptBuilder_.getMessageOrBuilder(); - } else { - return floatOpt_ == null ? - com.google.protobuf.FloatValue.getDefaultInstance() : floatOpt_; - } - } - /** - * .google.protobuf.FloatValue float_Opt = 9; - */ - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.FloatValue, com.google.protobuf.FloatValue.Builder, com.google.protobuf.FloatValueOrBuilder> - getFloatOptFieldBuilder() { - if (floatOptBuilder_ == null) { - floatOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.FloatValue, com.google.protobuf.FloatValue.Builder, com.google.protobuf.FloatValueOrBuilder>( - getFloatOpt(), - getParentForChildren(), - isClean()); - floatOpt_ = null; - } - return floatOptBuilder_; - } - - private com.google.protobuf.DoubleValue doubleOpt_; - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.DoubleValue, com.google.protobuf.DoubleValue.Builder, com.google.protobuf.DoubleValueOrBuilder> doubleOptBuilder_; - /** - * .google.protobuf.DoubleValue double_opt = 10; - * @return Whether the doubleOpt field is set. - */ - public boolean hasDoubleOpt() { - return doubleOptBuilder_ != null || doubleOpt_ != null; - } - /** - * .google.protobuf.DoubleValue double_opt = 10; - * @return The doubleOpt. - */ - public com.google.protobuf.DoubleValue getDoubleOpt() { - if (doubleOptBuilder_ == null) { - return doubleOpt_ == null ? com.google.protobuf.DoubleValue.getDefaultInstance() : doubleOpt_; - } else { - return doubleOptBuilder_.getMessage(); - } - } - /** - * .google.protobuf.DoubleValue double_opt = 10; - */ - public Builder setDoubleOpt(com.google.protobuf.DoubleValue value) { - if (doubleOptBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - doubleOpt_ = value; - onChanged(); - } else { - doubleOptBuilder_.setMessage(value); - } - - return this; - } - /** - * .google.protobuf.DoubleValue double_opt = 10; - */ - public Builder setDoubleOpt( - com.google.protobuf.DoubleValue.Builder builderForValue) { - if (doubleOptBuilder_ == null) { - doubleOpt_ = builderForValue.build(); - onChanged(); - } else { - doubleOptBuilder_.setMessage(builderForValue.build()); - } - - return this; - } - /** - * .google.protobuf.DoubleValue double_opt = 10; - */ - public Builder mergeDoubleOpt(com.google.protobuf.DoubleValue value) { - if (doubleOptBuilder_ == null) { - if (doubleOpt_ != null) { - doubleOpt_ = - com.google.protobuf.DoubleValue.newBuilder(doubleOpt_).mergeFrom(value).buildPartial(); - } else { - doubleOpt_ = value; - } - onChanged(); - } else { - doubleOptBuilder_.mergeFrom(value); - } - - return this; - } - /** - * .google.protobuf.DoubleValue double_opt = 10; - */ - public Builder clearDoubleOpt() { - if (doubleOptBuilder_ == null) { - doubleOpt_ = null; - onChanged(); - } else { - doubleOpt_ = null; - doubleOptBuilder_ = null; - } - - return this; - } - /** - * .google.protobuf.DoubleValue double_opt = 10; - */ - public com.google.protobuf.DoubleValue.Builder getDoubleOptBuilder() { - - onChanged(); - return getDoubleOptFieldBuilder().getBuilder(); - } - /** - * .google.protobuf.DoubleValue double_opt = 10; - */ - public com.google.protobuf.DoubleValueOrBuilder getDoubleOptOrBuilder() { - if (doubleOptBuilder_ != null) { - return doubleOptBuilder_.getMessageOrBuilder(); - } else { - return doubleOpt_ == null ? - com.google.protobuf.DoubleValue.getDefaultInstance() : doubleOpt_; - } - } - /** - * .google.protobuf.DoubleValue double_opt = 10; - */ - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.DoubleValue, com.google.protobuf.DoubleValue.Builder, com.google.protobuf.DoubleValueOrBuilder> - getDoubleOptFieldBuilder() { - if (doubleOptBuilder_ == null) { - doubleOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.DoubleValue, com.google.protobuf.DoubleValue.Builder, com.google.protobuf.DoubleValueOrBuilder>( - getDoubleOpt(), - getParentForChildren(), - isClean()); - doubleOpt_ = null; - } - return doubleOptBuilder_; - } - - private com.google.protobuf.BoolValue boolOpt_; - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.BoolValue, com.google.protobuf.BoolValue.Builder, com.google.protobuf.BoolValueOrBuilder> boolOptBuilder_; - /** - * .google.protobuf.BoolValue bool_opt = 11; - * @return Whether the boolOpt field is set. - */ - public boolean hasBoolOpt() { - return boolOptBuilder_ != null || boolOpt_ != null; - } - /** - * .google.protobuf.BoolValue bool_opt = 11; - * @return The boolOpt. - */ - public com.google.protobuf.BoolValue getBoolOpt() { - if (boolOptBuilder_ == null) { - return boolOpt_ == null ? com.google.protobuf.BoolValue.getDefaultInstance() : boolOpt_; - } else { - return boolOptBuilder_.getMessage(); - } - } - /** - * .google.protobuf.BoolValue bool_opt = 11; - */ - public Builder setBoolOpt(com.google.protobuf.BoolValue value) { - if (boolOptBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - boolOpt_ = value; - onChanged(); - } else { - boolOptBuilder_.setMessage(value); - } - - return this; - } - /** - * .google.protobuf.BoolValue bool_opt = 11; - */ - public Builder setBoolOpt( - com.google.protobuf.BoolValue.Builder builderForValue) { - if (boolOptBuilder_ == null) { - boolOpt_ = builderForValue.build(); - onChanged(); - } else { - boolOptBuilder_.setMessage(builderForValue.build()); - } - - return this; - } - /** - * .google.protobuf.BoolValue bool_opt = 11; - */ - public Builder mergeBoolOpt(com.google.protobuf.BoolValue value) { - if (boolOptBuilder_ == null) { - if (boolOpt_ != null) { - boolOpt_ = - com.google.protobuf.BoolValue.newBuilder(boolOpt_).mergeFrom(value).buildPartial(); - } else { - boolOpt_ = value; - } - onChanged(); - } else { - boolOptBuilder_.mergeFrom(value); - } - - return this; - } - /** - * .google.protobuf.BoolValue bool_opt = 11; - */ - public Builder clearBoolOpt() { - if (boolOptBuilder_ == null) { - boolOpt_ = null; - onChanged(); - } else { - boolOpt_ = null; - boolOptBuilder_ = null; - } - - return this; - } - /** - * .google.protobuf.BoolValue bool_opt = 11; - */ - public com.google.protobuf.BoolValue.Builder getBoolOptBuilder() { - - onChanged(); - return getBoolOptFieldBuilder().getBuilder(); - } - /** - * .google.protobuf.BoolValue bool_opt = 11; - */ - public com.google.protobuf.BoolValueOrBuilder getBoolOptOrBuilder() { - if (boolOptBuilder_ != null) { - return boolOptBuilder_.getMessageOrBuilder(); - } else { - return boolOpt_ == null ? - com.google.protobuf.BoolValue.getDefaultInstance() : boolOpt_; - } - } - /** - * .google.protobuf.BoolValue bool_opt = 11; - */ - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.BoolValue, com.google.protobuf.BoolValue.Builder, com.google.protobuf.BoolValueOrBuilder> - getBoolOptFieldBuilder() { - if (boolOptBuilder_ == null) { - boolOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.BoolValue, com.google.protobuf.BoolValue.Builder, com.google.protobuf.BoolValueOrBuilder>( - getBoolOpt(), - getParentForChildren(), - isClean()); - boolOpt_ = null; - } - return boolOptBuilder_; - } - - private com.google.protobuf.StringValue stringOpt_; - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.StringValue, com.google.protobuf.StringValue.Builder, com.google.protobuf.StringValueOrBuilder> stringOptBuilder_; - /** - * .google.protobuf.StringValue string_opt = 12; - * @return Whether the stringOpt field is set. - */ - public boolean hasStringOpt() { - return stringOptBuilder_ != null || stringOpt_ != null; - } - /** - * .google.protobuf.StringValue string_opt = 12; - * @return The stringOpt. - */ - public com.google.protobuf.StringValue getStringOpt() { - if (stringOptBuilder_ == null) { - return stringOpt_ == null ? com.google.protobuf.StringValue.getDefaultInstance() : stringOpt_; - } else { - return stringOptBuilder_.getMessage(); - } - } - /** - * .google.protobuf.StringValue string_opt = 12; - */ - public Builder setStringOpt(com.google.protobuf.StringValue value) { - if (stringOptBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - stringOpt_ = value; - onChanged(); - } else { - stringOptBuilder_.setMessage(value); - } - - return this; - } - /** - * .google.protobuf.StringValue string_opt = 12; - */ - public Builder setStringOpt( - com.google.protobuf.StringValue.Builder builderForValue) { - if (stringOptBuilder_ == null) { - stringOpt_ = builderForValue.build(); - onChanged(); - } else { - stringOptBuilder_.setMessage(builderForValue.build()); - } - - return this; - } - /** - * .google.protobuf.StringValue string_opt = 12; - */ - public Builder mergeStringOpt(com.google.protobuf.StringValue value) { - if (stringOptBuilder_ == null) { - if (stringOpt_ != null) { - stringOpt_ = - com.google.protobuf.StringValue.newBuilder(stringOpt_).mergeFrom(value).buildPartial(); - } else { - stringOpt_ = value; - } - onChanged(); - } else { - stringOptBuilder_.mergeFrom(value); - } - - return this; - } - /** - * .google.protobuf.StringValue string_opt = 12; - */ - public Builder clearStringOpt() { - if (stringOptBuilder_ == null) { - stringOpt_ = null; - onChanged(); - } else { - stringOpt_ = null; - stringOptBuilder_ = null; - } - - return this; - } - /** - * .google.protobuf.StringValue string_opt = 12; - */ - public com.google.protobuf.StringValue.Builder getStringOptBuilder() { - - onChanged(); - return getStringOptFieldBuilder().getBuilder(); - } - /** - * .google.protobuf.StringValue string_opt = 12; - */ - public com.google.protobuf.StringValueOrBuilder getStringOptOrBuilder() { - if (stringOptBuilder_ != null) { - return stringOptBuilder_.getMessageOrBuilder(); - } else { - return stringOpt_ == null ? - com.google.protobuf.StringValue.getDefaultInstance() : stringOpt_; - } - } - /** - * .google.protobuf.StringValue string_opt = 12; - */ - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.StringValue, com.google.protobuf.StringValue.Builder, com.google.protobuf.StringValueOrBuilder> - getStringOptFieldBuilder() { - if (stringOptBuilder_ == null) { - stringOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.StringValue, com.google.protobuf.StringValue.Builder, com.google.protobuf.StringValueOrBuilder>( - getStringOpt(), - getParentForChildren(), - isClean()); - stringOpt_ = null; - } - return stringOptBuilder_; - } - - private com.google.protobuf.Timestamp time_; - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> timeBuilder_; - /** - * .google.protobuf.Timestamp time = 13; - * @return Whether the time field is set. - */ - public boolean hasTime() { - return timeBuilder_ != null || time_ != null; - } - /** - * .google.protobuf.Timestamp time = 13; - * @return The time. - */ - public com.google.protobuf.Timestamp getTime() { - if (timeBuilder_ == null) { - return time_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : time_; - } else { - return timeBuilder_.getMessage(); - } - } - /** - * .google.protobuf.Timestamp time = 13; - */ - public Builder setTime(com.google.protobuf.Timestamp value) { - if (timeBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - time_ = value; - onChanged(); - } else { - timeBuilder_.setMessage(value); - } - - return this; - } - /** - * .google.protobuf.Timestamp time = 13; - */ - public Builder setTime( - com.google.protobuf.Timestamp.Builder builderForValue) { - if (timeBuilder_ == null) { - time_ = builderForValue.build(); - onChanged(); - } else { - timeBuilder_.setMessage(builderForValue.build()); - } - - return this; - } - /** - * .google.protobuf.Timestamp time = 13; - */ - public Builder mergeTime(com.google.protobuf.Timestamp value) { - if (timeBuilder_ == null) { - if (time_ != null) { - time_ = - com.google.protobuf.Timestamp.newBuilder(time_).mergeFrom(value).buildPartial(); - } else { - time_ = value; - } - onChanged(); - } else { - timeBuilder_.mergeFrom(value); - } - - return this; - } - /** - * .google.protobuf.Timestamp time = 13; - */ - public Builder clearTime() { - if (timeBuilder_ == null) { - time_ = null; - onChanged(); - } else { - time_ = null; - timeBuilder_ = null; - } - - return this; - } - /** - * .google.protobuf.Timestamp time = 13; - */ - public com.google.protobuf.Timestamp.Builder getTimeBuilder() { - - onChanged(); - return getTimeFieldBuilder().getBuilder(); - } - /** - * .google.protobuf.Timestamp time = 13; - */ - public com.google.protobuf.TimestampOrBuilder getTimeOrBuilder() { - if (timeBuilder_ != null) { - return timeBuilder_.getMessageOrBuilder(); - } else { - return time_ == null ? - com.google.protobuf.Timestamp.getDefaultInstance() : time_; - } - } - /** - * .google.protobuf.Timestamp time = 13; - */ - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> - getTimeFieldBuilder() { - if (timeBuilder_ == null) { - timeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( - getTime(), - getParentForChildren(), - isClean()); - time_ = null; - } - return timeBuilder_; - } - - private com.google.protobuf.Timestamp timeOpt_; - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> timeOptBuilder_; - /** - * .google.protobuf.Timestamp time_opt = 14; - * @return Whether the timeOpt field is set. - */ - public boolean hasTimeOpt() { - return timeOptBuilder_ != null || timeOpt_ != null; - } - /** - * .google.protobuf.Timestamp time_opt = 14; - * @return The timeOpt. - */ - public com.google.protobuf.Timestamp getTimeOpt() { - if (timeOptBuilder_ == null) { - return timeOpt_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : timeOpt_; - } else { - return timeOptBuilder_.getMessage(); - } - } - /** - * .google.protobuf.Timestamp time_opt = 14; - */ - public Builder setTimeOpt(com.google.protobuf.Timestamp value) { - if (timeOptBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - timeOpt_ = value; - onChanged(); - } else { - timeOptBuilder_.setMessage(value); - } - - return this; - } - /** - * .google.protobuf.Timestamp time_opt = 14; - */ - public Builder setTimeOpt( - com.google.protobuf.Timestamp.Builder builderForValue) { - if (timeOptBuilder_ == null) { - timeOpt_ = builderForValue.build(); - onChanged(); - } else { - timeOptBuilder_.setMessage(builderForValue.build()); - } - - return this; - } - /** - * .google.protobuf.Timestamp time_opt = 14; - */ - public Builder mergeTimeOpt(com.google.protobuf.Timestamp value) { - if (timeOptBuilder_ == null) { - if (timeOpt_ != null) { - timeOpt_ = - com.google.protobuf.Timestamp.newBuilder(timeOpt_).mergeFrom(value).buildPartial(); - } else { - timeOpt_ = value; - } - onChanged(); - } else { - timeOptBuilder_.mergeFrom(value); - } - - return this; - } - /** - * .google.protobuf.Timestamp time_opt = 14; - */ - public Builder clearTimeOpt() { - if (timeOptBuilder_ == null) { - timeOpt_ = null; - onChanged(); - } else { - timeOpt_ = null; - timeOptBuilder_ = null; - } - - return this; - } - /** - * .google.protobuf.Timestamp time_opt = 14; - */ - public com.google.protobuf.Timestamp.Builder getTimeOptBuilder() { - - onChanged(); - return getTimeOptFieldBuilder().getBuilder(); - } - /** - * .google.protobuf.Timestamp time_opt = 14; - */ - public com.google.protobuf.TimestampOrBuilder getTimeOptOrBuilder() { - if (timeOptBuilder_ != null) { - return timeOptBuilder_.getMessageOrBuilder(); - } else { - return timeOpt_ == null ? - com.google.protobuf.Timestamp.getDefaultInstance() : timeOpt_; - } - } - /** - * .google.protobuf.Timestamp time_opt = 14; - */ - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> - getTimeOptFieldBuilder() { - if (timeOptBuilder_ == null) { - timeOptBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( - getTimeOpt(), - getParentForChildren(), - isClean()); - timeOpt_ = null; - } - return timeOptBuilder_; - } - - private com.google.protobuf.Internal.IntList intArray_ = emptyIntList(); - private void ensureIntArrayIsMutable() { - if (!((bitField0_ & 0x00000001) != 0)) { - intArray_ = mutableCopy(intArray_); - bitField0_ |= 0x00000001; - } - } - /** - * repeated int32 int_array = 15; - * @return A list containing the intArray. - */ - public java.util.List - getIntArrayList() { - return ((bitField0_ & 0x00000001) != 0) ? - java.util.Collections.unmodifiableList(intArray_) : intArray_; - } - /** - * repeated int32 int_array = 15; - * @return The count of intArray. - */ - public int getIntArrayCount() { - return intArray_.size(); - } - /** - * repeated int32 int_array = 15; - * @param index The index of the element to return. - * @return The intArray at the given index. - */ - public int getIntArray(int index) { - return intArray_.getInt(index); - } - /** - * repeated int32 int_array = 15; - * @param index The index to set the value at. - * @param value The intArray to set. - * @return This builder for chaining. - */ - public Builder setIntArray( - int index, int value) { - ensureIntArrayIsMutable(); - intArray_.setInt(index, value); - onChanged(); - return this; - } - /** - * repeated int32 int_array = 15; - * @param value The intArray to add. - * @return This builder for chaining. - */ - public Builder addIntArray(int value) { - ensureIntArrayIsMutable(); - intArray_.addInt(value); - onChanged(); - return this; - } - /** - * repeated int32 int_array = 15; - * @param values The intArray to add. - * @return This builder for chaining. - */ - public Builder addAllIntArray( - Iterable values) { - ensureIntArrayIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll( - values, intArray_); - onChanged(); - return this; - } - /** - * repeated int32 int_array = 15; - * @return This builder for chaining. - */ - public Builder clearIntArray() { - intArray_ = emptyIntList(); - bitField0_ = (bitField0_ & ~0x00000001); - onChanged(); - return this; - } - - private com.google.protobuf.LazyStringList stringArray_ = com.google.protobuf.LazyStringArrayList.EMPTY; - private void ensureStringArrayIsMutable() { - if (!((bitField0_ & 0x00000002) != 0)) { - stringArray_ = new com.google.protobuf.LazyStringArrayList(stringArray_); - bitField0_ |= 0x00000002; - } - } - /** - * repeated string string_array = 16; - * @return A list containing the stringArray. - */ - public com.google.protobuf.ProtocolStringList - getStringArrayList() { - return stringArray_.getUnmodifiableView(); - } - /** - * repeated string string_array = 16; - * @return The count of stringArray. - */ - public int getStringArrayCount() { - return stringArray_.size(); - } - /** - * repeated string string_array = 16; - * @param index The index of the element to return. - * @return The stringArray at the given index. - */ - public String getStringArray(int index) { - return stringArray_.get(index); - } - /** - * repeated string string_array = 16; - * @param index The index of the value to return. - * @return The bytes of the stringArray at the given index. - */ - public com.google.protobuf.ByteString - getStringArrayBytes(int index) { - return stringArray_.getByteString(index); - } - /** - * repeated string string_array = 16; - * @param index The index to set the value at. - * @param value The stringArray to set. - * @return This builder for chaining. - */ - public Builder setStringArray( - int index, String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureStringArrayIsMutable(); - stringArray_.set(index, value); - onChanged(); - return this; - } - /** - * repeated string string_array = 16; - * @param value The stringArray to add. - * @return This builder for chaining. - */ - public Builder addStringArray( - String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureStringArrayIsMutable(); - stringArray_.add(value); - onChanged(); - return this; - } - /** - * repeated string string_array = 16; - * @param values The stringArray to add. - * @return This builder for chaining. - */ - public Builder addAllStringArray( - Iterable values) { - ensureStringArrayIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll( - values, stringArray_); - onChanged(); - return this; - } - /** - * repeated string string_array = 16; - * @return This builder for chaining. - */ - public Builder clearStringArray() { - stringArray_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000002); - onChanged(); - return this; - } - /** - * repeated string string_array = 16; - * @param value The bytes of the stringArray to add. - * @return This builder for chaining. - */ - public Builder addStringArrayBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - ensureStringArrayIsMutable(); - stringArray_.add(value); - onChanged(); - return this; - } - - private java.util.List personArray_ = - java.util.Collections.emptyList(); - private void ensurePersonArrayIsMutable() { - if (!((bitField0_ & 0x00000004) != 0)) { - personArray_ = new java.util.ArrayList(personArray_); - bitField0_ |= 0x00000004; - } - } - - private com.google.protobuf.RepeatedFieldBuilderV3< - PBPerson, PBPerson.Builder, PBPersonOrBuilder> personArrayBuilder_; - - /** - * repeated .PBPerson person_array = 17; - */ - public java.util.List getPersonArrayList() { - if (personArrayBuilder_ == null) { - return java.util.Collections.unmodifiableList(personArray_); - } else { - return personArrayBuilder_.getMessageList(); - } - } - /** - * repeated .PBPerson person_array = 17; - */ - public int getPersonArrayCount() { - if (personArrayBuilder_ == null) { - return personArray_.size(); - } else { - return personArrayBuilder_.getCount(); - } - } - /** - * repeated .PBPerson person_array = 17; - */ - public PBPerson getPersonArray(int index) { - if (personArrayBuilder_ == null) { - return personArray_.get(index); - } else { - return personArrayBuilder_.getMessage(index); - } - } - /** - * repeated .PBPerson person_array = 17; - */ - public Builder setPersonArray( - int index, PBPerson value) { - if (personArrayBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensurePersonArrayIsMutable(); - personArray_.set(index, value); - onChanged(); - } else { - personArrayBuilder_.setMessage(index, value); - } - return this; - } - /** - * repeated .PBPerson person_array = 17; - */ - public Builder setPersonArray( - int index, PBPerson.Builder builderForValue) { - if (personArrayBuilder_ == null) { - ensurePersonArrayIsMutable(); - personArray_.set(index, builderForValue.build()); - onChanged(); - } else { - personArrayBuilder_.setMessage(index, builderForValue.build()); - } - return this; - } - /** - * repeated .PBPerson person_array = 17; - */ - public Builder addPersonArray(PBPerson value) { - if (personArrayBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensurePersonArrayIsMutable(); - personArray_.add(value); - onChanged(); - } else { - personArrayBuilder_.addMessage(value); - } - return this; - } - /** - * repeated .PBPerson person_array = 17; - */ - public Builder addPersonArray( - int index, PBPerson value) { - if (personArrayBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensurePersonArrayIsMutable(); - personArray_.add(index, value); - onChanged(); - } else { - personArrayBuilder_.addMessage(index, value); - } - return this; - } - /** - * repeated .PBPerson person_array = 17; - */ - public Builder addPersonArray( - PBPerson.Builder builderForValue) { - if (personArrayBuilder_ == null) { - ensurePersonArrayIsMutable(); - personArray_.add(builderForValue.build()); - onChanged(); - } else { - personArrayBuilder_.addMessage(builderForValue.build()); - } - return this; - } - /** - * repeated .PBPerson person_array = 17; - */ - public Builder addPersonArray( - int index, PBPerson.Builder builderForValue) { - if (personArrayBuilder_ == null) { - ensurePersonArrayIsMutable(); - personArray_.add(index, builderForValue.build()); - onChanged(); - } else { - personArrayBuilder_.addMessage(index, builderForValue.build()); - } - return this; - } - /** - * repeated .PBPerson person_array = 17; - */ - public Builder addAllPersonArray( - Iterable values) { - if (personArrayBuilder_ == null) { - ensurePersonArrayIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll( - values, personArray_); - onChanged(); - } else { - personArrayBuilder_.addAllMessages(values); - } - return this; - } - /** - * repeated .PBPerson person_array = 17; - */ - public Builder clearPersonArray() { - if (personArrayBuilder_ == null) { - personArray_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000004); - onChanged(); - } else { - personArrayBuilder_.clear(); - } - return this; - } - /** - * repeated .PBPerson person_array = 17; - */ - public Builder removePersonArray(int index) { - if (personArrayBuilder_ == null) { - ensurePersonArrayIsMutable(); - personArray_.remove(index); - onChanged(); - } else { - personArrayBuilder_.remove(index); - } - return this; - } - /** - * repeated .PBPerson person_array = 17; - */ - public PBPerson.Builder getPersonArrayBuilder( - int index) { - return getPersonArrayFieldBuilder().getBuilder(index); - } - /** - * repeated .PBPerson person_array = 17; - */ - public PBPersonOrBuilder getPersonArrayOrBuilder( - int index) { - if (personArrayBuilder_ == null) { - return personArray_.get(index); } else { - return personArrayBuilder_.getMessageOrBuilder(index); - } - } - /** - * repeated .PBPerson person_array = 17; - */ - public java.util.List - getPersonArrayOrBuilderList() { - if (personArrayBuilder_ != null) { - return personArrayBuilder_.getMessageOrBuilderList(); - } else { - return java.util.Collections.unmodifiableList(personArray_); - } - } - /** - * repeated .PBPerson person_array = 17; - */ - public PBPerson.Builder addPersonArrayBuilder() { - return getPersonArrayFieldBuilder().addBuilder( - PBPerson.getDefaultInstance()); - } - /** - * repeated .PBPerson person_array = 17; - */ - public PBPerson.Builder addPersonArrayBuilder( - int index) { - return getPersonArrayFieldBuilder().addBuilder( - index, PBPerson.getDefaultInstance()); - } - /** - * repeated .PBPerson person_array = 17; - */ - public java.util.List - getPersonArrayBuilderList() { - return getPersonArrayFieldBuilder().getBuilderList(); - } - private com.google.protobuf.RepeatedFieldBuilderV3< - PBPerson, PBPerson.Builder, PBPersonOrBuilder> - getPersonArrayFieldBuilder() { - if (personArrayBuilder_ == null) { - personArrayBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< - PBPerson, PBPerson.Builder, PBPersonOrBuilder>( - personArray_, - ((bitField0_ & 0x00000004) != 0), - getParentForChildren(), - isClean()); - personArray_ = null; - } - return personArrayBuilder_; - } - - private com.google.protobuf.Internal.DoubleList seq_ = emptyDoubleList(); - private void ensureSeqIsMutable() { - if (!((bitField0_ & 0x00000008) != 0)) { - seq_ = mutableCopy(seq_); - bitField0_ |= 0x00000008; - } - } - /** - * repeated double seq = 18; - * @return A list containing the seq. - */ - public java.util.List - getSeqList() { - return ((bitField0_ & 0x00000008) != 0) ? - java.util.Collections.unmodifiableList(seq_) : seq_; - } - /** - * repeated double seq = 18; - * @return The count of seq. - */ - public int getSeqCount() { - return seq_.size(); - } - /** - * repeated double seq = 18; - * @param index The index of the element to return. - * @return The seq at the given index. - */ - public double getSeq(int index) { - return seq_.getDouble(index); - } - /** - * repeated double seq = 18; - * @param index The index to set the value at. - * @param value The seq to set. - * @return This builder for chaining. - */ - public Builder setSeq( - int index, double value) { - ensureSeqIsMutable(); - seq_.setDouble(index, value); - onChanged(); - return this; - } - /** - * repeated double seq = 18; - * @param value The seq to add. - * @return This builder for chaining. - */ - public Builder addSeq(double value) { - ensureSeqIsMutable(); - seq_.addDouble(value); - onChanged(); - return this; - } - /** - * repeated double seq = 18; - * @param values The seq to add. - * @return This builder for chaining. - */ - public Builder addAllSeq( - Iterable values) { - ensureSeqIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll( - values, seq_); - onChanged(); - return this; - } - /** - * repeated double seq = 18; - * @return This builder for chaining. - */ - public Builder clearSeq() { - seq_ = emptyDoubleList(); - bitField0_ = (bitField0_ & ~0x00000008); - onChanged(); - return this; - } - - private com.google.protobuf.MapField< - String, String> stringStringKV_; - private com.google.protobuf.MapField - internalGetStringStringKV() { - if (stringStringKV_ == null) { - return com.google.protobuf.MapField.emptyMapField( - StringStringKVDefaultEntryHolder.defaultEntry); - } - return stringStringKV_; - } - private com.google.protobuf.MapField - internalGetMutableStringStringKV() { - onChanged();; - if (stringStringKV_ == null) { - stringStringKV_ = com.google.protobuf.MapField.newMapField( - StringStringKVDefaultEntryHolder.defaultEntry); - } - if (!stringStringKV_.isMutable()) { - stringStringKV_ = stringStringKV_.copy(); - } - return stringStringKV_; - } - - public int getStringStringKVCount() { - return internalGetStringStringKV().getMap().size(); - } - /** - * map<string, string> string_string_k_v = 19; - */ - - @Override - public boolean containsStringStringKV( - String key) { - if (key == null) { throw new NullPointerException(); } - return internalGetStringStringKV().getMap().containsKey(key); - } - /** - * Use {@link #getStringStringKVMap()} instead. - */ - @Override - @Deprecated - public java.util.Map getStringStringKV() { - return getStringStringKVMap(); - } - /** - * map<string, string> string_string_k_v = 19; - */ - @Override - - public java.util.Map getStringStringKVMap() { - return internalGetStringStringKV().getMap(); - } - /** - * map<string, string> string_string_k_v = 19; - */ - @Override - - public String getStringStringKVOrDefault( - String key, - String defaultValue) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetStringStringKV().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<string, string> string_string_k_v = 19; - */ - @Override - - public String getStringStringKVOrThrow( - String key) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetStringStringKV().getMap(); - if (!map.containsKey(key)) { - throw new IllegalArgumentException(); - } - return map.get(key); - } - - public Builder clearStringStringKV() { - internalGetMutableStringStringKV().getMutableMap() - .clear(); - return this; - } - /** - * map<string, string> string_string_k_v = 19; - */ - - public Builder removeStringStringKV( - String key) { - if (key == null) { throw new NullPointerException(); } - internalGetMutableStringStringKV().getMutableMap() - .remove(key); - return this; - } - /** - * Use alternate mutation accessors instead. - */ - @Deprecated - public java.util.Map - getMutableStringStringKV() { - return internalGetMutableStringStringKV().getMutableMap(); - } - /** - * map<string, string> string_string_k_v = 19; - */ - public Builder putStringStringKV( - String key, - String value) { - if (key == null) { throw new NullPointerException(); } - if (value == null) { throw new NullPointerException(); } - internalGetMutableStringStringKV().getMutableMap() - .put(key, value); - return this; - } - /** - * map<string, string> string_string_k_v = 19; - */ - - public Builder putAllStringStringKV( - java.util.Map values) { - internalGetMutableStringStringKV().getMutableMap() - .putAll(values); - return this; - } - - private com.google.protobuf.MapField< - Long, String> longStringKV_; - private com.google.protobuf.MapField - internalGetLongStringKV() { - if (longStringKV_ == null) { - return com.google.protobuf.MapField.emptyMapField( - LongStringKVDefaultEntryHolder.defaultEntry); - } - return longStringKV_; - } - private com.google.protobuf.MapField - internalGetMutableLongStringKV() { - onChanged();; - if (longStringKV_ == null) { - longStringKV_ = com.google.protobuf.MapField.newMapField( - LongStringKVDefaultEntryHolder.defaultEntry); - } - if (!longStringKV_.isMutable()) { - longStringKV_ = longStringKV_.copy(); - } - return longStringKV_; - } - - public int getLongStringKVCount() { - return internalGetLongStringKV().getMap().size(); - } - /** - * map<int64, string> long_string_k_v = 20; - */ - - @Override - public boolean containsLongStringKV( - long key) { - - return internalGetLongStringKV().getMap().containsKey(key); - } - /** - * Use {@link #getLongStringKVMap()} instead. - */ - @Override - @Deprecated - public java.util.Map getLongStringKV() { - return getLongStringKVMap(); - } - /** - * map<int64, string> long_string_k_v = 20; - */ - @Override - - public java.util.Map getLongStringKVMap() { - return internalGetLongStringKV().getMap(); - } - /** - * map<int64, string> long_string_k_v = 20; - */ - @Override - - public String getLongStringKVOrDefault( - long key, - String defaultValue) { - - java.util.Map map = - internalGetLongStringKV().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<int64, string> long_string_k_v = 20; - */ - @Override - - public String getLongStringKVOrThrow( - long key) { - - java.util.Map map = - internalGetLongStringKV().getMap(); - if (!map.containsKey(key)) { - throw new IllegalArgumentException(); - } - return map.get(key); - } - - public Builder clearLongStringKV() { - internalGetMutableLongStringKV().getMutableMap() - .clear(); - return this; - } - /** - * map<int64, string> long_string_k_v = 20; - */ - - public Builder removeLongStringKV( - long key) { - - internalGetMutableLongStringKV().getMutableMap() - .remove(key); - return this; - } - /** - * Use alternate mutation accessors instead. - */ - @Deprecated - public java.util.Map - getMutableLongStringKV() { - return internalGetMutableLongStringKV().getMutableMap(); - } - /** - * map<int64, string> long_string_k_v = 20; - */ - public Builder putLongStringKV( - long key, - String value) { - - if (value == null) { throw new NullPointerException(); } - internalGetMutableLongStringKV().getMutableMap() - .put(key, value); - return this; - } - /** - * map<int64, string> long_string_k_v = 20; - */ - - public Builder putAllLongStringKV( - java.util.Map values) { - internalGetMutableLongStringKV().getMutableMap() - .putAll(values); - return this; - } - - private com.google.protobuf.MapField< - String, Integer> stringIntKV_; - private com.google.protobuf.MapField - internalGetStringIntKV() { - if (stringIntKV_ == null) { - return com.google.protobuf.MapField.emptyMapField( - StringIntKVDefaultEntryHolder.defaultEntry); - } - return stringIntKV_; - } - private com.google.protobuf.MapField - internalGetMutableStringIntKV() { - onChanged();; - if (stringIntKV_ == null) { - stringIntKV_ = com.google.protobuf.MapField.newMapField( - StringIntKVDefaultEntryHolder.defaultEntry); - } - if (!stringIntKV_.isMutable()) { - stringIntKV_ = stringIntKV_.copy(); - } - return stringIntKV_; - } - - public int getStringIntKVCount() { - return internalGetStringIntKV().getMap().size(); - } - /** - * map<string, int32> string_int_k_v = 21; - */ - - @Override - public boolean containsStringIntKV( - String key) { - if (key == null) { throw new NullPointerException(); } - return internalGetStringIntKV().getMap().containsKey(key); - } - /** - * Use {@link #getStringIntKVMap()} instead. - */ - @Override - @Deprecated - public java.util.Map getStringIntKV() { - return getStringIntKVMap(); - } - /** - * map<string, int32> string_int_k_v = 21; - */ - @Override - - public java.util.Map getStringIntKVMap() { - return internalGetStringIntKV().getMap(); - } - /** - * map<string, int32> string_int_k_v = 21; - */ - @Override - - public int getStringIntKVOrDefault( - String key, - int defaultValue) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetStringIntKV().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<string, int32> string_int_k_v = 21; - */ - @Override - - public int getStringIntKVOrThrow( - String key) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetStringIntKV().getMap(); - if (!map.containsKey(key)) { - throw new IllegalArgumentException(); - } - return map.get(key); - } - - public Builder clearStringIntKV() { - internalGetMutableStringIntKV().getMutableMap() - .clear(); - return this; - } - /** - * map<string, int32> string_int_k_v = 21; - */ - - public Builder removeStringIntKV( - String key) { - if (key == null) { throw new NullPointerException(); } - internalGetMutableStringIntKV().getMutableMap() - .remove(key); - return this; - } - /** - * Use alternate mutation accessors instead. - */ - @Deprecated - public java.util.Map - getMutableStringIntKV() { - return internalGetMutableStringIntKV().getMutableMap(); - } - /** - * map<string, int32> string_int_k_v = 21; - */ - public Builder putStringIntKV( - String key, - int value) { - if (key == null) { throw new NullPointerException(); } - - internalGetMutableStringIntKV().getMutableMap() - .put(key, value); - return this; - } - /** - * map<string, int32> string_int_k_v = 21; - */ - - public Builder putAllStringIntKV( - java.util.Map values) { - internalGetMutableStringIntKV().getMutableMap() - .putAll(values); - return this; - } - - private com.google.protobuf.MapField< - Long, Integer> longIntKV_; - private com.google.protobuf.MapField - internalGetLongIntKV() { - if (longIntKV_ == null) { - return com.google.protobuf.MapField.emptyMapField( - LongIntKVDefaultEntryHolder.defaultEntry); - } - return longIntKV_; - } - private com.google.protobuf.MapField - internalGetMutableLongIntKV() { - onChanged();; - if (longIntKV_ == null) { - longIntKV_ = com.google.protobuf.MapField.newMapField( - LongIntKVDefaultEntryHolder.defaultEntry); - } - if (!longIntKV_.isMutable()) { - longIntKV_ = longIntKV_.copy(); - } - return longIntKV_; - } - - public int getLongIntKVCount() { - return internalGetLongIntKV().getMap().size(); - } - /** - * map<int64, int32> long_int_k_v = 22; - */ - - @Override - public boolean containsLongIntKV( - long key) { - - return internalGetLongIntKV().getMap().containsKey(key); - } - /** - * Use {@link #getLongIntKVMap()} instead. - */ - @Override - @Deprecated - public java.util.Map getLongIntKV() { - return getLongIntKVMap(); - } - /** - * map<int64, int32> long_int_k_v = 22; - */ - @Override - - public java.util.Map getLongIntKVMap() { - return internalGetLongIntKV().getMap(); - } - /** - * map<int64, int32> long_int_k_v = 22; - */ - @Override - - public int getLongIntKVOrDefault( - long key, - int defaultValue) { - - java.util.Map map = - internalGetLongIntKV().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<int64, int32> long_int_k_v = 22; - */ - @Override - - public int getLongIntKVOrThrow( - long key) { - - java.util.Map map = - internalGetLongIntKV().getMap(); - if (!map.containsKey(key)) { - throw new IllegalArgumentException(); - } - return map.get(key); - } - - public Builder clearLongIntKV() { - internalGetMutableLongIntKV().getMutableMap() - .clear(); - return this; - } - /** - * map<int64, int32> long_int_k_v = 22; - */ - - public Builder removeLongIntKV( - long key) { - - internalGetMutableLongIntKV().getMutableMap() - .remove(key); - return this; - } - /** - * Use alternate mutation accessors instead. - */ - @Deprecated - public java.util.Map - getMutableLongIntKV() { - return internalGetMutableLongIntKV().getMutableMap(); - } - /** - * map<int64, int32> long_int_k_v = 22; - */ - public Builder putLongIntKV( - long key, - int value) { - - - internalGetMutableLongIntKV().getMutableMap() - .put(key, value); - return this; - } - /** - * map<int64, int32> long_int_k_v = 22; - */ - - public Builder putAllLongIntKV( - java.util.Map values) { - internalGetMutableLongIntKV().getMutableMap() - .putAll(values); - return this; - } - @Override - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFields(unknownFields); - } - - @Override - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - - // @@protoc_insertion_point(builder_scope:PBTestMessage) - } - - // @@protoc_insertion_point(class_scope:PBTestMessage) - private static final PBTestMessage DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new PBTestMessage(); - } - - public static PBTestMessage getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { - @Override - public PBTestMessage parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new PBTestMessage(input, extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - @Override - public PBTestMessage getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - - } - - public interface PBPersonOrBuilder extends - // @@protoc_insertion_point(interface_extends:PBPerson) - com.google.protobuf.MessageOrBuilder { - - /** - * int64 id = 1; - * @return The id. - */ - long getId(); - - /** - * string name = 2; - * @return The name. - */ - String getName(); - /** - * string name = 2; - * @return The bytes for name. - */ - com.google.protobuf.ByteString - getNameBytes(); - - /** - * .google.protobuf.StringValue phone = 3; - * @return Whether the phone field is set. - */ - boolean hasPhone(); - /** - * .google.protobuf.StringValue phone = 3; - * @return The phone. - */ - com.google.protobuf.StringValue getPhone(); - /** - * .google.protobuf.StringValue phone = 3; - */ - com.google.protobuf.StringValueOrBuilder getPhoneOrBuilder(); - - /** - * repeated string hobbies = 4; - * @return A list containing the hobbies. - */ - java.util.List - getHobbiesList(); - /** - * repeated string hobbies = 4; - * @return The count of hobbies. - */ - int getHobbiesCount(); - /** - * repeated string hobbies = 4; - * @param index The index of the element to return. - * @return The hobbies at the given index. - */ - String getHobbies(int index); - /** - * repeated string hobbies = 4; - * @param index The index of the value to return. - * @return The bytes of the hobbies at the given index. - */ - com.google.protobuf.ByteString - getHobbiesBytes(int index); - } - /** - * Protobuf type {@code PBPerson} - */ - public static final class PBPerson extends - GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:PBPerson) - PBPersonOrBuilder { - private static final long serialVersionUID = 0L; - // Use PBPerson.newBuilder() to construct. - private PBPerson(GeneratedMessageV3.Builder builder) { - super(builder); - } - private PBPerson() { - name_ = ""; - hobbies_ = com.google.protobuf.LazyStringArrayList.EMPTY; - } - - @Override - @SuppressWarnings({"unused"}) - protected Object newInstance( - UnusedPrivateParameter unused) { - return new PBPerson(); - } - - @Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private PBPerson( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - case 8: { - - id_ = input.readInt64(); - break; - } - case 18: { - String s = input.readStringRequireUtf8(); - - name_ = s; - break; - } - case 26: { - com.google.protobuf.StringValue.Builder subBuilder = null; - if (phone_ != null) { - subBuilder = phone_.toBuilder(); - } - phone_ = input.readMessage(com.google.protobuf.StringValue.parser(), extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(phone_); - phone_ = subBuilder.buildPartial(); - } - - break; - } - case 34: { - String s = input.readStringRequireUtf8(); - if (!((mutable_bitField0_ & 0x00000001) != 0)) { - hobbies_ = new com.google.protobuf.LazyStringArrayList(); - mutable_bitField0_ |= 0x00000001; - } - hobbies_.add(s); - break; - } - default: { - if (!parseUnknownField( - input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e).setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000001) != 0)) { - hobbies_ = hobbies_.getUnmodifiableView(); - } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ConversionTest.internal_static_PBPerson_descriptor; - } - - @Override - protected GeneratedMessageV3.FieldAccessorTable - internalGetFieldAccessorTable() { - return ConversionTest.internal_static_PBPerson_fieldAccessorTable - .ensureFieldAccessorsInitialized( - PBPerson.class, Builder.class); - } - - public static final int ID_FIELD_NUMBER = 1; - private long id_; - /** - * int64 id = 1; - * @return The id. - */ - @Override - public long getId() { - return id_; - } - - public static final int NAME_FIELD_NUMBER = 2; - private volatile Object name_; - /** - * string name = 2; - * @return The name. - */ - @Override - public String getName() { - Object ref = name_; - if (ref instanceof String) { - return (String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - name_ = s; - return s; - } - } - /** - * string name = 2; - * @return The bytes for name. - */ - @Override - public com.google.protobuf.ByteString - getNameBytes() { - Object ref = name_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - public static final int PHONE_FIELD_NUMBER = 3; - private com.google.protobuf.StringValue phone_; - /** - * .google.protobuf.StringValue phone = 3; - * @return Whether the phone field is set. - */ - @Override - public boolean hasPhone() { - return phone_ != null; - } - /** - * .google.protobuf.StringValue phone = 3; - * @return The phone. - */ - @Override - public com.google.protobuf.StringValue getPhone() { - return phone_ == null ? com.google.protobuf.StringValue.getDefaultInstance() : phone_; - } - /** - * .google.protobuf.StringValue phone = 3; - */ - @Override - public com.google.protobuf.StringValueOrBuilder getPhoneOrBuilder() { - return getPhone(); - } - - public static final int HOBBIES_FIELD_NUMBER = 4; - private com.google.protobuf.LazyStringList hobbies_; - /** - * repeated string hobbies = 4; - * @return A list containing the hobbies. - */ - public com.google.protobuf.ProtocolStringList - getHobbiesList() { - return hobbies_; - } - /** - * repeated string hobbies = 4; - * @return The count of hobbies. - */ - public int getHobbiesCount() { - return hobbies_.size(); - } - /** - * repeated string hobbies = 4; - * @param index The index of the element to return. - * @return The hobbies at the given index. - */ - public String getHobbies(int index) { - return hobbies_.get(index); - } - /** - * repeated string hobbies = 4; - * @param index The index of the value to return. - * @return The bytes of the hobbies at the given index. - */ - public com.google.protobuf.ByteString - getHobbiesBytes(int index) { - return hobbies_.getByteString(index); - } - - private byte memoizedIsInitialized = -1; - @Override - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - @Override - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - if (id_ != 0L) { - output.writeInt64(1, id_); - } - if (!getNameBytes().isEmpty()) { - GeneratedMessageV3.writeString(output, 2, name_); - } - if (phone_ != null) { - output.writeMessage(3, getPhone()); - } - for (int i = 0; i < hobbies_.size(); i++) { - GeneratedMessageV3.writeString(output, 4, hobbies_.getRaw(i)); - } - unknownFields.writeTo(output); - } - - @Override - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; - - size = 0; - if (id_ != 0L) { - size += com.google.protobuf.CodedOutputStream - .computeInt64Size(1, id_); - } - if (!getNameBytes().isEmpty()) { - size += GeneratedMessageV3.computeStringSize(2, name_); - } - if (phone_ != null) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(3, getPhone()); - } - { - int dataSize = 0; - for (int i = 0; i < hobbies_.size(); i++) { - dataSize += computeStringSizeNoTag(hobbies_.getRaw(i)); - } - size += dataSize; - size += 1 * getHobbiesList().size(); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof PBPerson)) { - return super.equals(obj); - } - PBPerson other = (PBPerson) obj; - - if (getId() - != other.getId()) return false; - if (!getName() - .equals(other.getName())) return false; - if (hasPhone() != other.hasPhone()) return false; - if (hasPhone()) { - if (!getPhone() - .equals(other.getPhone())) return false; - } - if (!getHobbiesList() - .equals(other.getHobbiesList())) return false; - if (!unknownFields.equals(other.unknownFields)) return false; - return true; - } - - @Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + ID_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashLong( - getId()); - hash = (37 * hash) + NAME_FIELD_NUMBER; - hash = (53 * hash) + getName().hashCode(); - if (hasPhone()) { - hash = (37 * hash) + PHONE_FIELD_NUMBER; - hash = (53 * hash) + getPhone().hashCode(); - } - if (getHobbiesCount() > 0) { - hash = (37 * hash) + HOBBIES_FIELD_NUMBER; - hash = (53 * hash) + getHobbiesList().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static PBPerson parseFrom( - java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static PBPerson parseFrom( - java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static PBPerson parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static PBPerson parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static PBPerson parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static PBPerson parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static PBPerson parseFrom(java.io.InputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static PBPerson parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - public static PBPerson parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - public static PBPerson parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - public static PBPerson parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static PBPerson parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - @Override - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - public static Builder newBuilder(PBPerson prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - @Override - public Builder toBuilder() { - return this == DEFAULT_INSTANCE - ? new Builder() : new Builder().mergeFrom(this); - } - - @Override - protected Builder newBuilderForType( - GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** - * Protobuf type {@code PBPerson} - */ - public static final class Builder extends - GeneratedMessageV3.Builder implements - // @@protoc_insertion_point(builder_implements:PBPerson) - PBPersonOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ConversionTest.internal_static_PBPerson_descriptor; - } - - @Override - protected GeneratedMessageV3.FieldAccessorTable - internalGetFieldAccessorTable() { - return ConversionTest.internal_static_PBPerson_fieldAccessorTable - .ensureFieldAccessorsInitialized( - PBPerson.class, Builder.class); - } - - // Construct using pbconverts.ConversionTest.PBPerson.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (GeneratedMessageV3 - .alwaysUseFieldBuilders) { - } - } - @Override - public Builder clear() { - super.clear(); - id_ = 0L; - - name_ = ""; - - if (phoneBuilder_ == null) { - phone_ = null; - } else { - phone_ = null; - phoneBuilder_ = null; - } - hobbies_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000001); - return this; - } - - @Override - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return ConversionTest.internal_static_PBPerson_descriptor; - } - - @Override - public PBPerson getDefaultInstanceForType() { - return PBPerson.getDefaultInstance(); - } - - @Override - public PBPerson build() { - PBPerson result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - @Override - public PBPerson buildPartial() { - PBPerson result = new PBPerson(this); - int from_bitField0_ = bitField0_; - result.id_ = id_; - result.name_ = name_; - if (phoneBuilder_ == null) { - result.phone_ = phone_; - } else { - result.phone_ = phoneBuilder_.build(); - } - if (((bitField0_ & 0x00000001) != 0)) { - hobbies_ = hobbies_.getUnmodifiableView(); - bitField0_ = (bitField0_ & ~0x00000001); - } - result.hobbies_ = hobbies_; - onBuilt(); - return result; - } - - @Override - public Builder clone() { - return super.clone(); - } - @Override - public Builder setField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.setField(field, value); - } - @Override - public Builder clearField( - com.google.protobuf.Descriptors.FieldDescriptor field) { - return super.clearField(field); - } - @Override - public Builder clearOneof( - com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return super.clearOneof(oneof); - } - @Override - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - int index, Object value) { - return super.setRepeatedField(field, index, value); - } - @Override - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.addRepeatedField(field, value); - } - @Override - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof PBPerson) { - return mergeFrom((PBPerson)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(PBPerson other) { - if (other == PBPerson.getDefaultInstance()) return this; - if (other.getId() != 0L) { - setId(other.getId()); - } - if (!other.getName().isEmpty()) { - name_ = other.name_; - onChanged(); - } - if (other.hasPhone()) { - mergePhone(other.getPhone()); - } - if (!other.hobbies_.isEmpty()) { - if (hobbies_.isEmpty()) { - hobbies_ = other.hobbies_; - bitField0_ = (bitField0_ & ~0x00000001); - } else { - ensureHobbiesIsMutable(); - hobbies_.addAll(other.hobbies_); - } - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - @Override - public final boolean isInitialized() { - return true; - } - - @Override - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - PBPerson parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (PBPerson) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - private int bitField0_; - - private long id_ ; - /** - * int64 id = 1; - * @return The id. - */ - @Override - public long getId() { - return id_; - } - /** - * int64 id = 1; - * @param value The id to set. - * @return This builder for chaining. - */ - public Builder setId(long value) { - - id_ = value; - onChanged(); - return this; - } - /** - * int64 id = 1; - * @return This builder for chaining. - */ - public Builder clearId() { - - id_ = 0L; - onChanged(); - return this; - } - - private Object name_ = ""; - /** - * string name = 2; - * @return The name. - */ - public String getName() { - Object ref = name_; - if (!(ref instanceof String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - name_ = s; - return s; - } else { - return (String) ref; - } - } - /** - * string name = 2; - * @return The bytes for name. - */ - public com.google.protobuf.ByteString - getNameBytes() { - Object ref = name_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * string name = 2; - * @param value The name to set. - * @return This builder for chaining. - */ - public Builder setName( - String value) { - if (value == null) { - throw new NullPointerException(); - } - - name_ = value; - onChanged(); - return this; - } - /** - * string name = 2; - * @return This builder for chaining. - */ - public Builder clearName() { - - name_ = getDefaultInstance().getName(); - onChanged(); - return this; - } - /** - * string name = 2; - * @param value The bytes for name to set. - * @return This builder for chaining. - */ - public Builder setNameBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - name_ = value; - onChanged(); - return this; - } - - private com.google.protobuf.StringValue phone_; - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.StringValue, com.google.protobuf.StringValue.Builder, com.google.protobuf.StringValueOrBuilder> phoneBuilder_; - /** - * .google.protobuf.StringValue phone = 3; - * @return Whether the phone field is set. - */ - public boolean hasPhone() { - return phoneBuilder_ != null || phone_ != null; - } - /** - * .google.protobuf.StringValue phone = 3; - * @return The phone. - */ - public com.google.protobuf.StringValue getPhone() { - if (phoneBuilder_ == null) { - return phone_ == null ? com.google.protobuf.StringValue.getDefaultInstance() : phone_; - } else { - return phoneBuilder_.getMessage(); - } - } - /** - * .google.protobuf.StringValue phone = 3; - */ - public Builder setPhone(com.google.protobuf.StringValue value) { - if (phoneBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - phone_ = value; - onChanged(); - } else { - phoneBuilder_.setMessage(value); - } - - return this; - } - /** - * .google.protobuf.StringValue phone = 3; - */ - public Builder setPhone( - com.google.protobuf.StringValue.Builder builderForValue) { - if (phoneBuilder_ == null) { - phone_ = builderForValue.build(); - onChanged(); - } else { - phoneBuilder_.setMessage(builderForValue.build()); - } - - return this; - } - /** - * .google.protobuf.StringValue phone = 3; - */ - public Builder mergePhone(com.google.protobuf.StringValue value) { - if (phoneBuilder_ == null) { - if (phone_ != null) { - phone_ = - com.google.protobuf.StringValue.newBuilder(phone_).mergeFrom(value).buildPartial(); - } else { - phone_ = value; - } - onChanged(); - } else { - phoneBuilder_.mergeFrom(value); - } - - return this; - } - /** - * .google.protobuf.StringValue phone = 3; - */ - public Builder clearPhone() { - if (phoneBuilder_ == null) { - phone_ = null; - onChanged(); - } else { - phone_ = null; - phoneBuilder_ = null; - } - - return this; - } - /** - * .google.protobuf.StringValue phone = 3; - */ - public com.google.protobuf.StringValue.Builder getPhoneBuilder() { - - onChanged(); - return getPhoneFieldBuilder().getBuilder(); - } - /** - * .google.protobuf.StringValue phone = 3; - */ - public com.google.protobuf.StringValueOrBuilder getPhoneOrBuilder() { - if (phoneBuilder_ != null) { - return phoneBuilder_.getMessageOrBuilder(); - } else { - return phone_ == null ? - com.google.protobuf.StringValue.getDefaultInstance() : phone_; - } - } - /** - * .google.protobuf.StringValue phone = 3; - */ - private com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.StringValue, com.google.protobuf.StringValue.Builder, com.google.protobuf.StringValueOrBuilder> - getPhoneFieldBuilder() { - if (phoneBuilder_ == null) { - phoneBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< - com.google.protobuf.StringValue, com.google.protobuf.StringValue.Builder, com.google.protobuf.StringValueOrBuilder>( - getPhone(), - getParentForChildren(), - isClean()); - phone_ = null; - } - return phoneBuilder_; - } - - private com.google.protobuf.LazyStringList hobbies_ = com.google.protobuf.LazyStringArrayList.EMPTY; - private void ensureHobbiesIsMutable() { - if (!((bitField0_ & 0x00000001) != 0)) { - hobbies_ = new com.google.protobuf.LazyStringArrayList(hobbies_); - bitField0_ |= 0x00000001; - } - } - /** - * repeated string hobbies = 4; - * @return A list containing the hobbies. - */ - public com.google.protobuf.ProtocolStringList - getHobbiesList() { - return hobbies_.getUnmodifiableView(); - } - /** - * repeated string hobbies = 4; - * @return The count of hobbies. - */ - public int getHobbiesCount() { - return hobbies_.size(); - } - /** - * repeated string hobbies = 4; - * @param index The index of the element to return. - * @return The hobbies at the given index. - */ - public String getHobbies(int index) { - return hobbies_.get(index); - } - /** - * repeated string hobbies = 4; - * @param index The index of the value to return. - * @return The bytes of the hobbies at the given index. - */ - public com.google.protobuf.ByteString - getHobbiesBytes(int index) { - return hobbies_.getByteString(index); - } - /** - * repeated string hobbies = 4; - * @param index The index to set the value at. - * @param value The hobbies to set. - * @return This builder for chaining. - */ - public Builder setHobbies( - int index, String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureHobbiesIsMutable(); - hobbies_.set(index, value); - onChanged(); - return this; - } - /** - * repeated string hobbies = 4; - * @param value The hobbies to add. - * @return This builder for chaining. - */ - public Builder addHobbies( - String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureHobbiesIsMutable(); - hobbies_.add(value); - onChanged(); - return this; - } - /** - * repeated string hobbies = 4; - * @param values The hobbies to add. - * @return This builder for chaining. - */ - public Builder addAllHobbies( - Iterable values) { - ensureHobbiesIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll( - values, hobbies_); - onChanged(); - return this; - } - /** - * repeated string hobbies = 4; - * @return This builder for chaining. - */ - public Builder clearHobbies() { - hobbies_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000001); - onChanged(); - return this; - } - /** - * repeated string hobbies = 4; - * @param value The bytes of the hobbies to add. - * @return This builder for chaining. - */ - public Builder addHobbiesBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - ensureHobbiesIsMutable(); - hobbies_.add(value); - onChanged(); - return this; - } - @Override - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFields(unknownFields); - } - - @Override - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - - // @@protoc_insertion_point(builder_scope:PBPerson) - } - - // @@protoc_insertion_point(class_scope:PBPerson) - private static final PBPerson DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new PBPerson(); - } - - public static PBPerson getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { - @Override - public PBPerson parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new PBPerson(input, extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - @Override - public PBPerson getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - - } - - public interface PBTestBytesOrBuilder extends - // @@protoc_insertion_point(interface_extends:PBTestBytes) - com.google.protobuf.MessageOrBuilder { - - /** - * bytes test_bytes = 1; - * @return The testBytes. - */ - com.google.protobuf.ByteString getTestBytes(); - } - /** - * Protobuf type {@code PBTestBytes} - */ - public static final class PBTestBytes extends - GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:PBTestBytes) - PBTestBytesOrBuilder { - private static final long serialVersionUID = 0L; - // Use PBTestBytes.newBuilder() to construct. - private PBTestBytes(GeneratedMessageV3.Builder builder) { - super(builder); - } - private PBTestBytes() { - testBytes_ = com.google.protobuf.ByteString.EMPTY; - } - - @Override - @SuppressWarnings({"unused"}) - protected Object newInstance( - GeneratedMessageV3.UnusedPrivateParameter unused) { - return new PBTestBytes(); - } - - @Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private PBTestBytes( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new NullPointerException(); - } - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - case 10: { - - testBytes_ = input.readBytes(); - break; - } - default: { - if (!parseUnknownField( - input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ConversionTest.internal_static_PBTestBytes_descriptor; - } - - @Override - protected GeneratedMessageV3.FieldAccessorTable - internalGetFieldAccessorTable() { - return ConversionTest.internal_static_PBTestBytes_fieldAccessorTable - .ensureFieldAccessorsInitialized( - PBTestBytes.class, Builder.class); - } - - public static final int TEST_BYTES_FIELD_NUMBER = 1; - private com.google.protobuf.ByteString testBytes_; - /** - * bytes test_bytes = 1; - * @return The testBytes. - */ - @Override - public com.google.protobuf.ByteString getTestBytes() { - return testBytes_; - } - - private byte memoizedIsInitialized = -1; - @Override - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - @Override - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - if (!testBytes_.isEmpty()) { - output.writeBytes(1, testBytes_); - } - unknownFields.writeTo(output); - } - - @Override - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; - - size = 0; - if (!testBytes_.isEmpty()) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(1, testBytes_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof PBTestBytes)) { - return super.equals(obj); - } - PBTestBytes other = (PBTestBytes) obj; - - if (!getTestBytes() - .equals(other.getTestBytes())) return false; - if (!unknownFields.equals(other.unknownFields)) return false; - return true; - } - - @Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + TEST_BYTES_FIELD_NUMBER; - hash = (53 * hash) + getTestBytes().hashCode(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static PBTestBytes parseFrom( - java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static PBTestBytes parseFrom( - java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static PBTestBytes parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static PBTestBytes parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static PBTestBytes parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static PBTestBytes parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static PBTestBytes parseFrom(java.io.InputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static PBTestBytes parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - public static PBTestBytes parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - public static PBTestBytes parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - public static PBTestBytes parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static PBTestBytes parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - @Override - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - public static Builder newBuilder(PBTestBytes prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - @Override - public Builder toBuilder() { - return this == DEFAULT_INSTANCE - ? new Builder() : new Builder().mergeFrom(this); - } - - @Override - protected Builder newBuilderForType( - GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** - * Protobuf type {@code PBTestBytes} - */ - public static final class Builder extends - GeneratedMessageV3.Builder implements - // @@protoc_insertion_point(builder_implements:PBTestBytes) - PBTestBytesOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ConversionTest.internal_static_PBTestBytes_descriptor; - } - - @Override - protected GeneratedMessageV3.FieldAccessorTable - internalGetFieldAccessorTable() { - return ConversionTest.internal_static_PBTestBytes_fieldAccessorTable - .ensureFieldAccessorsInitialized( - PBTestBytes.class, Builder.class); - } - - // Construct using pbconverts.ConversionTest.PBTestBytes.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (GeneratedMessageV3 - .alwaysUseFieldBuilders) { - } - } - @Override - public Builder clear() { - super.clear(); - testBytes_ = com.google.protobuf.ByteString.EMPTY; - - return this; - } - - @Override - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return ConversionTest.internal_static_PBTestBytes_descriptor; - } - - @Override - public PBTestBytes getDefaultInstanceForType() { - return PBTestBytes.getDefaultInstance(); - } - - @Override - public PBTestBytes build() { - PBTestBytes result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - @Override - public PBTestBytes buildPartial() { - PBTestBytes result = new PBTestBytes(this); - result.testBytes_ = testBytes_; - onBuilt(); - return result; - } - - @Override - public Builder clone() { - return super.clone(); - } - @Override - public Builder setField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.setField(field, value); - } - @Override - public Builder clearField( - com.google.protobuf.Descriptors.FieldDescriptor field) { - return super.clearField(field); - } - @Override - public Builder clearOneof( - com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return super.clearOneof(oneof); - } - @Override - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - int index, Object value) { - return super.setRepeatedField(field, index, value); - } - @Override - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.addRepeatedField(field, value); - } - @Override - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof PBTestBytes) { - return mergeFrom((PBTestBytes)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(PBTestBytes other) { - if (other == PBTestBytes.getDefaultInstance()) return this; - if (other.getTestBytes() != com.google.protobuf.ByteString.EMPTY) { - setTestBytes(other.getTestBytes()); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - @Override - public final boolean isInitialized() { - return true; - } - - @Override - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - PBTestBytes parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (PBTestBytes) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private com.google.protobuf.ByteString testBytes_ = com.google.protobuf.ByteString.EMPTY; - /** - * bytes test_bytes = 1; - * @return The testBytes. - */ - @Override - public com.google.protobuf.ByteString getTestBytes() { - return testBytes_; - } - /** - * bytes test_bytes = 1; - * @param value The testBytes to set. - * @return This builder for chaining. - */ - public Builder setTestBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - - testBytes_ = value; - onChanged(); - return this; - } - /** - * bytes test_bytes = 1; - * @return This builder for chaining. - */ - public Builder clearTestBytes() { - - testBytes_ = getDefaultInstance().getTestBytes(); - onChanged(); - return this; - } - @Override - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFields(unknownFields); - } - - @Override - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - - // @@protoc_insertion_point(builder_scope:PBTestBytes) - } - - // @@protoc_insertion_point(class_scope:PBTestBytes) - private static final PBTestBytes DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new PBTestBytes(); - } - - public static PBTestBytes getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { - @Override - public PBTestBytes parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new PBTestBytes(input, extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - @Override - public PBTestBytes getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - - } - - public interface IntMessageOrBuilder extends - // @@protoc_insertion_point(interface_extends:IntMessage) - com.google.protobuf.MessageOrBuilder { - - /** - * int32 value = 1; - * @return The value. - */ - int getValue(); - } - /** - * Protobuf type {@code IntMessage} - */ - public static final class IntMessage extends - GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:IntMessage) - IntMessageOrBuilder { - private static final long serialVersionUID = 0L; - // Use IntMessage.newBuilder() to construct. - private IntMessage(GeneratedMessageV3.Builder builder) { - super(builder); - } - private IntMessage() { - } - - @Override - @SuppressWarnings({"unused"}) - protected Object newInstance( - UnusedPrivateParameter unused) { - return new IntMessage(); - } - - @Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private IntMessage( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new NullPointerException(); - } - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - case 8: { - - value_ = input.readInt32(); - break; - } - default: { - if (!parseUnknownField( - input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ConversionTest.internal_static_IntMessage_descriptor; - } - - @Override - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return ConversionTest.internal_static_IntMessage_fieldAccessorTable - .ensureFieldAccessorsInitialized( - IntMessage.class, Builder.class); - } - - public static final int VALUE_FIELD_NUMBER = 1; - private int value_; - /** - * int32 value = 1; - * @return The value. - */ - @Override - public int getValue() { - return value_; - } - - private byte memoizedIsInitialized = -1; - @Override - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - @Override - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - if (value_ != 0) { - output.writeInt32(1, value_); - } - unknownFields.writeTo(output); - } - - @Override - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; - - size = 0; - if (value_ != 0) { - size += com.google.protobuf.CodedOutputStream - .computeInt32Size(1, value_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof IntMessage)) { - return super.equals(obj); - } - IntMessage other = (IntMessage) obj; - - if (getValue() - != other.getValue()) return false; - if (!unknownFields.equals(other.unknownFields)) return false; - return true; - } - - @Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + VALUE_FIELD_NUMBER; - hash = (53 * hash) + getValue(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static IntMessage parseFrom( - java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static IntMessage parseFrom( - java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static IntMessage parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static IntMessage parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static IntMessage parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static IntMessage parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static IntMessage parseFrom(java.io.InputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static IntMessage parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - public static IntMessage parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - public static IntMessage parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - public static IntMessage parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static IntMessage parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - @Override - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - public static Builder newBuilder(IntMessage prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - @Override - public Builder toBuilder() { - return this == DEFAULT_INSTANCE - ? new Builder() : new Builder().mergeFrom(this); - } - - @Override - protected Builder newBuilderForType( - BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** - * Protobuf type {@code IntMessage} - */ - public static final class Builder extends - GeneratedMessageV3.Builder implements - // @@protoc_insertion_point(builder_implements:IntMessage) - IntMessageOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ConversionTest.internal_static_IntMessage_descriptor; - } - - @Override - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return ConversionTest.internal_static_IntMessage_fieldAccessorTable - .ensureFieldAccessorsInitialized( - IntMessage.class, Builder.class); - } - - // Construct using pbconverts.ConversionTest.IntMessage.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (GeneratedMessageV3 - .alwaysUseFieldBuilders) { - } - } - @Override - public Builder clear() { - super.clear(); - value_ = 0; - - return this; - } - - @Override - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return ConversionTest.internal_static_IntMessage_descriptor; - } - - @Override - public IntMessage getDefaultInstanceForType() { - return IntMessage.getDefaultInstance(); - } - - @Override - public IntMessage build() { - IntMessage result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - @Override - public IntMessage buildPartial() { - IntMessage result = new IntMessage(this); - result.value_ = value_; - onBuilt(); - return result; - } - - @Override - public Builder clone() { - return super.clone(); - } - @Override - public Builder setField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.setField(field, value); - } - @Override - public Builder clearField( - com.google.protobuf.Descriptors.FieldDescriptor field) { - return super.clearField(field); - } - @Override - public Builder clearOneof( - com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return super.clearOneof(oneof); - } - @Override - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - int index, Object value) { - return super.setRepeatedField(field, index, value); - } - @Override - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.addRepeatedField(field, value); - } - @Override - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof IntMessage) { - return mergeFrom((IntMessage)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(IntMessage other) { - if (other == IntMessage.getDefaultInstance()) return this; - if (other.getValue() != 0) { - setValue(other.getValue()); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - @Override - public final boolean isInitialized() { - return true; - } - - @Override - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - IntMessage parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (IntMessage) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int value_ ; - /** - * int32 value = 1; - * @return The value. - */ - @Override - public int getValue() { - return value_; - } - /** - * int32 value = 1; - * @param value The value to set. - * @return This builder for chaining. - */ - public Builder setValue(int value) { - - value_ = value; - onChanged(); - return this; - } - /** - * int32 value = 1; - * @return This builder for chaining. - */ - public Builder clearValue() { - - value_ = 0; - onChanged(); - return this; - } - @Override - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFields(unknownFields); - } - - @Override - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - - // @@protoc_insertion_point(builder_scope:IntMessage) - } - - // @@protoc_insertion_point(class_scope:IntMessage) - private static final IntMessage DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new IntMessage(); - } - - public static IntMessage getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { - @Override - public IntMessage parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new IntMessage(input, extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - @Override - public IntMessage getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - - } - - public interface StringMessageOrBuilder extends - // @@protoc_insertion_point(interface_extends:StringMessage) - com.google.protobuf.MessageOrBuilder { - - /** - * string value = 1; - * @return The value. - */ - String getValue(); - /** - * string value = 1; - * @return The bytes for value. - */ - com.google.protobuf.ByteString - getValueBytes(); - } - /** - * Protobuf type {@code StringMessage} - */ - public static final class StringMessage extends - GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:StringMessage) - StringMessageOrBuilder { - private static final long serialVersionUID = 0L; - // Use StringMessage.newBuilder() to construct. - private StringMessage(GeneratedMessageV3.Builder builder) { - super(builder); - } - private StringMessage() { - value_ = ""; - } - - @Override - @SuppressWarnings({"unused"}) - protected Object newInstance( - UnusedPrivateParameter unused) { - return new StringMessage(); - } - - @Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private StringMessage( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new NullPointerException(); - } - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - case 10: { - String s = input.readStringRequireUtf8(); - - value_ = s; - break; - } - default: { - if (!parseUnknownField( - input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ConversionTest.internal_static_StringMessage_descriptor; - } - - @Override - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return ConversionTest.internal_static_StringMessage_fieldAccessorTable - .ensureFieldAccessorsInitialized( - StringMessage.class, Builder.class); - } - - public static final int VALUE_FIELD_NUMBER = 1; - private volatile Object value_; - /** - * string value = 1; - * @return The value. - */ - @Override - public String getValue() { - Object ref = value_; - if (ref instanceof String) { - return (String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - value_ = s; - return s; - } - } - /** - * string value = 1; - * @return The bytes for value. - */ - @Override - public com.google.protobuf.ByteString - getValueBytes() { - Object ref = value_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - value_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - private byte memoizedIsInitialized = -1; - @Override - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - @Override - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - if (!getValueBytes().isEmpty()) { - GeneratedMessageV3.writeString(output, 1, value_); - } - unknownFields.writeTo(output); - } - - @Override - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; - - size = 0; - if (!getValueBytes().isEmpty()) { - size += GeneratedMessageV3.computeStringSize(1, value_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof StringMessage)) { - return super.equals(obj); - } - StringMessage other = (StringMessage) obj; - - if (!getValue() - .equals(other.getValue())) return false; - if (!unknownFields.equals(other.unknownFields)) return false; - return true; - } - - @Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + VALUE_FIELD_NUMBER; - hash = (53 * hash) + getValue().hashCode(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static StringMessage parseFrom( - java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static StringMessage parseFrom( - java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static StringMessage parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static StringMessage parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static StringMessage parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static StringMessage parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static StringMessage parseFrom(java.io.InputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static StringMessage parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - public static StringMessage parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - public static StringMessage parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - public static StringMessage parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static StringMessage parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - @Override - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - public static Builder newBuilder(StringMessage prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - @Override - public Builder toBuilder() { - return this == DEFAULT_INSTANCE - ? new Builder() : new Builder().mergeFrom(this); - } - - @Override - protected Builder newBuilderForType( - BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** - * Protobuf type {@code StringMessage} - */ - public static final class Builder extends - GeneratedMessageV3.Builder implements - // @@protoc_insertion_point(builder_implements:StringMessage) - StringMessageOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return ConversionTest.internal_static_StringMessage_descriptor; - } - - @Override - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return ConversionTest.internal_static_StringMessage_fieldAccessorTable - .ensureFieldAccessorsInitialized( - StringMessage.class, Builder.class); - } - - // Construct using pbconverts.ConversionTest.StringMessage.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (GeneratedMessageV3 - .alwaysUseFieldBuilders) { - } - } - @Override - public Builder clear() { - super.clear(); - value_ = ""; - - return this; - } - - @Override - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return ConversionTest.internal_static_StringMessage_descriptor; - } - - @Override - public StringMessage getDefaultInstanceForType() { - return StringMessage.getDefaultInstance(); - } - - @Override - public StringMessage build() { - StringMessage result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - @Override - public StringMessage buildPartial() { - StringMessage result = new StringMessage(this); - result.value_ = value_; - onBuilt(); - return result; - } - - @Override - public Builder clone() { - return super.clone(); - } - @Override - public Builder setField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.setField(field, value); - } - @Override - public Builder clearField( - com.google.protobuf.Descriptors.FieldDescriptor field) { - return super.clearField(field); - } - @Override - public Builder clearOneof( - com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return super.clearOneof(oneof); - } - @Override - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - int index, Object value) { - return super.setRepeatedField(field, index, value); - } - @Override - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.addRepeatedField(field, value); - } - @Override - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof StringMessage) { - return mergeFrom((StringMessage)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(StringMessage other) { - if (other == StringMessage.getDefaultInstance()) return this; - if (!other.getValue().isEmpty()) { - value_ = other.value_; - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - @Override - public final boolean isInitialized() { - return true; - } - - @Override - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - StringMessage parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (StringMessage) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private Object value_ = ""; - /** - * string value = 1; - * @return The value. - */ - public String getValue() { - Object ref = value_; - if (!(ref instanceof String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - value_ = s; - return s; - } else { - return (String) ref; - } - } - /** - * string value = 1; - * @return The bytes for value. - */ - public com.google.protobuf.ByteString - getValueBytes() { - Object ref = value_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - value_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * string value = 1; - * @param value The value to set. - * @return This builder for chaining. - */ - public Builder setValue( - String value) { - if (value == null) { - throw new NullPointerException(); - } - - value_ = value; - onChanged(); - return this; - } - /** - * string value = 1; - * @return This builder for chaining. - */ - public Builder clearValue() { - - value_ = getDefaultInstance().getValue(); - onChanged(); - return this; - } - /** - * string value = 1; - * @param value The bytes for value to set. - * @return This builder for chaining. - */ - public Builder setValueBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - value_ = value; - onChanged(); - return this; - } - @Override - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFields(unknownFields); - } - - @Override - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - - // @@protoc_insertion_point(builder_scope:StringMessage) - } - - // @@protoc_insertion_point(class_scope:StringMessage) - private static final StringMessage DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new StringMessage(); - } - - public static StringMessage getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { - @Override - public StringMessage parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new StringMessage(input, extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - @Override - public StringMessage getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - - } - - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_PBTestMessage_descriptor; - private static final - GeneratedMessageV3.FieldAccessorTable - internal_static_PBTestMessage_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_PBTestMessage_StringStringKVEntry_descriptor; - private static final - GeneratedMessageV3.FieldAccessorTable - internal_static_PBTestMessage_StringStringKVEntry_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_PBTestMessage_LongStringKVEntry_descriptor; - private static final - GeneratedMessageV3.FieldAccessorTable - internal_static_PBTestMessage_LongStringKVEntry_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_PBTestMessage_StringIntKVEntry_descriptor; - private static final - GeneratedMessageV3.FieldAccessorTable - internal_static_PBTestMessage_StringIntKVEntry_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_PBTestMessage_LongIntKVEntry_descriptor; - private static final - GeneratedMessageV3.FieldAccessorTable - internal_static_PBTestMessage_LongIntKVEntry_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_PBPerson_descriptor; - private static final - GeneratedMessageV3.FieldAccessorTable - internal_static_PBPerson_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_PBTestBytes_descriptor; - private static final - GeneratedMessageV3.FieldAccessorTable - internal_static_PBTestBytes_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_IntMessage_descriptor; - private static final - GeneratedMessageV3.FieldAccessorTable - internal_static_IntMessage_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_StringMessage_descriptor; - private static final - GeneratedMessageV3.FieldAccessorTable - internal_static_StringMessage_fieldAccessorTable; - - public static com.google.protobuf.Descriptors.FileDescriptor - getDescriptor() { - return descriptor; - } - private static com.google.protobuf.Descriptors.FileDescriptor - descriptor; - static { - String[] descriptorData = { - "\n\025conversion_test.proto\032\036google/protobuf" + - "/wrappers.proto\032\037google/protobuf/timesta" + - "mp.proto\"\223\010\n\rPBTestMessage\022\021\n\tint_value\030" + - "\001 \001(\005\022\022\n\nlong_value\030\002 \001(\003\022\023\n\013float_value" + - "\030\003 \001(\002\022\024\n\014double_value\030\004 \001(\001\022\022\n\nbool_val" + - "ue\030\005 \001(\010\022\024\n\014string_value\030\006 \001(\t\022,\n\007int_Op" + - "t\030\007 \001(\0132\033.google.protobuf.Int32Value\022-\n\010" + - "long_Opt\030\010 \001(\0132\033.google.protobuf.Int64Va" + - "lue\022.\n\tfloat_Opt\030\t \001(\0132\033.google.protobuf" + - ".FloatValue\0220\n\ndouble_opt\030\n \001(\0132\034.google" + - ".protobuf.DoubleValue\022,\n\010bool_opt\030\013 \001(\0132" + - "\032.google.protobuf.BoolValue\0220\n\nstring_op" + - "t\030\014 \001(\0132\034.google.protobuf.StringValue\022(\n" + - "\004time\030\r \001(\0132\032.google.protobuf.Timestamp\022" + - ",\n\010time_opt\030\016 \001(\0132\032.google.protobuf.Time" + - "stamp\022\021\n\tint_array\030\017 \003(\005\022\024\n\014string_array" + - "\030\020 \003(\t\022\037\n\014person_array\030\021 \003(\0132\t.PBPerson\022" + - "\013\n\003seq\030\022 \003(\001\022=\n\021string_string_k_v\030\023 \003(\0132" + - "\".PBTestMessage.StringStringKVEntry\0229\n\017l" + - "ong_string_k_v\030\024 \003(\0132 .PBTestMessage.Lon" + - "gStringKVEntry\0227\n\016string_int_k_v\030\025 \003(\0132\037" + - ".PBTestMessage.StringIntKVEntry\0223\n\014long_" + - "int_k_v\030\026 \003(\0132\035.PBTestMessage.LongIntKVE" + - "ntry\0325\n\023StringStringKVEntry\022\013\n\003key\030\001 \001(\t" + - "\022\r\n\005value\030\002 \001(\t:\0028\001\0323\n\021LongStringKVEntry" + - "\022\013\n\003key\030\001 \001(\003\022\r\n\005value\030\002 \001(\t:\0028\001\0322\n\020Stri" + - "ngIntKVEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005value\030\002 \001(\005" + - ":\0028\001\0320\n\016LongIntKVEntry\022\013\n\003key\030\001 \001(\003\022\r\n\005v" + - "alue\030\002 \001(\005:\0028\001\"b\n\010PBPerson\022\n\n\002id\030\001 \001(\003\022\014" + - "\n\004name\030\002 \001(\t\022+\n\005phone\030\003 \001(\0132\034.google.pro" + - "tobuf.StringValue\022\017\n\007hobbies\030\004 \003(\t\"!\n\013PB" + - "TestBytes\022\022\n\ntest_bytes\030\001 \001(\014\"\033\n\nIntMess" + - "age\022\r\n\005value\030\001 \001(\005\"\036\n\rStringMessage\022\r\n\005v" + - "alue\030\001 \001(\tB\014\n\npbconvertsb\006proto3" - }; - descriptor = com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[] { - com.google.protobuf.WrappersProto.getDescriptor(), - com.google.protobuf.TimestampProto.getDescriptor(), - }); - internal_static_PBTestMessage_descriptor = - getDescriptor().getMessageTypes().get(0); - internal_static_PBTestMessage_fieldAccessorTable = new - GeneratedMessageV3.FieldAccessorTable( - internal_static_PBTestMessage_descriptor, - new String[] { "IntValue", "LongValue", "FloatValue", "DoubleValue", "BoolValue", "StringValue", "IntOpt", "LongOpt", "FloatOpt", "DoubleOpt", "BoolOpt", "StringOpt", "Time", "TimeOpt", "IntArray", "StringArray", "PersonArray", "Seq", "StringStringKV", "LongStringKV", "StringIntKV", "LongIntKV", }); - internal_static_PBTestMessage_StringStringKVEntry_descriptor = - internal_static_PBTestMessage_descriptor.getNestedTypes().get(0); - internal_static_PBTestMessage_StringStringKVEntry_fieldAccessorTable = new - GeneratedMessageV3.FieldAccessorTable( - internal_static_PBTestMessage_StringStringKVEntry_descriptor, - new String[] { "Key", "Value", }); - internal_static_PBTestMessage_LongStringKVEntry_descriptor = - internal_static_PBTestMessage_descriptor.getNestedTypes().get(1); - internal_static_PBTestMessage_LongStringKVEntry_fieldAccessorTable = new - GeneratedMessageV3.FieldAccessorTable( - internal_static_PBTestMessage_LongStringKVEntry_descriptor, - new String[] { "Key", "Value", }); - internal_static_PBTestMessage_StringIntKVEntry_descriptor = - internal_static_PBTestMessage_descriptor.getNestedTypes().get(2); - internal_static_PBTestMessage_StringIntKVEntry_fieldAccessorTable = new - GeneratedMessageV3.FieldAccessorTable( - internal_static_PBTestMessage_StringIntKVEntry_descriptor, - new String[] { "Key", "Value", }); - internal_static_PBTestMessage_LongIntKVEntry_descriptor = - internal_static_PBTestMessage_descriptor.getNestedTypes().get(3); - internal_static_PBTestMessage_LongIntKVEntry_fieldAccessorTable = new - GeneratedMessageV3.FieldAccessorTable( - internal_static_PBTestMessage_LongIntKVEntry_descriptor, - new String[] { "Key", "Value", }); - internal_static_PBPerson_descriptor = - getDescriptor().getMessageTypes().get(1); - internal_static_PBPerson_fieldAccessorTable = new - GeneratedMessageV3.FieldAccessorTable( - internal_static_PBPerson_descriptor, - new String[] { "Id", "Name", "Phone", "Hobbies", }); - internal_static_PBTestBytes_descriptor = - getDescriptor().getMessageTypes().get(2); - internal_static_PBTestBytes_fieldAccessorTable = new - GeneratedMessageV3.FieldAccessorTable( - internal_static_PBTestBytes_descriptor, - new String[] { "TestBytes", }); - internal_static_IntMessage_descriptor = - getDescriptor().getMessageTypes().get(3); - internal_static_IntMessage_fieldAccessorTable = new - GeneratedMessageV3.FieldAccessorTable( - internal_static_IntMessage_descriptor, - new String[] { "Value", }); - internal_static_StringMessage_descriptor = - getDescriptor().getMessageTypes().get(4); - internal_static_StringMessage_fieldAccessorTable = new - GeneratedMessageV3.FieldAccessorTable( - internal_static_StringMessage_descriptor, - new String[] { "Value", }); - com.google.protobuf.WrappersProto.getDescriptor(); - com.google.protobuf.TimestampProto.getDescriptor(); - } - - // @@protoc_insertion_point(outer_class_scope) -} diff --git a/pbconverts/src/test/scala/pbconverts/ScalableSpec.scala b/pbconverts/src/test/scala/pbconverts/ScalableSpec.scala index 323a0f6..5581143 100644 --- a/pbconverts/src/test/scala/pbconverts/ScalableSpec.scala +++ b/pbconverts/src/test/scala/pbconverts/ScalableSpec.scala @@ -1,60 +1,60 @@ -package pbconverts +// package pbconverts -import com.google.protobuf.StringValue -import org.scalatest.funsuite.AnyFunSuite -import pbconverts.ConversionTest.{IntMessage, PBPerson} +// import com.google.protobuf.StringValue +// import org.scalatest.funsuite.AnyFunSuite +// import pbconverts.ConversionTest.{IntMessage, PBPerson} -class ScalableSpec extends AnyFunSuite { - test("Scalable") { - val person = Person(1L, "person name", Some("123456"), Seq("play games", "sing song")) +// class ScalableSpec extends AnyFunSuite { +// test("Scalable") { +// // val person = Person(1L, "person name", Some("123456"), Seq("play games", "sing song")) - val builder = PBPerson.newBuilder() - builder.setId(1L) - builder.setName("person name") - builder.setPhone(StringValue.of("123456")) - builder.addHobbies("play games") - builder.addHobbies("sing song") - val personDto = builder.build() +// // val builder = PBPerson.newBuilder() +// // builder.setId(1L) +// // builder.setName("person name") +// // builder.setPhone(StringValue.of("123456")) +// // builder.addHobbies("play games") +// // builder.addHobbies("sing song") +// // val personDto = builder.build() - val person1 = Person( - personDto.getId, - personDto.getName, - if (personDto.hasPhone) Some(personDto.getPhone.getValue) else None, - scala.collection.JavaConverters.iterableAsScalaIterable(personDto.getHobbiesList).toSeq - ) +// // val person1 = Person( +// // personDto.getId, +// // personDto.getName, +// // if (personDto.hasPhone) Some(personDto.getPhone.getValue) else None, +// // scala.collection.JavaConverters.iterableAsScalaIterable(personDto.getHobbiesList).toSeq +// // ) - val person2 = Scalable[Person, PBPerson].toScala(builder.build()) +// // val person2 = Scalable[Person, PBPerson].toScala(builder.build()) - assert(person1 == person2) - } +// // assert(person1 == person2) +// } -// test("type alias") { -// val pbPerson = PBPerson.newBuilder().setId(1L).build() -// -// locally { -// type PPP = Person -// val p = Scalable[PPP, PBPerson].toScala(pbPerson) -// assert(p.id == 1L) -// } -// -// locally { -// type PBP = PBPerson -// val p = Scalable[Person, PBP].toScala(pbPerson) -// assert(p.id == 1L) -// } -// -// locally { -// type PPP = Person -// type PBP = PBPerson -// val p = Scalable[PPP, PBP].toScala(pbPerson) -// assert(p.id == 1L) -// } -// -// locally { -// type IM = IntMessage -// type MTI = MessageWithType[Int] -// val p = Scalable[MTI, IM].toScala(IntMessage.newBuilder().setValue(1).build()) -// assert(p.value == 1L) -// } -// } -} +// // test("type alias") { +// // val pbPerson = PBPerson.newBuilder().setId(1L).build() +// // +// // locally { +// // type PPP = Person +// // val p = Scalable[PPP, PBPerson].toScala(pbPerson) +// // assert(p.id == 1L) +// // } +// // +// // locally { +// // type PBP = PBPerson +// // val p = Scalable[Person, PBP].toScala(pbPerson) +// // assert(p.id == 1L) +// // } +// // +// // locally { +// // type PPP = Person +// // type PBP = PBPerson +// // val p = Scalable[PPP, PBP].toScala(pbPerson) +// // assert(p.id == 1L) +// // } +// // +// // locally { +// // type IM = IntMessage +// // type MTI = MessageWithType[Int] +// // val p = Scalable[MTI, IM].toScala(IntMessage.newBuilder().setValue(1).build()) +// // assert(p.value == 1L) +// // } +// // } +// } diff --git a/project/build.properties b/project/build.properties index 1129869..7d9ef1e 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1 +1 @@ -sbt.version = 1.5.0-RC2 +sbt.version = 1.5.4 From ed1f28ac712df50710e67f921207db1b85181951 Mon Sep 17 00:00:00 2001 From: changvvb Date: Fri, 17 Dec 2021 16:04:29 +0800 Subject: [PATCH 06/17] wip --- .scalafmt.conf | 3 +- build.sbt | 2 +- .../main/scala/pbconverts/MacroCache.scala | 2 +- .../scala/pbconverts/ProtoScalableMacro.scala | 376 ++++++++++-------- .../src/main/scala/pbconverts/Protoable.scala | 32 +- .../scala/pbconverts/ProtoableBuilder.scala | 10 +- .../src/main/scala/pbconverts/Scalable.scala | 23 +- .../scala/pbconverts/ScalableBuilder.scala | 8 +- .../scala/pbconverts/ScalableImplicits.scala | 4 +- .../src/main/scala/pbconverts/Test.scala | 3 +- .../src/test/scala/pbconverts/MapSpec.scala | 56 +-- .../test/scala/pbconverts/ScalableSpec.scala | 121 +++--- .../src/test/scala/pbconverts/TestMain.scala | 19 + .../test/scala/pbconverts/TestMessage.scala | 142 +++---- version.sbt | 2 +- 15 files changed, 434 insertions(+), 369 deletions(-) create mode 100644 pbconverts/src/test/scala/pbconverts/TestMain.scala diff --git a/.scalafmt.conf b/.scalafmt.conf index 5562c41..6b97c96 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -2,4 +2,5 @@ maxColumn = 160 includeCurlyBraceInSelectChains = false project.git = true project.excludeFilters = ["target/"] -version = 2.6.4 \ No newline at end of file +version = 3.2.1 +runner.dialect = scala3 \ No newline at end of file diff --git a/build.sbt b/build.sbt index c020aee..4cf09f9 100644 --- a/build.sbt +++ b/build.sbt @@ -2,7 +2,7 @@ import sbt._ //lazy val scala213 = "2.13.4" //lazy val scala212 = "2.12.12" -lazy val scala3 = "3.0.2-RC1-bin-SNAPSHOT" +lazy val scala3 = "3.1.0" //lazy val supportedScalaVersions = List(scala212, scala213) diff --git a/pbconverts/src/main/scala/pbconverts/MacroCache.scala b/pbconverts/src/main/scala/pbconverts/MacroCache.scala index 14da99b..295e531 100644 --- a/pbconverts/src/main/scala/pbconverts/MacroCache.scala +++ b/pbconverts/src/main/scala/pbconverts/MacroCache.scala @@ -9,5 +9,5 @@ object MacroCache { def getBuilderId: Int = builderCount.synchronized { builderCount += 1; builderCount } def getIdentityId: Int = identityCount.synchronized { identityCount += 1; identityCount } - lazy val builderFunctionTrees: mutable.Map[Int, mutable.Map[String, Any]] = mutable.Map.empty + lazy val builderFunctionTrees: mutable.Map[String, mutable.Map[String, Any]] = mutable.Map.empty } diff --git a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala index 449bf3d..3853c38 100644 --- a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala +++ b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala @@ -5,50 +5,67 @@ import com.google.protobuf.{ByteString, GeneratedMessageV3, Message} import quoted.{Expr, Quotes, Type} import scala.collection.mutable +import scala.quoted.ToExpr.NoneToExpr +import scala.quoted.Exprs // scalastyle:off number.of.methods -class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Quotes) { +class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])(using quotas: Quotes) { import quotas.reflect._ private[this] val scalaClassType = quotas.reflect.TypeRepr.of[T](using typeT).dealias private[this] val protoClassType = quotas.reflect.TypeRepr.of[M](using typeM).dealias - private[this] val scalaClassSymbol = scalaClassType.typeSymbol + private[this] val scalaClassSymbol: quotas.reflect.Symbol = scalaClassType.typeSymbol private[this] val protoClassSymbol: quotas.reflect.Symbol = quotas.reflect.TypeReprMethods.classSymbol(protoClassType).get + private[this] val scalaClassSymbolModule = quotas.reflect.SymbolMethods.companionModule(scalaClassSymbol) + + private[this] val scalaClassApplySymbol = scalaClassSymbolModule.methodMember("apply").head private[this] val protoClassSymbolClass = quotas.reflect.SymbolMethods.companionClass(protoClassSymbol) private[this] val protoClassSymbolModule = quotas.reflect.SymbolMethods.companionModule(protoClassSymbol) private val newBuilderMethod = quotas.reflect.SymbolMethods.memberMethod(protoClassSymbolModule)("newBuilder").last - private val builderType:TypeRepr = newBuilderMethod.tree.asInstanceOf[DefDef].returnTpt.tpe - private val builderClassSymbol:Symbol = builderType.classSymbol.get + private val builderType: TypeRepr = newBuilderMethod.tree.asInstanceOf[DefDef].returnTpt.tpe + private val builderClassSymbol: Symbol = builderType.classSymbol.get private val builderBuildMethod = builderType.classSymbol.get.memberMethod("build").head + private val (scalaclassOuter, scalaClassName) = scalaClassType match { + case t: AppliedType => + val TypeRef(scalaclassOuter, scalaClassName) = t.tycon + (scalaclassOuter, scalaClassName) + case t: TypeRef => + val TypeRef(scalaclassOuter, scalaClassName) = t + (scalaclassOuter, scalaClassName) + } + + // private val TypeRef(scalaclassOuter, scalaClassName) = scalaClassType.asInstanceOf[TypeRef] + private val scalaCompanionIdent = Ident.apply(TermRef.apply(scalaclassOuter, scalaClassName)) + private val TypeRef(outer, name) = protoClassType.asInstanceOf[TypeRef] private val protoCompanionIdent = Ident.apply(TermRef.apply(outer, name)) - private val newBuilderApply = Apply(Select.apply(protoCompanionIdent, newBuilderMethod),List.empty) - private def builderBuildeWithTerms(termsBuilder:Ident => List[Term]) = ValDef.let(Symbol.spliceOwner,"builder",newBuilderApply) { ident => - val terms = termsBuilder(ident.asInstanceOf[Ident]) - Block(terms,Apply(Select(ident,builderBuildMethod),Nil)) + private val newBuilderApply = Apply(Select.apply(protoCompanionIdent, newBuilderMethod), List.empty) + private def builderBuildeWithTerms(termsBuilder: Ident => List[Term]) = ValDef.let(Symbol.spliceOwner, "builder", newBuilderApply) { ident => + val terms: List[Term] = termsBuilder(ident.asInstanceOf[Ident]) + Block(terms, Apply(Select(ident, builderBuildMethod), Nil)) } - private[this] def implicitlyProtoable(entityType: TypeRepr, protoType: TypeRepr):Term = { - val target = TypeRepr.of[Protoable].appliedTo(List(entityType,protoType)) + private[this] def implicitlyProtoable(entityType: TypeRepr, protoType: TypeRepr): Term = { + val target = TypeRepr.of[Protoable].appliedTo(List(entityType, protoType)) Implicits.search(target) match { case s: ImplicitSearchSuccess => s.tree case _ => report.error(s"implicit ${Printer.TypeReprAnsiCode.show(target)} not found") ??? + } } -} - private[this] def implicitlyScalable(entityType: TypeRepr, protoType: TypeRepr):Term = { + private[this] def implicitlyScalable(entityType: TypeRepr, protoType: TypeRepr): Term = { val target = TypeRepr.of[Scalable].appliedTo(List(entityType, protoType)) Implicits.search(target) match { case s: ImplicitSearchSuccess => s.tree case _ => report.error(s"implicit ${Printer.TypeReprAnsiCode.show(target)} not found") ??? - } //q"implicitly[$packageName.Scalable[$entityType,$protoType]]" + } // q"implicitly[$packageName.Scalable[$entityType,$protoType]]" } private[this] def isOption(tpe: TypeRepr): Boolean = { @@ -78,21 +95,20 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q // Convert expr (`scalaTree` in this class) to protobuf value private class ToProtoProcessor( - protoBuilderIdent:Ident, - scalaTree: Term, + protoBuilderIdent: Ident, + scalaTree: Term, override val scalaTreeType: TypeRepr, override val protoFieldName: String ) extends ProtoFieldAnalyst { - override def protoIdent: ProtoScalableMacro.this.quotas.reflect.Ident = ??? private[this] def toProto(t1: TypeRepr, t2: TypeRepr): Term = { if (t1 <:< t2) { scalaTree } else { - val toProtoMethod = TypeRepr.of[Protoable[_,_]].typeSymbol.memberMethod("toProto").head - Apply(Select(implicitlyProtoable(t1,t2),toProtoMethod),List(scalaTree)) + val toProtoMethod = TypeRepr.of[Protoable[_, _]].typeSymbol.memberMethod("toProto").head + Apply(Select(implicitlyProtoable(t1, t2), toProtoMethod), List(scalaTree)) } } @@ -106,19 +122,19 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q } else { defaultTree(optFieldType) } - '{ if(${scalaTree.asExprOf[Option[_]]}.isDefined) ${tree.asExpr} }.asTerm + '{ if (${ scalaTree.asExprOf[Option[_]] }.isDefined) ${ tree.asExpr } }.asTerm // If(q"$scalaTree.isDefined", tree, EmptyTree) } def seqTree(iterableType: TypeRepr): Term = { - val addAllMethod = builderClassSymbol.memberMethod(addAllMethodName).last + val addAllMethod = builderClassSymbol.memberMethod(addAllMethodName).last val listType = addAllMethod.tree.asInstanceOf[DefDef].paramss.head.params.head.asInstanceOf[ValDef].tpt.tpe val valueTree = toProto(iterableType, listType) Apply(Select(protoBuilderIdent, addAllMethod), List(valueTree)) } def mapTree(mapType: TypeRepr): Term = { - val putAllMethod = builderClassSymbol.memberMethod(putAllMethodName).head + val putAllMethod = builderClassSymbol.memberMethod(putAllMethodName).head val putAllMapType = putAllMethod.tree.asInstanceOf[DefDef].paramss.head.params.head.asInstanceOf[ValDef].tpt.tpe val valueTree = toProto(mapType, putAllMapType) Apply(Select(protoBuilderIdent, putAllMethod), List(valueTree)) @@ -126,13 +142,13 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q def defaultTree(fieldType: TypeRepr): Term = { val valueTree = toProto(fieldType, protoValueType) - val setFieldMethod = builderClassSymbol.memberMethod(setField).last + val setFieldMethod = builderClassSymbol.memberMethod(setField).last Apply(Select(protoBuilderIdent, setFieldMethod), List(valueTree)) } override def tree: Option[Term] = { if (protoValueType == TypeRepr.of[Unit]) { - None + None } else { val _tree = if (isOption(scalaTreeType)) { optTree(resolvedCaseClassFieldType) @@ -145,8 +161,8 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q } if (scalaTreeType <:< TypeRepr.of[AnyRef]) { - Some('{ - if(${scalaTree.asExprOf[AnyRef]} ne null) ${_tree.asExpr} + Some('{ + if (${ scalaTree.asExprOf[AnyRef] } ne null) ${ _tree.asExpr } }.asTerm) } else { Some(_tree) @@ -156,8 +172,7 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q } // Convert expr (`protoValueTree` in this class) to case class filed value - private case class ToScalaProcessor(caseClassSelector: Symbol, protoValueTree: Term, protoValueType: TypeRepr) - extends AbstractToScalaProcessor + private case class ToScalaProcessor(caseClassSelector: Symbol, protoValueTree: Term, protoValueType: TypeRepr) extends AbstractToScalaProcessor private trait AbstractToScalaProcessor extends Processor { @@ -165,14 +180,14 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q def protoValueTree: Term - override def scalaTreeType: TypeRepr = caseClassSelector.tree.asInstanceOf[ValDef].tpt.tpe + override def scalaTreeType: TypeRepr = caseClassSelector.tree.asInstanceOf[ValDef].tpt.tpe - protected def toScala(t1: TypeRepr, t2: TypeRepr, value: Term):Term = { + protected def toScala(t1: TypeRepr, t2: TypeRepr, value: Term): Term = { if (t2 <:< t1) { value } else { - val toScalaMethod = TypeRepr.of[Scalable[_,_]].typeSymbol.memberMethod("toScala").head - Apply(Select(implicitlyScalable(t1,t2),toScalaMethod),List(value)) + val toScalaMethod = TypeRepr.of[Scalable[_, _]].typeSymbol.memberMethod("toScala").head + Apply(Select(implicitlyScalable(t1, t2), toScalaMethod), List(value)) } } @@ -180,7 +195,8 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q def defaultTree(fieldType: TypeRepr): Term = { // q"$caseClassSelector = ${toScala(fieldType, protoValueType, protoValueTree)}" - Assign(caseClassSelector.tree.asInstanceOf[Term],toScala(fieldType,protoValueType,protoValueTree)) + toScala(fieldType, protoValueType, protoValueTree) +// Assign(caseClassSelector.tree.asInstanceOf[Term], toScala(fieldType,protoValueType,protoValueTree)) } override def tree: Option[Term] = @@ -198,7 +214,7 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q // Contain some methods and vals to analyze Protobuf fields private trait ProtoFieldAnalyst extends Processor { - def protoIdent:Ident + def protoIdent: Ident def protoFieldName: String @@ -215,11 +231,11 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q def protoValueTree: Term = { if (builderClassSymbol.memberMethod(addField).nonEmpty) { - Apply(Select(protoIdent,builderClassSymbol.memberMethod(getListField).head),Nil) + Apply(Select(protoIdent, builderClassSymbol.memberMethod(getListField).head), Nil) } else if (builderClassSymbol.memberMethod(putField).nonEmpty) { - Apply(Select(protoIdent,builderClassSymbol.memberMethod(getMapField).head),Nil) + Apply(Select(protoIdent, builderClassSymbol.memberMethod(getMapField).head), Nil) } else if (builderClassSymbol.memberMethod(setField).nonEmpty) { - Apply(Select(protoIdent,builderClassSymbol.memberMethod(getField).head),Nil) + Apply(Select(protoIdent, builderClassSymbol.memberMethod(getField).head), Nil) } else { '{}.asTerm } @@ -236,8 +252,10 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q Nil } val pbBuilderType = TypeRepr.of[com.google.protobuf.Message.Builder] - setters.map(_.tree.asInstanceOf[DefDef].paramss.head.params.head.asInstanceOf[ValDef].tpt.tpe) - .filterNot(_ <:< pbBuilderType).headOption + setters + .map(_.tree.asInstanceOf[DefDef].paramss.head.params.head.asInstanceOf[ValDef].tpt.tpe) + .filterNot(_ <:< pbBuilderType) + .headOption } lazy val protoValueGetterType: Option[TypeRepr] = { @@ -255,21 +273,19 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q } - // Convert scala clase class field value to protobuf value - private case class ToProtoFieldProcessor(scalaEntity:Ident,protoBuilderIdent:Ident,accessor: Symbol) + private case class ToProtoFieldProcessor(scalaEntity: Ident, protoBuilderIdent: Ident, accessor: Symbol) extends ToProtoProcessor( - protoBuilderIdent:Ident, - Select(scalaEntity,accessor), + protoBuilderIdent: Ident, + Select(scalaEntity, accessor), scalaClassType.memberType(accessor), - accessor.name.toString.capitalize) { + accessor.name.toString.capitalize + ) { override def protoIdent: ProtoScalableMacro.this.quotas.reflect.Ident = ??? } // Convert protobuf value to case class filed value - private case class ToScalaFieldProcessor(protoIdent:Ident, accessor: Symbol) - extends AbstractToScalaProcessor - with ProtoFieldAnalyst { + private case class ToScalaFieldProcessor(protoIdent: Ident, accessor: Symbol) extends AbstractToScalaProcessor with ProtoFieldAnalyst { override def caseClassSelector: Symbol = accessor @@ -282,14 +298,12 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q val hasProtoFieldMethod = protoClassSymbol.memberMethod(hasProtoField).headOption hasProtoFieldMethod match { case Some(method) => - val optExpr = '{ - if(${Apply(Select(protoIdent,method),Nil).asExprOf[Boolean]}) { - Some(${toScala(optType, protoValueType, protoValueTree).asExpr}) - } else { - None - } - } - Assign(accessor.tree.asInstanceOf[Term],optExpr.asTerm) + val AppliedType(_, typeArg :: Nil) = optType + If( + Apply(Select(protoIdent, method), Nil), + toScala(optType, protoValueType, protoValueTree), + '{ None }.asTerm + ) case None => defaultTree(optType) } } @@ -297,38 +311,31 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q private[this] def resolveFieldType(originType: TypeRepr): TypeRepr = { val typeTree = scalaClassType.typeSymbol.tree.asInstanceOf[TypeDef] -// println(quotas.reflect.TypeReprMethods.widen(originType)) -// println(typeTree.rhs) - - - -// val types = (entityType.typeSymbol.asType.typeParams zip entityType.typeArgs).toMap -// def resolve(tpe: Type): Type = { -// if (tpe.typeArgs.isEmpty) { -// types.getOrElse(tpe.typeSymbol, tpe) -// } else { -// appliedType(tpe.typeConstructor, tpe.typeArgs.map(resolve)) -// } -// } -// originType match { -// case t: Type if isOption(t) ⇒ -// appliedType(typeOf[Option[_]].typeConstructor, resolve(t.typeArgs.head)) -// case t: Type if isIterable(t) ⇒ -// appliedType(t.typeConstructor, resolve(t.typeArgs.head)) -// case t: Type if isMap(t) ⇒ -// appliedType(t.typeConstructor, resolve(t.typeArgs.head), resolve(t.typeArgs.last)) -// case t: Type ⇒ -// resolve(t) -// } - println(Printer.TreeAnsiCode.show(typeTree)) + val types = scalaClassType match { + case AppliedType(typeConstructor, args) => scalaClassType.typeSymbol.typeMembers.zip(args).toMap + case _ => Map.empty + } -// originType.asSeenFrom(entityType, entityType.typeSymbol.asClass) -// TypeReprMethods.asType(originType) -// originType.select(scalaClassSymbol) -// originType + def resolve(tpe: TypeRepr): TypeRepr = { + val typeMembers = tpe.typeSymbol.typeMembers + if (typeMembers.isEmpty) { + types.getOrElse(tpe.typeSymbol, tpe) + } else { + tpe match { + case AppliedType(typeConstructor, typeArgs) => + typeConstructor.appliedTo(typeArgs.map(resolve)) + case other => other + } + } + } - originType + originType match { + case AppliedType(tycon, args) ⇒ + tycon.appliedTo(args.map(resolve)) + case t: TypeRepr ⇒ + resolve(t) + } } private[this] def resolveType[T](using Type[T]): TypeRepr = { @@ -343,9 +350,9 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q quotas.reflect.SymbolMethods.caseFields(classSymbol) } - private[this] def defaultProtoableFieldConvertTrees(scalaEntity:Ident, protoBuilderIdent:Ident): List[Tuple2[String, Term]] = { + private[this] def defaultProtoableFieldConvertTrees(scalaEntity: Ident, protoBuilderIdent: Ident): List[Tuple2[String, Term]] = { getCaseAccessors().flatMap { a ⇒ - val p = ToProtoFieldProcessor(scalaEntity, protoBuilderIdent,a) + val p = ToProtoFieldProcessor(scalaEntity, protoBuilderIdent, a) p.tree.map(p.protoFieldName -> _) } } @@ -361,8 +368,8 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q ??? } - private def defalutScalableFieldConvertTrees(protoIdent:Ident): Map[String, Term] = { - getCaseAccessors().flatMap(accessor ⇒ ToScalaFieldProcessor(protoIdent,accessor).tree.map(accessor.name.toString -> _)).toMap + private def defalutScalableFieldConvertTrees(protoIdent: Ident): Map[String, Term] = { + getCaseAccessors().flatMap(accessor ⇒ ToScalaFieldProcessor(protoIdent, accessor).tree.map(accessor.name.toString -> _)).toMap } private def scalableBody(scalableFieldConvertTrees: Iterable[Tree]): Tree = { @@ -376,49 +383,51 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q ??? } - def scalasImpl: Expr[Scalable[T,M]] = { - scalasImpl(defalutScalableFieldConvertTrees(_).values, Nil) + def scalasImpl: Expr[Scalable[T, M]] = { + scalasImpl(defalutScalableFieldConvertTrees(_).values, Nil) } - private[this] def scalasImpl(scalableFieldConvertTrees: Ident => Iterable[Term], perTrees: Iterable[Tree]): Expr[Scalable[T,M]] = { -// q""" -// ..$perTrees -// new $packageName.Scalable[$caseClassType, $protoType] { ${scalableBody(caseClassType, protoType, scalableFieldConvertTrees)} } -// """ - + private[this] def scalasImpl(scalableFieldConvertTrees: Ident => Iterable[Term], perTrthemees: Iterable[Tree]): Expr[Scalable[T, M]] = { val res = '{ - new Scalable[T,M] { + new Scalable[T, M] { override def toScala(proto: M): T = ${ - val protoIdent = '{proto}.asTerm.asInstanceOf[Ident] - val x= scalableFieldConvertTrees(protoIdent) - x.foreach { t => -// println(Printer.TreeAnsiCode.show(t)) + val protoIdent = '{ proto }.asTerm.asInstanceOf[Ident] + val x = scalableFieldConvertTrees(protoIdent) + + val types = scalaClassType match { + case AppliedType(typeConstructor, args) => + args + case _ => + Nil } - New(TypeTree.of[T]).asExprOf[T] + + Apply(Select(scalaCompanionIdent, scalaClassApplySymbol).appliedToTypes(types), scalableFieldConvertTrees(protoIdent).toList).asExprOf[T] + // New(TypeTree.of[T]).asExprOf[T] } } } - quotas.show(res) + println(res.show) res } - private def protosImpl: Expr[Protoable[T,M]] = { - protosImpl((scalaEntityIdent, protoBuilderIdent) => defaultProtoableFieldConvertTrees(scalaEntityIdent, protoBuilderIdent).map(_._2), Nil) + private def protosImpl: Expr[Protoable[T, M]] = { + protosImpl((scalaEntityIdent, protoBuilderIdent) => defaultProtoableFieldConvertTrees(scalaEntityIdent, protoBuilderIdent).map(_._2)) } - - private[this] def protosImpl(protoableFieldConvertTrees:(Ident, Ident) => List[Term], perTrees: Iterable[Tree]): Expr[Protoable[T,M]] = { - '{ - new Protoable[T,M] { + private[this] def protosImpl(protoableFieldConvertTrees: (Ident, Ident) => List[Term]): Expr[Protoable[T, M]] = { + val result = '{ + new Protoable[T, M] { override def toProto(scalaEntity: T): M = ${ - val scalaEntityIdent = '{scalaEntity}.asTerm.asInstanceOf[Ident] - builderBuildeWithTerms(protoableFieldConvertTrees(scalaEntityIdent,_)).asExprOf[M] + val scalaEntityIdent = '{ scalaEntity }.asTerm.asInstanceOf[Ident] + builderBuildeWithTerms(protoableFieldConvertTrees(scalaEntityIdent, _)).asExprOf[M] } } } + println(result.show) + result } - def convertsImpl[T, M](using Type[T], Type[M]): Expr[ProtoScalable[T,M]] = { + def convertsImpl[T, M](using Type[T], Type[M]): Expr[ProtoScalable[T, M]] = { // q""" // new $packageName.ProtoScalable[${resolveType[T]}, ${resolveType[M]}] { // ${scalableBody(caseClassType, protoType, defalutScalableFieldConvertTrees(caseClassType, protoType).values)} @@ -428,27 +437,32 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q ??? } - private def buildProtoableImpl[T, M]: Tree = { -// val caseClassType = resolveType[T] -// val protoType = resolveType[M] -// val customTrees = MacroCache.builderFunctionTrees.getOrElse(getBuilderId(), mutable.Map.empty) -// val (fixedCustomTrees, preTrees) = customTrees.map { -// case (key, tree) ⇒ -// tree match { // setField -// case buildFunction: Function ⇒ -// val functionName = TermName("builderFunction$" + MacroCache.getIdentityId) -// val fromType = buildFunction.tpe.typeArgs.last // buildFunction 的返回值 -// val buildExpr = new ToProtoProcessor(q"$functionName($entityIdent)", fromType, caseClassType, protoType, key).tree.get -// (key -> buildExpr) -> q"val $functionName = $buildFunction" -// case value: Tree ⇒ // setFieldValue -// val identity = TermName("identity$" + MacroCache.getIdentityId) -// val buildExpr = new ToProtoProcessor(q"$identity", value.tpe, caseClassType, protoType, key).tree.get -// (key -> buildExpr) -> q"val $identity = $value" -// } -// }.unzip -// val protoableFieldConvertTrees = (defaultProtoableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values -// protosImpl(caseClassType, protoType, protoableFieldConvertTrees, preTrees) - ??? + private def buildProtoableImpl: Expr[Protoable[T, M]] = { + val customTrees = MacroCache.builderFunctionTrees.getOrElse(getBuilderId(), mutable.Map.empty) + def getCustomTrees(scalaIdent: Ident, protoBuilderIdent: Ident): Map[String, Term] = customTrees.map { case (key, tree) ⇒ + tree match { // setField + case buildFunction: Expr[Any => Any] if buildFunction.isExprOf[_ => _] ⇒ + val functionName = "builderFunction$" + MacroCache.getIdentityId + // val fromType = buildFunction.tpe.typeArgs.last // buildFunction 的返回值 + // val buildExpr = new ToProtoProcessor(q"$functionName($entityIdent)", fromType, caseClassType, protoType, key).tree.get + val tree = buildFunction.asTerm + val valDef = ValDef(Symbol.newVal(Symbol.spliceOwner, functionName, tree.tpe, Flags.EmptyFlags, Symbol.noSymbol), Some(tree)) + // val applied = Apply(Select.unique(Ref(valDef.symbol), "apply"), List(scalaIdent)) + val applied = Apply(Select.unique(tree, "apply"), List(scalaIdent)) + val buildExpr = new ToProtoProcessor(protoBuilderIdent, applied, applied.tpe, key).tree.get + + (key -> buildExpr) + // case value: Tree ⇒ // setFieldValue + // val identity = TermName("identity$" + MacroCache.getIdentityId) + // val buildExpr = new ToProtoProcessor(q"$identity", value.tpe, caseClassType, protoType, key).tree.get + // (key -> buildExpr) -> q"val $identity = $value" + } + }.toMap + // val protoableFieldConvertTrees = (defaultProtoableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values + protosImpl({ (scalaIdent, protoBuilderIdent) => + val terms = getCustomTrees(scalaIdent, protoBuilderIdent) + (defaultProtoableFieldConvertTrees(scalaIdent, protoBuilderIdent) ++ terms).toMap.values.toList + }) } private def buildScalableImpl[T, M]: Tree = { @@ -486,27 +500,26 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q ??? } - private def setProtoFieldImpl[T, M, TF, MF](protoFieldSelector: Tree, value: Tree): Tree = { -// val getter = "^get(\\w+)$".r -// val listGetter = "^get(\\w+)List$".r -// val mapGetter = "^get(\\w+)Map$".r -// val setter = protoFieldSelector.find { -// case _: Select ⇒ true -// case _: Tree ⇒ false -// } match { -// case Some(select: Select) ⇒ -// select.name.toString match { -// case mapGetter(n) if select.tpe.resultType <:< typeOf[java.util.Map[_, _]] ⇒ n -// case listGetter(n) if select.tpe.resultType <:< typeOf[java.util.List[_]] ⇒ n -// case getter(n) ⇒ n -// case _ ⇒ c.abort(protoFieldSelector.pos, "Invalid setter") -// } -// case _ ⇒ c.abort(protoFieldSelector.pos, "Invalid setter") -// } -// val builderId = getBuilderId() -// MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(setter, value) -// q"new ${c.prefix.actualType}" - ??? + private def setProtoFieldImpl[TF: Type, MF: Type](protoFieldSelector: Expr[M ⇒ MF], value: Expr[T ⇒ TF]): Expr[ProtoableBuilder[T, M]] = { + val getter = "^get(\\w+)$".r + val listGetter = "^get(\\w+)List$".r + val mapGetter = "^get(\\w+)Map$".r + val setter = protoFieldSelector.asTerm match { + case Inlined(_, _, Inlined(_, _, Block(List(DefDef(_, _, _, Some(Apply(Select(qualifier, symbolName), _)))), _))) => + symbolName match { + case mapGetter(n) if TypeRepr.of[MF] <:< TypeRepr.of[java.util.Map[_, _]] ⇒ n + case listGetter(n) if TypeRepr.of[MF] <:< TypeRepr.of[java.util.List[_]] ⇒ n + case getter(n) ⇒ n + case _ => report.errorAndAbort("Invalid setter") + } + case _ => report.errorAndAbort("Invalid setter") + } + + val builderId = Symbol.spliceOwner.owner.fullName + MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(setter, value) + // New.apply(TypeTree.of[BLD]).asExprOf[BLD] + // println(TypeRepr.of[BLD]) + protoableBuilderApply } val annoBuilderPrefix = "AnonBuilder$" @@ -520,36 +533,61 @@ class ProtoScalableMacro[T,M](using typeT:Type[T], typeM:Type[M])(using quotas:Q ??? } - private def protoableBuilderApply[T, M]: Tree = { -// val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) -// q""" -// class $className extends $packageName.ProtoableBuilder[${resolveType[T]}, ${resolveType[M]}] -// new $className -// """ - ??? + private def protoableBuilderApply: Expr[ProtoableBuilder[T, M]] = { + '{ ProtoableBuilder._default.asInstanceOf[ProtoableBuilder[T, M]] } } - private[this] def getBuilderId() = { -// c.prefix.actualType.toString.replace(annoBuilderPrefix, "").toInt - quotas.reflect.Position.ofMacroExpansion + private[this] def getBuilderId(): String = { + Symbol.spliceOwner.owner.fullName } } - object ProtoScalableMacro { - inline def protoable[T,M]:Protoable[T,M] = ${protosImpl[T,M]} + inline def protoable[T, M <: Message]: Protoable[T, M] = ${ protosImpl[T, M] } - def protosImpl[T,M](using t:Type[T], m:Type[M],quotes: Quotes):Expr[Protoable[T,M]] = { + def protosImpl[T, M <: Message](using t: Type[T], m: Type[M], quotes: Quotes): Expr[Protoable[T, M]] = { val protoScalableMacro = new ProtoScalableMacro(using t, m) protoScalableMacro.protosImpl } - inline def scalable[T,M]:Scalable[T,M] = ${scalasImpl[T,M]} + inline def protoableBuilder[T, M <: Message]: ProtoableBuilder[T, M] = ${ protoableBuilderImpl[T, M] } - def scalasImpl[T,M](using t:Type[T], m:Type[M],quotes: Quotes):Expr[Scalable[T,M]] = { + def protoableBuilderImpl[T, M <: Message](using t: Type[T], m: Type[M], quotes: Quotes): Expr[ProtoableBuilder[T, M]] = { + val protoScalableMacro = new ProtoScalableMacro(using t, m) + protoScalableMacro.protoableBuilderApply + } + + inline def protoableBuilderSetField[T, M <: Message, MF, TF](inline protoFieldSelector: M ⇒ MF, inline value: T ⇒ TF): ProtoableBuilder[T, M] = + ${ protoableBuilderSetFieldImpl[T, M, MF, TF]('protoFieldSelector, 'value) } + + def protoableBuilderSetFieldImpl[T: Type, M <: Message: Type, MF: Type, TF: Type](protoFieldSelector: Expr[M ⇒ MF], value: Expr[T ⇒ TF])(using + quotes: Quotes + ): Expr[ProtoableBuilder[T, M]] = { + val protoScalableMacro = new ProtoScalableMacro[T, M] + protoScalableMacro.setProtoFieldImpl[TF, MF](protoFieldSelector, value) + } + + inline def scalableBuilder[T, M <: Message]: ScalableBuilder[T, M] = ${ scalableBuilderImpl[T, M] } + + def scalableBuilderImpl[T: Type, M <: Message: Type](using t: Type[T], m: Type[M], quotes: Quotes): Expr[ScalableBuilder[T, M]] = { + val protoScalableMacro = new ProtoScalableMacro(using t, m) + ??? + } + + inline def buildProtoable[T, M <: Message]: Protoable[T, M] = + ${ buildProtoableImpl[T, M] } + + def buildProtoableImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[Protoable[T, M]] = { + val protoScalableMacro = new ProtoScalableMacro[T, M] + protoScalableMacro.buildProtoableImpl + } + + inline def scalable[T, M <: Message]: Scalable[T, M] = ${ scalasImpl[T, M] } + + def scalasImpl[T, M <: Message](using t: Type[T], m: Type[M], quotes: Quotes): Expr[Scalable[T, M]] = { val protoScalableMacro = new ProtoScalableMacro(using t, m) protoScalableMacro.scalasImpl } -} \ No newline at end of file +} diff --git a/pbconverts/src/main/scala/pbconverts/Protoable.scala b/pbconverts/src/main/scala/pbconverts/Protoable.scala index d35e2cc..8230106 100644 --- a/pbconverts/src/main/scala/pbconverts/Protoable.scala +++ b/pbconverts/src/main/scala/pbconverts/Protoable.scala @@ -12,7 +12,7 @@ trait Protoable[-T, +M] { object Protoable { - inline def apply[T <: Product, M <: GeneratedMessageV3 with MessageOrBuilder]: Protoable[T, M] = + inline def apply[T <: Product, M <: GeneratedMessageV3 with MessageOrBuilder]: Protoable[T, M] = ProtoScalableMacro.protoable[T, M] def apply[T, M](f: T ⇒ M): Protoable[T, M] = @@ -27,18 +27,18 @@ object Protoable { given Protoable[Char, java.lang.Character] = Protoable(_.toChar) given Protoable[Byte, java.lang.Byte] = Protoable(_.toByte) - given Protoable[String, StringValue]= Protoable(StringValue.of) - given Protoable[Double, DoubleValue]= Protoable(DoubleValue.of) - given Protoable[Float, FloatValue]= Protoable(FloatValue.of) - given Protoable[Int, Int32Value]= Protoable(Int32Value.of) - given Protoable[Boolean, BoolValue]= Protoable(BoolValue.of) - given Protoable[Long, Int64Value]= Protoable(Int64Value.of) + given Protoable[String, StringValue] = Protoable(StringValue.of) + given Protoable[Double, DoubleValue] = Protoable(DoubleValue.of) + given Protoable[Float, FloatValue] = Protoable(FloatValue.of) + given Protoable[Int, Int32Value] = Protoable(Int32Value.of) + given Protoable[Boolean, BoolValue] = Protoable(BoolValue.of) + given Protoable[Long, Int64Value] = Protoable(Int64Value.of) given Protoable[ZonedDateTime, Timestamp] = Protoable { entity ⇒ Timestamp.newBuilder().setSeconds(entity.toEpochSecond).setNanos(entity.getNano).build() } - given [T, M](using protoable: Protoable[T, M]): Protoable[scala.Iterable[T], java.util.List[M]] = + given [T, M](using protoable: Protoable[T, M]): Protoable[scala.Iterable[T], java.util.List[M]] = Protoable[scala.Iterable[T], java.util.List[M]] { entity ⇒ entity.toList.map(protoable.toProto).asJava } @@ -46,33 +46,33 @@ object Protoable { given [T]: Protoable[scala.Iterable[T], java.util.List[T]] = Protoable[scala.Iterable[T], java.util.List[T]] { entity ⇒ entity.toList.asJava } - given[T]: Protoable[Array[T], java.util.List[T]] = + given [T]: Protoable[Array[T], java.util.List[T]] = Protoable[Array[T], java.util.List[T]] { entity ⇒ entity.toList.asJava } - given[T, M](using protoable: Protoable[T, M]): Protoable[Array[T], java.lang.Iterable[M]] = + given [T, M](using protoable: Protoable[T, M]): Protoable[Array[T], java.lang.Iterable[M]] = Protoable[Array[T], java.util.List[M]] { entity ⇒ entity.toList.map(protoable.toProto).asJava } - given[F, Target <: Any](using protoable: Protoable[F, Target]): Protoable[Option[F], Target] = + given [F, Target <: Any](using protoable: Protoable[F, Target]): Protoable[Option[F], Target] = Protoable[Option[F], Target] { (entity: Option[F]) ⇒ entity.map(protoable.toProto).getOrElse(None.orNull.asInstanceOf[Target]) } - given[T]: Protoable[Option[T], T] = + given [T]: Protoable[Option[T], T] = Protoable[Option[T], T] { (opt: Option[T]) => opt.getOrElse(None.orNull.asInstanceOf[T]) } - given[K, V]: Protoable[Map[K, V], java.util.Map[K, V]] = + given [K, V]: Protoable[Map[K, V], java.util.Map[K, V]] = Protoable[Map[K, V], java.util.Map[K, V]] { m ⇒ m.asJava } @targetName("for key mapping") - given[K1, K2, V](using kProtoable: Protoable[K1, K2]): Protoable[Map[K1, V], java.util.Map[K2, V]] = + given [K1, K2, V](using kProtoable: Protoable[K1, K2]): Protoable[Map[K1, V], java.util.Map[K2, V]] = Protoable[Map[K1, V], java.util.Map[K2, V]] { m ⇒ m.map { case (k, v) ⇒ kProtoable.toProto(k) -> v }.asJava } - given[K, V1, V2](using vProtoable: Protoable[V1, V2]): Protoable[Map[K, V1], java.util.Map[K, V2]] = + given [K, V1, V2](using vProtoable: Protoable[V1, V2]): Protoable[Map[K, V1], java.util.Map[K, V2]] = Protoable[Map[K, V1], java.util.Map[K, V2]] { m ⇒ m.map { case (k, v) ⇒ k -> vProtoable.toProto(v) }.asJava } - given[K1, K2, V1, V2](using + given [K1, K2, V1, V2](using kProtoable: Protoable[K1, K2], vProtoable: Protoable[V1, V2] ): Protoable[Map[K1, V1], java.util.Map[K2, V2]] = diff --git a/pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala b/pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala index 2af409d..fcb1026 100644 --- a/pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala +++ b/pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala @@ -4,13 +4,15 @@ import com.google.protobuf.Message class ProtoableBuilder[T, M <: Message]() { - def setField[TF, MF](protoFieldSelector: M ⇒ MF, value: T ⇒ TF): this.type = ??? //macro ProtoScalableMacro.setProtoFieldImpl[T, M, TF, MF] + inline def setField[TF, MF](inline protoFieldSelector: M ⇒ MF, inline value: T ⇒ TF): ProtoableBuilder[T, M] = + ProtoScalableMacro.protoableBuilderSetField[T, M, MF, TF](protoFieldSelector, value) - def setFieldValue[TF, MF](protoFieldSelector: M ⇒ MF, value: TF): this.type = ??? //macro ProtoScalableMacro.setProtoFieldImpl[T, M, TF, MF] + def setFieldValue[TF, MF](protoFieldSelector: M ⇒ MF, value: TF): this.type = ??? // macro ProtoScalableMacro.setProtoFieldImpl[T, M, TF, MF] - def build: Protoable[T, M] = ??? //macro ProtoScalableMacro.buildProtoableImpl[T, M] + inline def build: Protoable[T, M] = ProtoScalableMacro.buildProtoable[T, M] } object ProtoableBuilder { - def apply[T, M <: Message]: ProtoableBuilder[T, M] = ??? //macro ProtoScalableMacro.protoableBuilderApply[T, M] + val _default = new ProtoableBuilder[Nothing, Nothing] + inline def apply[T, M <: Message]: ProtoableBuilder[T, M] = ProtoScalableMacro.protoableBuilder[T, M] } diff --git a/pbconverts/src/main/scala/pbconverts/Scalable.scala b/pbconverts/src/main/scala/pbconverts/Scalable.scala index a65c8f8..eb86f71 100644 --- a/pbconverts/src/main/scala/pbconverts/Scalable.scala +++ b/pbconverts/src/main/scala/pbconverts/Scalable.scala @@ -6,6 +6,7 @@ import com.google.protobuf.{BoolValue, DoubleValue, FloatValue, Int32Value, Int6 import scala.collection.JavaConverters._ import scala.concurrent.ExecutionContext import scala.reflect.ClassTag +import com.google.protobuf.Message trait Scalable[+T, -M] { def toScala(proto: M): T @@ -13,7 +14,7 @@ trait Scalable[+T, -M] { object Scalable extends ScalableImplicits { - inline def apply[T <: Product, M]: Scalable[T, M] = ProtoScalableMacro.scalable[T, M] + inline def apply[T <: Product, M <: Message]: Scalable[T, M] = ProtoScalableMacro.scalable[T, M] def apply[T, M](convert: M ⇒ T): Scalable[T, M] = new Scalable[T, M] { @@ -28,21 +29,21 @@ object Scalable extends ScalableImplicits { given Scalable[Double, java.lang.Double] = Scalable(_.toDouble) given Scalable[Float, java.lang.Float] = Scalable(_.toFloat) given Scalable[Char, java.lang.Character] = Scalable(_.toChar) - given javaByteScalable:Scalable[Byte, java.lang.Byte] = Scalable(_.toByte) + given javaByteScalable: Scalable[Byte, java.lang.Byte] = Scalable(_.toByte) - given Scalable [String, StringValue] = Scalable (_.getValue) - given Scalable [Int, Int32Value] = Scalable(_.getValue) - given Scalable [Long, Int64Value] = Scalable(_.getValue) - given Scalable [Double, DoubleValue] = Scalable(_.getValue) - given Scalable [Float, FloatValue] = Scalable(_.getValue) - given Scalable [Boolean, BoolValue] = Scalable(_.getValue) + given Scalable[String, StringValue] = Scalable(_.getValue) + given Scalable[Int, Int32Value] = Scalable(_.getValue) + given Scalable[Long, Int64Value] = Scalable(_.getValue) + given Scalable[Double, DoubleValue] = Scalable(_.getValue) + given Scalable[Float, FloatValue] = Scalable(_.getValue) + given Scalable[Boolean, BoolValue] = Scalable(_.getValue) given Scalable[ZonedDateTime, Timestamp] = Scalable { proto ⇒ Instant.ofEpochSecond(proto.getSeconds, proto.getNanos).atZone(ZoneId.systemDefault()) } - //java.lang.Iterable[M] => Array[T] - given [T:ClassTag,M](using scalable:Scalable[T, M]):Scalable[Array[T], java.lang.Iterable[M]] = + // java.lang.Iterable[M] => Array[T] + given [T: ClassTag, M](using scalable: Scalable[T, M]): Scalable[Array[T], java.lang.Iterable[M]] = Scalable { proto ⇒ proto.asScala.map(scalable.toScala).toArray } @@ -55,6 +56,6 @@ object Scalable extends ScalableImplicits { Option(scalable.toScala(proto)) } - given [T]: Scalable[Option[T], T] = Scalable(Option(_)) + given [T]: Scalable[Option[T], T] = Scalable(Option(_)) } diff --git a/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala b/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala index 8a9003b..f2cced3 100644 --- a/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala +++ b/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala @@ -1,14 +1,16 @@ package pbconverts +import com.google.protobuf.Message + class ScalableBuilder[+T, M]() { - def setField[TF, MF](scalaField: T ⇒ TF, value: M ⇒ MF): ScalableBuilder[T, M] = ??? //macro ProtoScalableMacro.setScalaFieldImpl[T, M, TF, MF] + def setField[TF, MF](scalaField: T ⇒ TF, value: M ⇒ MF): ScalableBuilder[T, M] = ??? // macro ProtoScalableMacro.setScalaFieldImpl[T, M, TF, MF] - def setFieldValue[TF, MF](scalaField: T ⇒ TF, value: MF): ScalableBuilder[T, M] = ??? //macro ProtoScalableMacro.setScalaFieldImpl[T, M, TF, MF] + def setFieldValue[TF, MF](scalaField: T ⇒ TF, value: MF): ScalableBuilder[T, M] = ??? // macro ProtoScalableMacro.setScalaFieldImpl[T, M, TF, MF] def build: Scalable[T, M] = ??? // macro ProtoScalableMacro.buildScalableImpl[T, M] } object ScalableBuilder { - def apply[T, M]: ScalableBuilder[T, M] = ??? //macro ProtoScalableMacro.scalableBuilderApply[T, M] + inline def apply[T, M <: Message]: ScalableBuilder[T, M] = ProtoScalableMacro.scalableBuilder[T, M] } diff --git a/pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala b/pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala index 003bf46..f581fc9 100644 --- a/pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala +++ b/pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala @@ -9,7 +9,7 @@ import scala.reflect.ClassTag trait ScalableImplicits { // java.lang.Iterable[M] => That[T] - given[That[_], T, M](using scalable: Scalable[T, M], bf: BuildFrom[Seq[_], T, That[T]]): Scalable[That[T], java.lang.Iterable[M]] = + given [That[_], T, M](using scalable: Scalable[T, M], bf: BuildFrom[Seq[_], T, That[T]]): Scalable[That[T], java.lang.Iterable[M]] = Scalable { proto ⇒ bf.fromSpecific(Seq.empty)(proto.asScala.iterator.map(scalable.toScala)) } @@ -20,7 +20,7 @@ trait ScalableImplicits { } // // Repr[M] => That[T] - given[That, Repr <: Iterable[M], T, M](using + given [That, Repr <: Iterable[M], T, M](using scalable: Scalable[T, M], bf: BuildFrom[Iterable[_], T, That] ): Scalable[That, Repr] = { proto ⇒ diff --git a/pbconverts/src/main/scala/pbconverts/Test.scala b/pbconverts/src/main/scala/pbconverts/Test.scala index 0cbd5ae..badc1fd 100644 --- a/pbconverts/src/main/scala/pbconverts/Test.scala +++ b/pbconverts/src/main/scala/pbconverts/Test.scala @@ -1,8 +1,7 @@ package pbconverts -object Test { +object Test { given Int = 1 implicitly[Int].toString } - diff --git a/pbconverts/src/test/scala/pbconverts/MapSpec.scala b/pbconverts/src/test/scala/pbconverts/MapSpec.scala index 0d29c13..58d7cc4 100644 --- a/pbconverts/src/test/scala/pbconverts/MapSpec.scala +++ b/pbconverts/src/test/scala/pbconverts/MapSpec.scala @@ -1,35 +1,37 @@ package pbconverts import com.google.protobuf.ByteString -import org.scalatest.funsuite.AnyFunSuite +// import org.scalatest.funsuite.AnyFunSuite import ConversionTest.{PBTestBytes, PBTestMessage} +import org.scalatest.funsuite.AnyFunSuite class MapSpec extends AnyFunSuite { - test("test map") { - val testMessage = TestMessage.default - - val pbTestMessage: PBTestMessage = Protoable[TestMessage, PBTestMessage].toProto(testMessage) - assert(pbTestMessage.getIntValue == testMessage.intValue) - assert(pbTestMessage.getLongIntKVOrThrow(1L) == 1) - assert(pbTestMessage.getLongStringKVOrThrow(1L) == "string1") - assert(pbTestMessage.getStringIntKVOrThrow("string1") == 1) - assert(pbTestMessage.getStringStringKVOrThrow("string1") == "string1") - } + // test("test map") { + // val testMessage = TestMessage.default + + // val pbTestMessage: PBTestMessage = Protoable[TestMessage, PBTestMessage].toProto(testMessage) + // assert(pbTestMessage.getIntValue == testMessage.intValue) + // assert(pbTestMessage.getLongIntKVOrThrow(1L) == 1) + // assert(pbTestMessage.getLongStringKVOrThrow(1L) == "string1") + // assert(pbTestMessage.getStringIntKVOrThrow("string1") == 1) + // assert(pbTestMessage.getStringStringKVOrThrow("string1") == "string1") + // } + + case class TestBytes(m: Map[String, Int]) -// case class TestBytes(m: Map[String, Int]) -// test("test conversion between bytes in protobuf and Map in case class") { -// val pbTest1 = ProtoableBuilder[TestBytes, PBTestBytes] -// .setField(_.getTestBytes, x => ByteString.copyFromUtf8(x.m.keys.mkString(","))) -// .build -// .toProto(TestBytes(Map("test" -> 1, "bytes" -> 1))) -// -// assert(pbTest1.getTestBytes.toStringUtf8 == "test,bytes") -// -// val test = ScalableBuilder[TestBytes, PBTestBytes] -// .setField(_.m, _.getTestBytes.toStringUtf8.split(",").map(_ -> 1).toMap) -// .build -// .toScala(PBTestBytes.newBuilder().setTestBytes(ByteString.copyFromUtf8("test,bytes")).build()) -// -// assert(test.m == Map("test" -> 1, "bytes" -> 1)) -// } + test("test conversion between bytes in protobuf and Map in case class") { + val pbTest1 = ProtoableBuilder[TestBytes, PBTestBytes] + .setField(_.getTestBytes, x => ByteString.copyFromUtf8(x.m.keys.mkString(","))) + .build + .toProto(TestBytes(Map("test" -> 1, "bytes" -> 1))) + + assert(pbTest1.getTestBytes.toStringUtf8 == "test,bytes") + + // val test = ScalableBuilder[TestBytes, PBTestBytes] + // .setField(_.m, _.getTestBytes.toStringUtf8.split(",").map(_ -> 1).toMap) + // .build + // .toScala(PBTestBytes.newBuilder().setTestBytes(ByteString.copyFromUtf8("test,bytes")).build()) + + // assert(test.m == Map("test" -> 1, "bytes" -> 1)) + } } diff --git a/pbconverts/src/test/scala/pbconverts/ScalableSpec.scala b/pbconverts/src/test/scala/pbconverts/ScalableSpec.scala index 5581143..db6730a 100644 --- a/pbconverts/src/test/scala/pbconverts/ScalableSpec.scala +++ b/pbconverts/src/test/scala/pbconverts/ScalableSpec.scala @@ -1,60 +1,61 @@ -// package pbconverts - -// import com.google.protobuf.StringValue -// import org.scalatest.funsuite.AnyFunSuite -// import pbconverts.ConversionTest.{IntMessage, PBPerson} - -// class ScalableSpec extends AnyFunSuite { -// test("Scalable") { -// // val person = Person(1L, "person name", Some("123456"), Seq("play games", "sing song")) - -// // val builder = PBPerson.newBuilder() -// // builder.setId(1L) -// // builder.setName("person name") -// // builder.setPhone(StringValue.of("123456")) -// // builder.addHobbies("play games") -// // builder.addHobbies("sing song") -// // val personDto = builder.build() - -// // val person1 = Person( -// // personDto.getId, -// // personDto.getName, -// // if (personDto.hasPhone) Some(personDto.getPhone.getValue) else None, -// // scala.collection.JavaConverters.iterableAsScalaIterable(personDto.getHobbiesList).toSeq -// // ) - -// // val person2 = Scalable[Person, PBPerson].toScala(builder.build()) - -// // assert(person1 == person2) -// } - -// // test("type alias") { -// // val pbPerson = PBPerson.newBuilder().setId(1L).build() -// // -// // locally { -// // type PPP = Person -// // val p = Scalable[PPP, PBPerson].toScala(pbPerson) -// // assert(p.id == 1L) -// // } -// // -// // locally { -// // type PBP = PBPerson -// // val p = Scalable[Person, PBP].toScala(pbPerson) -// // assert(p.id == 1L) -// // } -// // -// // locally { -// // type PPP = Person -// // type PBP = PBPerson -// // val p = Scalable[PPP, PBP].toScala(pbPerson) -// // assert(p.id == 1L) -// // } -// // -// // locally { -// // type IM = IntMessage -// // type MTI = MessageWithType[Int] -// // val p = Scalable[MTI, IM].toScala(IntMessage.newBuilder().setValue(1).build()) -// // assert(p.value == 1L) -// // } -// // } -// } +package pbconverts + +import com.google.protobuf.StringValue +import org.scalatest.funsuite.AnyFunSuite +import pbconverts.ConversionTest.{IntMessage, PBPerson} + +class ScalableSpec extends AnyFunSuite { + + test("Scalable") { + val person = Person(1L, "person name", Some("123456"), Seq("play games", "sing song")) + + val builder = PBPerson.newBuilder() + builder.setId(1L) + builder.setName("person name") + builder.setPhone(StringValue.of("123456")) + builder.addHobbies("play games") + builder.addHobbies("sing song") + val personDto = builder.build() + + val person1 = Person( + personDto.getId, + personDto.getName, + if (personDto.hasPhone) Some(personDto.getPhone.getValue) else None, + scala.collection.JavaConverters.iterableAsScalaIterable(personDto.getHobbiesList).toSeq + ) + + val person2 = Scalable[Person, PBPerson].toScala(builder.build()) + + assert(person1 == person2) + } + + test("type alias") { + val pbPerson = PBPerson.newBuilder().setId(1L).build() + + locally { + type PPP = Person + val p = Scalable[PPP, PBPerson].toScala(pbPerson) + assert(p.id == 1L) + } + + locally { + type PBP = PBPerson + val p = Scalable[Person, PBP].toScala(pbPerson) + assert(p.id == 1L) + } + + locally { + type PPP = Person + type PBP = PBPerson + val p = Scalable[PPP, PBP].toScala(pbPerson) + assert(p.id == 1L) + } + + locally { + type IM = IntMessage + type MTI = MessageWithType[Int] + val p = Scalable[MTI, IM].toScala(IntMessage.newBuilder().setValue(1).build()) + assert(p.value == 1L) + } + } +} diff --git a/pbconverts/src/test/scala/pbconverts/TestMain.scala b/pbconverts/src/test/scala/pbconverts/TestMain.scala new file mode 100644 index 0000000..e13815e --- /dev/null +++ b/pbconverts/src/test/scala/pbconverts/TestMain.scala @@ -0,0 +1,19 @@ +package pbconverts + +import ConversionTest.PBTestMessage +import ConversionTest.StringMessage + +object TestMain extends App { + + // val testMessage = TestMessage.default + // val pbTestMessage: PBTestMessage = Protoable[TestMessage, PBTestMessage].toProto(testMessage) + // println(pbTestMessage.getIntValue) + + val stringMessage = MessageWithType("test") + // val x = Protoable[MessageWithType[String], StringMessage].toProto(stringMessage) + val x = StringMessage.newBuilder.setValue("Test").build + val y = Scalable[MessageWithType[String], StringMessage].toScala(x) + + println(x.getValue) + // println(y) +} diff --git a/pbconverts/src/test/scala/pbconverts/TestMessage.scala b/pbconverts/src/test/scala/pbconverts/TestMessage.scala index 2f2db1b..1f95c3c 100644 --- a/pbconverts/src/test/scala/pbconverts/TestMessage.scala +++ b/pbconverts/src/test/scala/pbconverts/TestMessage.scala @@ -3,80 +3,80 @@ package pbconverts import java.time.ZonedDateTime case class TestMessage( - intValue: Int, - longValue: Long, - floatValue: Float, - doubleValue: Double, - boolValue: Boolean, - stringValue: String, - intOpt: Option[Int], - longOpt: Option[Long], - floatOpt: Option[Float], - doubleOpt: Option[Double], - boolOpt: Option[Boolean], - stringOpt: Option[String], - time: ZonedDateTime, - timeOpt: Option[ZonedDateTime], - intArray: Array[Int], - stringArray: Array[String], + intValue: Int, + longValue: Long, + floatValue: Float, + doubleValue: Double, + boolValue: Boolean, + stringValue: String, + intOpt: Option[Int], + longOpt: Option[Long], + floatOpt: Option[Float], + doubleOpt: Option[Double], + boolOpt: Option[Boolean], + stringOpt: Option[String], + time: ZonedDateTime, + timeOpt: Option[ZonedDateTime], + intArray: Array[Int], + stringArray: Array[String], // personArray: Array[Person], - seq: Seq[Double], - stringStringKV: Map[String, String], // not convert k or v - longStringKV: Map[Long, String], // convert k, but not v - stringIntKV: Map[String, Int], // convert v, but not k - longIntKV: Map[Long, Int] // convert k and v - ) + seq: Seq[Double], + stringStringKV: Map[String, String], // not convert k or v + longStringKV: Map[Long, String], // convert k, but not v + stringIntKV: Map[String, Int], // convert v, but not k + longIntKV: Map[Long, Int] // convert k and v +) object TestMessage { - def default = - TestMessage( - intValue = 64, - longValue = 128, - floatValue = 256.0f, - doubleValue = 512.0, - boolValue = true, - stringValue = "stringValue", - intOpt = Some(64), - longOpt = Some(128), - floatOpt = Some(256.0f), - doubleOpt = Some(512.0), - boolOpt = Some(true), - stringOpt = Some("stringValue"), - time = ZonedDateTime.now(), - timeOpt = Some(ZonedDateTime.now()), - intArray = Array(100, 200, 300), - stringArray = Array("string1", "string2", "string3"), + def default = + TestMessage( + intValue = 64, + longValue = 128, + floatValue = 256.0f, + doubleValue = 512.0, + boolValue = true, + stringValue = "stringValue", + intOpt = Some(64), + longOpt = Some(128), + floatOpt = Some(256.0f), + doubleOpt = Some(512.0), + boolOpt = Some(true), + stringOpt = Some("stringValue"), + time = ZonedDateTime.now(), + timeOpt = Some(ZonedDateTime.now()), + intArray = Array(100, 200, 300), + stringArray = Array("string1", "string2", "string3"), // personArray = Array(Person.default), - seq = Seq(1.0, 2.0, 3.0), - stringStringKV = Map("string1" -> "string1", "string2" -> "string2"), - longStringKV = Map(1L -> "string1", 2L -> "string2"), - stringIntKV = Map("string1" -> 1, "string2" -> 2), - longIntKV = Map(1L -> 1, 2L -> 2) - ) + seq = Seq(1.0, 2.0, 3.0), + stringStringKV = Map("string1" -> "string1", "string2" -> "string2"), + longStringKV = Map(1L -> "string1", 2L -> "string2"), + stringIntKV = Map("string1" -> 1, "string2" -> 2), + longIntKV = Map(1L -> 1, 2L -> 2) + ) - def zero: TestMessage = - TestMessage( - intValue = 0, - longValue = 0, - floatValue = 0f, - doubleValue = 0.0, - boolValue = false, - stringValue = "", - intOpt = None, - longOpt = None, - floatOpt = None, - doubleOpt = None, - boolOpt = None, - stringOpt = None, - time = ZonedDateTime.now(), - timeOpt = None, - intArray = Array.empty, - stringArray = Array.empty, + def zero: TestMessage = + TestMessage( + intValue = 0, + longValue = 0, + floatValue = 0f, + doubleValue = 0.0, + boolValue = false, + stringValue = "", + intOpt = None, + longOpt = None, + floatOpt = None, + doubleOpt = None, + boolOpt = None, + stringOpt = None, + time = ZonedDateTime.now(), + timeOpt = None, + intArray = Array.empty, + stringArray = Array.empty, // personArray = Array.empty, - seq = Seq.empty, - stringStringKV = Map.empty, - longStringKV = Map.empty, - stringIntKV = Map.empty, - longIntKV = Map.empty - ) -} \ No newline at end of file + seq = Seq.empty, + stringStringKV = Map.empty, + longStringKV = Map.empty, + stringIntKV = Map.empty, + longIntKV = Map.empty + ) +} diff --git a/version.sbt b/version.sbt index 9f4bd1e..c609dc0 100644 --- a/version.sbt +++ b/version.sbt @@ -1 +1 @@ -version in ThisBuild := "0.2.0" +ThisBuild / version := "0.2.0" From a85ee91d78dd3cac1b84048579f7662272948967 Mon Sep 17 00:00:00 2001 From: changvvb Date: Fri, 17 Dec 2021 17:55:25 +0800 Subject: [PATCH 07/17] update --- .../scala/pbconverts/ProtoScalableMacro.scala | 101 ++++++++++-------- .../scala/pbconverts/ScalableBuilder.scala | 8 +- .../src/test/scala/pbconverts/MapSpec.scala | 30 +++--- 3 files changed, 77 insertions(+), 62 deletions(-) diff --git a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala index 3853c38..8b4df19 100644 --- a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala +++ b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala @@ -384,10 +384,10 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( } def scalasImpl: Expr[Scalable[T, M]] = { - scalasImpl(defalutScalableFieldConvertTrees(_).values, Nil) + scalasImpl(defalutScalableFieldConvertTrees(_).values) } - private[this] def scalasImpl(scalableFieldConvertTrees: Ident => Iterable[Term], perTrthemees: Iterable[Tree]): Expr[Scalable[T, M]] = { + private[this] def scalasImpl(scalableFieldConvertTrees: Ident => Iterable[Term]): Expr[Scalable[T, M]] = { val res = '{ new Scalable[T, M] { override def toScala(proto: M): T = ${ @@ -443,11 +443,8 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( tree match { // setField case buildFunction: Expr[Any => Any] if buildFunction.isExprOf[_ => _] ⇒ val functionName = "builderFunction$" + MacroCache.getIdentityId - // val fromType = buildFunction.tpe.typeArgs.last // buildFunction 的返回值 - // val buildExpr = new ToProtoProcessor(q"$functionName($entityIdent)", fromType, caseClassType, protoType, key).tree.get val tree = buildFunction.asTerm val valDef = ValDef(Symbol.newVal(Symbol.spliceOwner, functionName, tree.tpe, Flags.EmptyFlags, Symbol.noSymbol), Some(tree)) - // val applied = Apply(Select.unique(Ref(valDef.symbol), "apply"), List(scalaIdent)) val applied = Apply(Select.unique(tree, "apply"), List(scalaIdent)) val buildExpr = new ToProtoProcessor(protoBuilderIdent, applied, applied.tpe, key).tree.get @@ -465,39 +462,42 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( }) } - private def buildScalableImpl[T, M]: Tree = { -// val caseClassType = resolveType[T] -// val protoType = resolveType[M] -// val builderId = getBuilderId() -// val customTrees = MacroCache.builderFunctionTrees.getOrElse(builderId, mutable.Map.empty) -// val entityType = resolveType[T] -// -// val (fixedCustomTrees, preTrees) = customTrees.map { -// case (key, tree) ⇒ -// val selector = entityType.member(TermName(key)) -// tree match { -// case buildFunction: Function ⇒ // setField -// val functionName = TermName("builderFunction$" + MacroCache.getIdentityId) -// val expr = new ToScalaProcessor(selector.asMethod, q"$functionName($protoIdent)", buildFunction.body.tpe, resolveType[T], resolveType[M]).tree.get -// (key -> expr) -> q"val $functionName = $buildFunction" -// case value: Tree ⇒ // setFieldValue -// val identity = TermName("identity$" + MacroCache.getIdentityId) -// val expr = new ToScalaProcessor(selector.asMethod, q"$identity", value.tpe, resolveType[T], resolveType[M]).tree.get -// (key -> expr) -> q"val $identity = $value" -// } -// }.unzip -// -// val scalableFieldConvertTrees = (defalutScalableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values -// scalasImpl(caseClassType, protoType, scalableFieldConvertTrees, preTrees) - ??? + private def buildScalableImpl: Expr[Scalable[T, M]] = { + val builderId = getBuilderId() + val customTrees = MacroCache.builderFunctionTrees.getOrElse(builderId, mutable.Map.empty) + + def getCustomTrees(protoIdent: Ident): Map[String, Term] = customTrees.map { case (key, tree) ⇒ + // val selector = entityType.member(TermName(key)) + tree match { + case buildFunction: Expr[Any => Any] if buildFunction.isExprOf[_ => _] ⇒ // setField + val functionName = "builderFunction$" + MacroCache.getIdentityId + val selector = scalaClassSymbol.caseFields.find(_.name == key).get + val tree = buildFunction.asTerm + val valDef = ValDef(Symbol.newVal(Symbol.spliceOwner, functionName, tree.tpe, Flags.EmptyFlags, Symbol.noSymbol), Some(tree)) + val applied = Apply(Select.unique(tree, "apply"), List(protoIdent)) + val expr = new ToScalaProcessor(selector, applied, applied.tpe).tree.get + (key -> expr) + // case value: Tree ⇒ // setFieldValue + // val identity = TermName("identity$" + MacroCache.getIdentityId) + // val expr = new ToScalaProcessor(selector.asMethod, q"$identity", value.tpe, resolveType[T], resolveType[M]).tree.get + // (key -> expr) -> q"val $identity = $value" + } + }.toMap + scalasImpl { protoIdent => + val defaults = defalutScalableFieldConvertTrees(protoIdent) + val customs = getCustomTrees(protoIdent) + (defaults ++ customs).values + } } - private def setScalaFieldImpl[T, M, TF, MF](scalaField: Tree, value: Tree): Tree = { -// val Function(_, Select(_, termName)) = scalaField -// val builderId = getBuilderId() -// MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(termName.toString, value) -// q"new ${c.prefix.actualType}" - ??? + private def setScalaFieldImpl[TF, MF](scalaField: Expr[T => TF], value: Expr[M => MF]): Expr[ScalableBuilder[T, M]] = { + scalaField.asTerm match { + case Inlined(_, _, Inlined(_, _, Block(List(DefDef(_, _, _, Some(Select(_, symbolName)))), _))) => + val builderId = getBuilderId() + MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(symbolName, value) + scalableBuilderApply + case _ => report.errorAndAbort("Invalid setter") + } } private def setProtoFieldImpl[TF: Type, MF: Type](protoFieldSelector: Expr[M ⇒ MF], value: Expr[T ⇒ TF]): Expr[ProtoableBuilder[T, M]] = { @@ -524,13 +524,8 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( val annoBuilderPrefix = "AnonBuilder$" - private def scalableBuilderApply[T, M]: Tree = { -// val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) -// q""" -// class $className extends $packageName.ScalableBuilder[${resolveType[T]}, ${resolveType[M]}] -// new $className -// """ - ??? + private def scalableBuilderApply: Expr[ScalableBuilder[T, M]] = { + '{ ScalableBuilder._default.asInstanceOf[ScalableBuilder[T, M]] } } private def protoableBuilderApply: Expr[ProtoableBuilder[T, M]] = { @@ -573,7 +568,25 @@ object ProtoScalableMacro { def scalableBuilderImpl[T: Type, M <: Message: Type](using t: Type[T], m: Type[M], quotes: Quotes): Expr[ScalableBuilder[T, M]] = { val protoScalableMacro = new ProtoScalableMacro(using t, m) - ??? + protoScalableMacro.scalableBuilderApply + } + + inline def scalableBuilderSetField[T, M <: Message, TF, MF](inline scalaFieldSelector: T ⇒ TF, inline value: M ⇒ MF): ScalableBuilder[T, M] = + ${ scalableBuilderSetFieldImpl[T, M, TF, MF]('scalaFieldSelector, 'value) } + + def scalableBuilderSetFieldImpl[T: Type, M <: Message: Type, TF: Type, MF: Type](scalaFieldSelector: Expr[T ⇒ TF], value: Expr[M ⇒ MF])(using + quotes: Quotes + ): Expr[ScalableBuilder[T, M]] = { + val protoScalableMacro = new ProtoScalableMacro[T, M] + protoScalableMacro.setScalaFieldImpl[TF, MF](scalaFieldSelector, value) + } + + inline def buildScalable[T, M <: Message]: Scalable[T, M] = + ${ buildScalableImpl[T, M] } + + def buildScalableImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[Scalable[T, M]] = { + val protoScalableMacro = new ProtoScalableMacro[T, M] + protoScalableMacro.buildScalableImpl } inline def buildProtoable[T, M <: Message]: Protoable[T, M] = diff --git a/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala b/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala index f2cced3..ec43362 100644 --- a/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala +++ b/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala @@ -2,15 +2,17 @@ package pbconverts import com.google.protobuf.Message -class ScalableBuilder[+T, M]() { +class ScalableBuilder[+T, M <: Message]() { - def setField[TF, MF](scalaField: T ⇒ TF, value: M ⇒ MF): ScalableBuilder[T, M] = ??? // macro ProtoScalableMacro.setScalaFieldImpl[T, M, TF, MF] + inline def setField[TF, MF](inline scalaField: T ⇒ TF, inline value: M ⇒ MF): ScalableBuilder[T, M] = + ProtoScalableMacro.scalableBuilderSetField[T, M, TF, MF](scalaField, value) def setFieldValue[TF, MF](scalaField: T ⇒ TF, value: MF): ScalableBuilder[T, M] = ??? // macro ProtoScalableMacro.setScalaFieldImpl[T, M, TF, MF] - def build: Scalable[T, M] = ??? // macro ProtoScalableMacro.buildScalableImpl[T, M] + inline def build: Scalable[T, M] = ProtoScalableMacro.buildScalable[T, M] } object ScalableBuilder { + val _default = new ScalableBuilder[Nothing, Nothing] inline def apply[T, M <: Message]: ScalableBuilder[T, M] = ProtoScalableMacro.scalableBuilder[T, M] } diff --git a/pbconverts/src/test/scala/pbconverts/MapSpec.scala b/pbconverts/src/test/scala/pbconverts/MapSpec.scala index 58d7cc4..affaab1 100644 --- a/pbconverts/src/test/scala/pbconverts/MapSpec.scala +++ b/pbconverts/src/test/scala/pbconverts/MapSpec.scala @@ -6,16 +6,16 @@ import ConversionTest.{PBTestBytes, PBTestMessage} import org.scalatest.funsuite.AnyFunSuite class MapSpec extends AnyFunSuite { - // test("test map") { - // val testMessage = TestMessage.default - - // val pbTestMessage: PBTestMessage = Protoable[TestMessage, PBTestMessage].toProto(testMessage) - // assert(pbTestMessage.getIntValue == testMessage.intValue) - // assert(pbTestMessage.getLongIntKVOrThrow(1L) == 1) - // assert(pbTestMessage.getLongStringKVOrThrow(1L) == "string1") - // assert(pbTestMessage.getStringIntKVOrThrow("string1") == 1) - // assert(pbTestMessage.getStringStringKVOrThrow("string1") == "string1") - // } + test("test map") { + val testMessage = TestMessage.default + + val pbTestMessage: PBTestMessage = Protoable[TestMessage, PBTestMessage].toProto(testMessage) + assert(pbTestMessage.getIntValue == testMessage.intValue) + assert(pbTestMessage.getLongIntKVOrThrow(1L) == 1) + assert(pbTestMessage.getLongStringKVOrThrow(1L) == "string1") + assert(pbTestMessage.getStringIntKVOrThrow("string1") == 1) + assert(pbTestMessage.getStringStringKVOrThrow("string1") == "string1") + } case class TestBytes(m: Map[String, Int]) @@ -27,11 +27,11 @@ class MapSpec extends AnyFunSuite { assert(pbTest1.getTestBytes.toStringUtf8 == "test,bytes") - // val test = ScalableBuilder[TestBytes, PBTestBytes] - // .setField(_.m, _.getTestBytes.toStringUtf8.split(",").map(_ -> 1).toMap) - // .build - // .toScala(PBTestBytes.newBuilder().setTestBytes(ByteString.copyFromUtf8("test,bytes")).build()) + val test = ScalableBuilder[TestBytes, PBTestBytes] + .setField(_.m, _.getTestBytes.toStringUtf8.split(",").map(_ -> 1).toMap) + .build + .toScala(PBTestBytes.newBuilder().setTestBytes(ByteString.copyFromUtf8("test,bytes")).build()) - // assert(test.m == Map("test" -> 1, "bytes" -> 1)) + assert(test.m == Map("test" -> 1, "bytes" -> 1)) } } From 1a622655d61e2a7640afefcb20487938c50c5ccd Mon Sep 17 00:00:00 2001 From: changvvb Date: Sat, 18 Dec 2021 01:55:18 +0800 Subject: [PATCH 08/17] update --- .../main/scala/pbconverts/ProtoScalable.scala | 4 +- .../scala/pbconverts/ProtoScalableMacro.scala | 220 +++++++----------- .../src/test/scala/pbconverts/MapSpec.scala | 1 + .../pbconverts/MessageWithTypeSpec.scala | 29 +++ .../src/test/scala/pbconverts/Person.scala | 9 + .../pbconverts/ProtoableBuilderSpec.scala | 34 +++ .../pbconverts/ScalableBuilderSpec.scala | 32 +++ .../src/test/scala/pbconverts/TestMain.scala | 2 +- .../test/scala/pbconverts/TestMessage.scala | 11 +- 9 files changed, 201 insertions(+), 141 deletions(-) create mode 100644 pbconverts/src/test/scala/pbconverts/MessageWithTypeSpec.scala create mode 100644 pbconverts/src/test/scala/pbconverts/ProtoableBuilderSpec.scala create mode 100644 pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala diff --git a/pbconverts/src/main/scala/pbconverts/ProtoScalable.scala b/pbconverts/src/main/scala/pbconverts/ProtoScalable.scala index 1b77f63..0eff6ed 100644 --- a/pbconverts/src/main/scala/pbconverts/ProtoScalable.scala +++ b/pbconverts/src/main/scala/pbconverts/ProtoScalable.scala @@ -1,10 +1,12 @@ package pbconverts +import com.google.protobuf.Message + trait ProtoScalable[T, M] extends Protoable[T, M] with Scalable[T, M] object ProtoScalable { - def apply[T <: Product, M]: ProtoScalable[T, M] = ??? // macro ProtoScalableMacro.convertsImpl[T, M] + inline def apply[T <: Product, M <: Message]: ProtoScalable[T, M] = ProtoScalableMacro.protoScalable[T, M] def apply[T, M](toProtoFun: T ⇒ M, toScalaFun: M ⇒ T): ProtoScalable[T, M] = new ProtoScalable[T, M] { diff --git a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala index 8b4df19..d6d7797 100644 --- a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala +++ b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala @@ -9,52 +9,32 @@ import scala.quoted.ToExpr.NoneToExpr import scala.quoted.Exprs // scalastyle:off number.of.methods -class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])(using quotas: Quotes) { +class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { import quotas.reflect._ - private[this] val scalaClassType = quotas.reflect.TypeRepr.of[T](using typeT).dealias - private[this] val protoClassType = quotas.reflect.TypeRepr.of[M](using typeM).dealias + private val scalaClassType = quotas.reflect.TypeRepr.of[T].dealias + private val protoClassType = quotas.reflect.TypeRepr.of[M].dealias - private[this] val scalaClassSymbol: quotas.reflect.Symbol = scalaClassType.typeSymbol - private[this] val protoClassSymbol: quotas.reflect.Symbol = quotas.reflect.TypeReprMethods.classSymbol(protoClassType).get - private[this] val scalaClassSymbolModule = quotas.reflect.SymbolMethods.companionModule(scalaClassSymbol) + private val scalaClassSymbol: quotas.reflect.Symbol = scalaClassType.typeSymbol + private val protoClassSymbol: quotas.reflect.Symbol = protoClassType.typeSymbol - private[this] val scalaClassApplySymbol = scalaClassSymbolModule.methodMember("apply").head - private[this] val protoClassSymbolClass = quotas.reflect.SymbolMethods.companionClass(protoClassSymbol) - private[this] val protoClassSymbolModule = quotas.reflect.SymbolMethods.companionModule(protoClassSymbol) + private val protoCompanionIdent = Ref(protoClassSymbol.companionModule) + private val newBuilder = Select.overloaded(protoCompanionIdent, "newBuilder", Nil, Nil) + private val builderType: TypeRepr = newBuilder.tpe + private val builderClassSymbol: Symbol = builderType.typeSymbol - private val newBuilderMethod = quotas.reflect.SymbolMethods.memberMethod(protoClassSymbolModule)("newBuilder").last - private val builderType: TypeRepr = newBuilderMethod.tree.asInstanceOf[DefDef].returnTpt.tpe - private val builderClassSymbol: Symbol = builderType.classSymbol.get - private val builderBuildMethod = builderType.classSymbol.get.memberMethod("build").head - - private val (scalaclassOuter, scalaClassName) = scalaClassType match { - case t: AppliedType => - val TypeRef(scalaclassOuter, scalaClassName) = t.tycon - (scalaclassOuter, scalaClassName) - case t: TypeRef => - val TypeRef(scalaclassOuter, scalaClassName) = t - (scalaclassOuter, scalaClassName) - } - - // private val TypeRef(scalaclassOuter, scalaClassName) = scalaClassType.asInstanceOf[TypeRef] - private val scalaCompanionIdent = Ident.apply(TermRef.apply(scalaclassOuter, scalaClassName)) - - private val TypeRef(outer, name) = protoClassType.asInstanceOf[TypeRef] - private val protoCompanionIdent = Ident.apply(TermRef.apply(outer, name)) - private val newBuilderApply = Apply(Select.apply(protoCompanionIdent, newBuilderMethod), List.empty) - private def builderBuildeWithTerms(termsBuilder: Ident => List[Term]) = ValDef.let(Symbol.spliceOwner, "builder", newBuilderApply) { ident => - val terms: List[Term] = termsBuilder(ident.asInstanceOf[Ident]) - Block(terms, Apply(Select(ident, builderBuildMethod), Nil)) + private def builderBuildeWithTerms(termsBuilder: Ident => List[Term]) = { + ValDef.let(Symbol.spliceOwner, "builder", newBuilder) { builderIdent => + val terms: List[Term] = termsBuilder(builderIdent.asInstanceOf[Ident]) + Block(terms, Select.overloaded(builderIdent, "build", Nil, Nil)) + } } private[this] def implicitlyProtoable(entityType: TypeRepr, protoType: TypeRepr): Term = { val target = TypeRepr.of[Protoable].appliedTo(List(entityType, protoType)) Implicits.search(target) match { case s: ImplicitSearchSuccess => s.tree - case _ => - report.error(s"implicit ${Printer.TypeReprAnsiCode.show(target)} not found") - ??? + case _ => report.errorAndAbort(s"implicit ${Printer.TypeReprAnsiCode.show(target)} not found") } } @@ -62,10 +42,8 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( val target = TypeRepr.of[Scalable].appliedTo(List(entityType, protoType)) Implicits.search(target) match { case s: ImplicitSearchSuccess => s.tree - case _ => - report.error(s"implicit ${Printer.TypeReprAnsiCode.show(target)} not found") - ??? - } // q"implicitly[$packageName.Scalable[$entityType,$protoType]]" + case _ => report.errorAndAbort(s"implicit ${Printer.TypeReprAnsiCode.show(target)} not found") + } } private[this] def isOption(tpe: TypeRepr): Boolean = { @@ -79,10 +57,6 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( private[this] def isMap(tpe: TypeRepr): Boolean = tpe <:< TypeRepr.of[Map[_, _]] || tpe <:< TypeRepr.of[java.util.Map[_, _]] - private[this] def getBuilderType(): TypeRepr = { - builderType - } - private trait Processor { def scalaTreeType: TypeRepr @@ -122,28 +96,26 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( } else { defaultTree(optFieldType) } - '{ if (${ scalaTree.asExprOf[Option[_]] }.isDefined) ${ tree.asExpr } }.asTerm -// If(q"$scalaTree.isDefined", tree, EmptyTree) + If(Select.unique(scalaTree, "isDefined"), tree, '{}.asTerm) } def seqTree(iterableType: TypeRepr): Term = { val addAllMethod = builderClassSymbol.memberMethod(addAllMethodName).last val listType = addAllMethod.tree.asInstanceOf[DefDef].paramss.head.params.head.asInstanceOf[ValDef].tpt.tpe val valueTree = toProto(iterableType, listType) - Apply(Select(protoBuilderIdent, addAllMethod), List(valueTree)) + Select.overloaded(protoBuilderIdent, addAllMethodName, Nil, valueTree :: Nil) } def mapTree(mapType: TypeRepr): Term = { val putAllMethod = builderClassSymbol.memberMethod(putAllMethodName).head val putAllMapType = putAllMethod.tree.asInstanceOf[DefDef].paramss.head.params.head.asInstanceOf[ValDef].tpt.tpe val valueTree = toProto(mapType, putAllMapType) - Apply(Select(protoBuilderIdent, putAllMethod), List(valueTree)) + Select.overloaded(protoBuilderIdent, putAllMethodName, Nil, valueTree :: Nil) } def defaultTree(fieldType: TypeRepr): Term = { val valueTree = toProto(fieldType, protoValueType) - val setFieldMethod = builderClassSymbol.memberMethod(setField).last - Apply(Select(protoBuilderIdent, setFieldMethod), List(valueTree)) + Select.overloaded(protoBuilderIdent, setField, Nil, valueTree :: Nil) } override def tree: Option[Term] = { @@ -160,12 +132,12 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( defaultTree(resolvedCaseClassFieldType) } - if (scalaTreeType <:< TypeRepr.of[AnyRef]) { - Some('{ - if (${ scalaTree.asExprOf[AnyRef] } ne null) ${ _tree.asExpr } - }.asTerm) - } else { - Some(_tree) + scalaTree match { + case Select(_, _) if scalaTreeType <:< TypeRepr.of[AnyRef] => + val cond = Select.unique(scalaTree, "ne").appliedTo(Literal(NullConstant())) + Some(If(cond, _tree, '{}.asTerm)) + case _ => + Some(_tree) } } } @@ -194,20 +166,19 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( def optTree(optType: TypeRepr): Term = defaultTree(optType) def defaultTree(fieldType: TypeRepr): Term = { -// q"$caseClassSelector = ${toScala(fieldType, protoValueType, protoValueTree)}" - toScala(fieldType, protoValueType, protoValueTree) -// Assign(caseClassSelector.tree.asInstanceOf[Term], toScala(fieldType,protoValueType,protoValueTree)) + NamedArg(caseClassSelector.name, toScala(fieldType, protoValueType, protoValueTree)) } override def tree: Option[Term] = if (protoValueType == TypeRepr.of[Unit]) { None } else { - if (isOption(scalaTreeType)) { - Some(optTree(resolvedCaseClassFieldType)) + val tree = if (isOption(scalaTreeType)) { + optTree(resolvedCaseClassFieldType) } else { - Some(defaultTree(resolvedCaseClassFieldType)) + defaultTree(resolvedCaseClassFieldType) } + Some(tree) } } @@ -338,13 +309,6 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( } } - private[this] def resolveType[T](using Type[T]): TypeRepr = { -// val tpe = weakTypeOf[T] -// tpe.dealias -// ??? - TypeRepr.of[T] - } - private[this] def getCaseAccessors(): List[Symbol] = { val classSymbol = quotas.reflect.TypeReprMethods.classSymbol(scalaClassType).get quotas.reflect.SymbolMethods.caseFields(classSymbol) @@ -357,57 +321,39 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( } } - private[this] def protoableBody(protoableFieldConvertTrees: Iterable[Tree]): Tree = { -// q""" -// override def toProto(${entityIdent.name.toTermName}: $caseClassType): $protoType = { -// val ${builderIdent} = ${protoType.typeSymbol.companion}.newBuilder() -// ..$protoableFieldConvertTrees -// $builderIdent.build() -// } -// """ - ??? + private[this] def protoableBody(scalaEntityIdent: Ident, protoableFieldConvertTrees: (Ident, Ident) => List[Term]): Expr[M] = { + builderBuildeWithTerms(protoableFieldConvertTrees(scalaEntityIdent, _)).asExprOf[M] } private def defalutScalableFieldConvertTrees(protoIdent: Ident): Map[String, Term] = { getCaseAccessors().flatMap(accessor ⇒ ToScalaFieldProcessor(protoIdent, accessor).tree.map(accessor.name.toString -> _)).toMap } - private def scalableBody(scalableFieldConvertTrees: Iterable[Tree]): Tree = { -// q""" -// override def toScala(${protoIdent.name.toTermName} :$protoType): $caseClassType = { -// new ${caseClassType.typeSymbol} ( -// ..${scalableFieldConvertTrees} -// ) -// } -// """ - ??? + private def scalableBody(protoIdent: Ident, scalableFieldConvertTrees: Ident => Iterable[Term]): Expr[T] = { + val args = scalableFieldConvertTrees(protoIdent).toList + + val types = scalaClassType match { + case t: AppliedType => t.args + case _ => Nil + } + + val scalaCompanionIdent = Ref(scalaClassType.typeSymbol.companionModule) + Select.overloaded(scalaCompanionIdent, "apply", types, args).asExprOf[T] } def scalasImpl: Expr[Scalable[T, M]] = { - scalasImpl(defalutScalableFieldConvertTrees(_).values) + scalasImpl { protoIdent => + val args = defalutScalableFieldConvertTrees(protoIdent) + getCaseAccessors().flatMap(a => args.get(a.name)) + } } - private[this] def scalasImpl(scalableFieldConvertTrees: Ident => Iterable[Term]): Expr[Scalable[T, M]] = { - val res = '{ + private[this] def scalasImpl(scalableFieldConvertTrees: Ident => List[Term]): Expr[Scalable[T, M]] = { + '{ new Scalable[T, M] { - override def toScala(proto: M): T = ${ - val protoIdent = '{ proto }.asTerm.asInstanceOf[Ident] - val x = scalableFieldConvertTrees(protoIdent) - - val types = scalaClassType match { - case AppliedType(typeConstructor, args) => - args - case _ => - Nil - } - - Apply(Select(scalaCompanionIdent, scalaClassApplySymbol).appliedToTypes(types), scalableFieldConvertTrees(protoIdent).toList).asExprOf[T] - // New(TypeTree.of[T]).asExprOf[T] - } + def toScala(proto: M): T = ${ scalableBody('{ proto }.asTerm.asInstanceOf[Ident], scalableFieldConvertTrees) } } } - println(res.show) - res } private def protosImpl: Expr[Protoable[T, M]] = { @@ -415,33 +361,31 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( } private[this] def protosImpl(protoableFieldConvertTrees: (Ident, Ident) => List[Term]): Expr[Protoable[T, M]] = { - val result = '{ + '{ new Protoable[T, M] { - override def toProto(scalaEntity: T): M = ${ - val scalaEntityIdent = '{ scalaEntity }.asTerm.asInstanceOf[Ident] - builderBuildeWithTerms(protoableFieldConvertTrees(scalaEntityIdent, _)).asExprOf[M] - } + def toProto(scalaEntity: T): M = ${ protoableBody('{ scalaEntity }.asTerm.asInstanceOf[Ident], protoableFieldConvertTrees) } } } - println(result.show) - result } - def convertsImpl[T, M](using Type[T], Type[M]): Expr[ProtoScalable[T, M]] = { -// q""" -// new $packageName.ProtoScalable[${resolveType[T]}, ${resolveType[M]}] { -// ${scalableBody(caseClassType, protoType, defalutScalableFieldConvertTrees(caseClassType, protoType).values)} -// ${protoableBody(caseClassType, protoType, defaultProtoableFieldConvertTrees(caseClassType, protoType).values)} -// } -// """ - ??? + def protoScalableImpl: Expr[ProtoScalable[T, M]] = { + '{ + new ProtoScalable[T, M] { + def toScala(proto: M) = ${ scalableBody('{ proto }.asTerm.asInstanceOf[Ident], defalutScalableFieldConvertTrees(_).values) } + + def toProto(scalaEntity: T): M = ${ + val scalaEntityIdent = '{ scalaEntity }.asTerm.asInstanceOf[Ident] + builderBuildeWithTerms(defaultProtoableFieldConvertTrees(scalaEntityIdent, _).map(_._2)).asExprOf[M] + } + } + } } private def buildProtoableImpl: Expr[Protoable[T, M]] = { val customTrees = MacroCache.builderFunctionTrees.getOrElse(getBuilderId(), mutable.Map.empty) def getCustomTrees(scalaIdent: Ident, protoBuilderIdent: Ident): Map[String, Term] = customTrees.map { case (key, tree) ⇒ tree match { // setField - case buildFunction: Expr[Any => Any] if buildFunction.isExprOf[_ => _] ⇒ + case buildFunction: Expr[_] if buildFunction.isExprOf[_ => _] ⇒ val functionName = "builderFunction$" + MacroCache.getIdentityId val tree = buildFunction.asTerm val valDef = ValDef(Symbol.newVal(Symbol.spliceOwner, functionName, tree.tpe, Flags.EmptyFlags, Symbol.noSymbol), Some(tree)) @@ -455,7 +399,6 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( // (key -> buildExpr) -> q"val $identity = $value" } }.toMap - // val protoableFieldConvertTrees = (defaultProtoableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values protosImpl({ (scalaIdent, protoBuilderIdent) => val terms = getCustomTrees(scalaIdent, protoBuilderIdent) (defaultProtoableFieldConvertTrees(scalaIdent, protoBuilderIdent) ++ terms).toMap.values.toList @@ -467,9 +410,8 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( val customTrees = MacroCache.builderFunctionTrees.getOrElse(builderId, mutable.Map.empty) def getCustomTrees(protoIdent: Ident): Map[String, Term] = customTrees.map { case (key, tree) ⇒ - // val selector = entityType.member(TermName(key)) tree match { - case buildFunction: Expr[Any => Any] if buildFunction.isExprOf[_ => _] ⇒ // setField + case buildFunction: Expr[_] if buildFunction.isExprOf[_ => _] ⇒ // setField val functionName = "builderFunction$" + MacroCache.getIdentityId val selector = scalaClassSymbol.caseFields.find(_.name == key).get val tree = buildFunction.asTerm @@ -486,7 +428,10 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( scalasImpl { protoIdent => val defaults = defalutScalableFieldConvertTrees(protoIdent) val customs = getCustomTrees(protoIdent) - (defaults ++ customs).values + val all = defaults ++ customs + getCaseAccessors().flatMap { accessor => + all.get(accessor.name) + } } } @@ -517,8 +462,6 @@ class ProtoScalableMacro[T, M <: Message](using typeT: Type[T], typeM: Type[M])( val builderId = Symbol.spliceOwner.owner.fullName MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(setter, value) - // New.apply(TypeTree.of[BLD]).asExprOf[BLD] - // println(TypeRepr.of[BLD]) protoableBuilderApply } @@ -542,15 +485,15 @@ object ProtoScalableMacro { inline def protoable[T, M <: Message]: Protoable[T, M] = ${ protosImpl[T, M] } - def protosImpl[T, M <: Message](using t: Type[T], m: Type[M], quotes: Quotes): Expr[Protoable[T, M]] = { - val protoScalableMacro = new ProtoScalableMacro(using t, m) + def protosImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[Protoable[T, M]] = { + val protoScalableMacro = new ProtoScalableMacro[T, M] protoScalableMacro.protosImpl } inline def protoableBuilder[T, M <: Message]: ProtoableBuilder[T, M] = ${ protoableBuilderImpl[T, M] } - def protoableBuilderImpl[T, M <: Message](using t: Type[T], m: Type[M], quotes: Quotes): Expr[ProtoableBuilder[T, M]] = { - val protoScalableMacro = new ProtoScalableMacro(using t, m) + def protoableBuilderImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[ProtoableBuilder[T, M]] = { + val protoScalableMacro = new ProtoScalableMacro[T, M] protoScalableMacro.protoableBuilderApply } @@ -566,8 +509,8 @@ object ProtoScalableMacro { inline def scalableBuilder[T, M <: Message]: ScalableBuilder[T, M] = ${ scalableBuilderImpl[T, M] } - def scalableBuilderImpl[T: Type, M <: Message: Type](using t: Type[T], m: Type[M], quotes: Quotes): Expr[ScalableBuilder[T, M]] = { - val protoScalableMacro = new ProtoScalableMacro(using t, m) + def scalableBuilderImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[ScalableBuilder[T, M]] = { + val protoScalableMacro = new ProtoScalableMacro[T, M] protoScalableMacro.scalableBuilderApply } @@ -599,8 +542,15 @@ object ProtoScalableMacro { inline def scalable[T, M <: Message]: Scalable[T, M] = ${ scalasImpl[T, M] } - def scalasImpl[T, M <: Message](using t: Type[T], m: Type[M], quotes: Quotes): Expr[Scalable[T, M]] = { - val protoScalableMacro = new ProtoScalableMacro(using t, m) + def scalasImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[Scalable[T, M]] = { + val protoScalableMacro = new ProtoScalableMacro[T, M] protoScalableMacro.scalasImpl } + + inline def protoScalable[T, M <: Message]: ProtoScalable[T, M] = ${ protoScalableImpl[T, M] } + + def protoScalableImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[ProtoScalable[T, M]] = { + val protoScalableMacro = new ProtoScalableMacro[T, M] + protoScalableMacro.protoScalableImpl + } } diff --git a/pbconverts/src/test/scala/pbconverts/MapSpec.scala b/pbconverts/src/test/scala/pbconverts/MapSpec.scala index affaab1..e204f96 100644 --- a/pbconverts/src/test/scala/pbconverts/MapSpec.scala +++ b/pbconverts/src/test/scala/pbconverts/MapSpec.scala @@ -20,6 +20,7 @@ class MapSpec extends AnyFunSuite { case class TestBytes(m: Map[String, Int]) test("test conversion between bytes in protobuf and Map in case class") { + PBTestBytes.newBuilder().setTestBytes val pbTest1 = ProtoableBuilder[TestBytes, PBTestBytes] .setField(_.getTestBytes, x => ByteString.copyFromUtf8(x.m.keys.mkString(","))) .build diff --git a/pbconverts/src/test/scala/pbconverts/MessageWithTypeSpec.scala b/pbconverts/src/test/scala/pbconverts/MessageWithTypeSpec.scala new file mode 100644 index 0000000..dd97008 --- /dev/null +++ b/pbconverts/src/test/scala/pbconverts/MessageWithTypeSpec.scala @@ -0,0 +1,29 @@ +package pbconverts + +import org.scalatest.funsuite.AnyFunSuite +import pbconverts.ConversionTest.{IntMessage, StringMessage} + +class MessageWithTypeSpec extends AnyFunSuite { + + test("test message with type parameter") { + locally { + val intMessage = MessageWithType(5) + val proto = Protoable[MessageWithType[Int], IntMessage].toProto(intMessage) + assert(proto.getValue == 5) + + val intMessage2 = Scalable[MessageWithType[Int], IntMessage].toScala(proto) + assert(intMessage == intMessage2) + } + + locally { + val stringMessage = MessageWithType("test") + val proto = Protoable[MessageWithType[String], StringMessage].toProto(stringMessage) + assert(proto.getValue == "test") + + val stringMessage2 = Scalable[MessageWithType[String], StringMessage].toScala(proto) + assert(stringMessage == stringMessage2) + } + + } + +} diff --git a/pbconverts/src/test/scala/pbconverts/Person.scala b/pbconverts/src/test/scala/pbconverts/Person.scala index ad00e67..ad99548 100644 --- a/pbconverts/src/test/scala/pbconverts/Person.scala +++ b/pbconverts/src/test/scala/pbconverts/Person.scala @@ -1,2 +1,11 @@ package pbconverts + +import pbconverts.ConversionTest.PBPerson + case class Person(id: Long, name: String, phone: Option[String], hobbies: Seq[String]) + +object Person { + def default = Person(1L, "name", Some("123"), hobbies = Seq("ping pong")) + + given ProtoScalable[Person, PBPerson] = ProtoScalable[Person, PBPerson] +} \ No newline at end of file diff --git a/pbconverts/src/test/scala/pbconverts/ProtoableBuilderSpec.scala b/pbconverts/src/test/scala/pbconverts/ProtoableBuilderSpec.scala new file mode 100644 index 0000000..7c51f25 --- /dev/null +++ b/pbconverts/src/test/scala/pbconverts/ProtoableBuilderSpec.scala @@ -0,0 +1,34 @@ +package pbconverts + +import org.scalatest.funsuite.AnyFunSuite +import pbconverts.ConversionTest.PBTestMessage + +class ProtoableBuilderSpec extends AnyFunSuite { + test("test ProtoableBuilder") { + assertTestMessage(TestMessage.default) + assertTestMessage(TestMessage.zero) + } + + def assertTestMessage(testMessage: TestMessage) = { + val pbTestMessage: PBTestMessage = ProtoableBuilder[TestMessage, PBTestMessage] + .setField(_.getIntValue, _.intValue + 1) + .build + .toProto(testMessage) + + assert(pbTestMessage.getIntValue == testMessage.intValue + 1) + val testMessage2 = Scalable[TestMessage, PBTestMessage].toScala(pbTestMessage) + + assert(testMessage2.intArray.sameElements(testMessage.intArray)) + assert(testMessage2.stringArray.sameElements(testMessage.stringArray)) + assert(testMessage2.personArray.sameElements(testMessage.personArray)) + + assert( + testMessage == testMessage2.copy( + intValue = testMessage2.intValue - 1, + intArray = testMessage.intArray, + stringArray = testMessage.stringArray, + personArray = testMessage.personArray + ) + ) + } +} diff --git a/pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala b/pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala new file mode 100644 index 0000000..f77747a --- /dev/null +++ b/pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala @@ -0,0 +1,32 @@ +package pbconverts + +import org.scalatest.funsuite.AnyFunSuite +import pbconverts.ConversionTest.PBTestMessage + +class ScalableBuilderSpec extends AnyFunSuite { + test("test ScalableBuilder") { + assertTestMessage(TestMessage.default) + assertTestMessage(TestMessage.zero) + } + + def assertTestMessage(testMessage: TestMessage) = { + val pbTestMessage = Protoable[TestMessage, PBTestMessage].toProto(testMessage) + val testMessage2 = ScalableBuilder[TestMessage, PBTestMessage] + .setField(_.intOpt, m => if (m.hasIntOpt) Some(m.getIntOpt.getValue + 1) else None) + .build + .toScala(pbTestMessage) + + assert(testMessage2.intArray.sameElements(testMessage.intArray)) + assert(testMessage2.stringArray.sameElements(testMessage.stringArray)) + assert(testMessage2.personArray.sameElements(testMessage.personArray)) + + assert( + testMessage == testMessage2.copy( + intOpt = testMessage2.intOpt.map(_ - 1), + intArray = testMessage.intArray, + stringArray = testMessage.stringArray, + personArray = testMessage.personArray + ) + ) + } +} \ No newline at end of file diff --git a/pbconverts/src/test/scala/pbconverts/TestMain.scala b/pbconverts/src/test/scala/pbconverts/TestMain.scala index e13815e..a8edce1 100644 --- a/pbconverts/src/test/scala/pbconverts/TestMain.scala +++ b/pbconverts/src/test/scala/pbconverts/TestMain.scala @@ -12,7 +12,7 @@ object TestMain extends App { val stringMessage = MessageWithType("test") // val x = Protoable[MessageWithType[String], StringMessage].toProto(stringMessage) val x = StringMessage.newBuilder.setValue("Test").build - val y = Scalable[MessageWithType[String], StringMessage].toScala(x) +// val y = Scalable[MessageWithType[String], StringMessage].toScala(x) println(x.getValue) // println(y) diff --git a/pbconverts/src/test/scala/pbconverts/TestMessage.scala b/pbconverts/src/test/scala/pbconverts/TestMessage.scala index 1f95c3c..e801c6f 100644 --- a/pbconverts/src/test/scala/pbconverts/TestMessage.scala +++ b/pbconverts/src/test/scala/pbconverts/TestMessage.scala @@ -19,7 +19,7 @@ case class TestMessage( timeOpt: Option[ZonedDateTime], intArray: Array[Int], stringArray: Array[String], -// personArray: Array[Person], + personArray: Array[Person], seq: Seq[Double], stringStringKV: Map[String, String], // not convert k or v longStringKV: Map[Long, String], // convert k, but not v @@ -28,6 +28,9 @@ case class TestMessage( ) object TestMessage { + + def apply():TestMessage = ??? + def default = TestMessage( intValue = 64, @@ -46,7 +49,7 @@ object TestMessage { timeOpt = Some(ZonedDateTime.now()), intArray = Array(100, 200, 300), stringArray = Array("string1", "string2", "string3"), -// personArray = Array(Person.default), + personArray = Array(Person.default), seq = Seq(1.0, 2.0, 3.0), stringStringKV = Map("string1" -> "string1", "string2" -> "string2"), longStringKV = Map(1L -> "string1", 2L -> "string2"), @@ -72,11 +75,11 @@ object TestMessage { timeOpt = None, intArray = Array.empty, stringArray = Array.empty, -// personArray = Array.empty, + personArray = Array.empty, seq = Seq.empty, stringStringKV = Map.empty, longStringKV = Map.empty, stringIntKV = Map.empty, longIntKV = Map.empty ) -} +} \ No newline at end of file From 89a1d89d70a185f5fbad8a5c2163a6963a41f5e7 Mon Sep 17 00:00:00 2001 From: changvvb Date: Sat, 18 Dec 2021 16:52:53 +0800 Subject: [PATCH 09/17] support scala3 done --- .../scala/pbconverts/ProtoScalableMacro.scala | 39 +++++++++---------- .../scala/pbconverts/ProtoableBuilder.scala | 3 +- .../scala/pbconverts/ScalableBuilder.scala | 3 +- .../pbconverts/ProtoableBuilderSpec.scala | 12 ++++++ .../pbconverts/ScalableBuilderSpec.scala | 13 +++++++ 5 files changed, 47 insertions(+), 23 deletions(-) diff --git a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala index d6d7797..a2f3b55 100644 --- a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala +++ b/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala @@ -136,7 +136,7 @@ class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { case Select(_, _) if scalaTreeType <:< TypeRepr.of[AnyRef] => val cond = Select.unique(scalaTree, "ne").appliedTo(Literal(NullConstant())) Some(If(cond, _tree, '{}.asTerm)) - case _ => + case _ => Some(_tree) } } @@ -386,17 +386,15 @@ class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { def getCustomTrees(scalaIdent: Ident, protoBuilderIdent: Ident): Map[String, Term] = customTrees.map { case (key, tree) ⇒ tree match { // setField case buildFunction: Expr[_] if buildFunction.isExprOf[_ => _] ⇒ - val functionName = "builderFunction$" + MacroCache.getIdentityId val tree = buildFunction.asTerm - val valDef = ValDef(Symbol.newVal(Symbol.spliceOwner, functionName, tree.tpe, Flags.EmptyFlags, Symbol.noSymbol), Some(tree)) val applied = Apply(Select.unique(tree, "apply"), List(scalaIdent)) val buildExpr = new ToProtoProcessor(protoBuilderIdent, applied, applied.tpe, key).tree.get (key -> buildExpr) - // case value: Tree ⇒ // setFieldValue - // val identity = TermName("identity$" + MacroCache.getIdentityId) - // val buildExpr = new ToProtoProcessor(q"$identity", value.tpe, caseClassType, protoType, key).tree.get - // (key -> buildExpr) -> q"val $identity = $value" + case value: Expr[_] ⇒ // setFieldValue + val valueTerm = value.asTerm + val buildExpr = new ToProtoProcessor(protoBuilderIdent, valueTerm, valueTerm.tpe, key).tree.get + (key -> buildExpr) } }.toMap protosImpl({ (scalaIdent, protoBuilderIdent) => @@ -412,17 +410,16 @@ class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { def getCustomTrees(protoIdent: Ident): Map[String, Term] = customTrees.map { case (key, tree) ⇒ tree match { case buildFunction: Expr[_] if buildFunction.isExprOf[_ => _] ⇒ // setField - val functionName = "builderFunction$" + MacroCache.getIdentityId val selector = scalaClassSymbol.caseFields.find(_.name == key).get val tree = buildFunction.asTerm - val valDef = ValDef(Symbol.newVal(Symbol.spliceOwner, functionName, tree.tpe, Flags.EmptyFlags, Symbol.noSymbol), Some(tree)) val applied = Apply(Select.unique(tree, "apply"), List(protoIdent)) val expr = new ToScalaProcessor(selector, applied, applied.tpe).tree.get (key -> expr) - // case value: Tree ⇒ // setFieldValue - // val identity = TermName("identity$" + MacroCache.getIdentityId) - // val expr = new ToScalaProcessor(selector.asMethod, q"$identity", value.tpe, resolveType[T], resolveType[M]).tree.get - // (key -> expr) -> q"val $identity = $value" + case value: Expr[_] ⇒ // setFieldValue + val valueTerm = value.asTerm + val selector = scalaClassSymbol.caseFields.find(_.name == key).get + val buildExpr = new ToScalaProcessor(selector, valueTerm, valueTerm.tpe).tree.get + (key -> buildExpr) } }.toMap scalasImpl { protoIdent => @@ -435,7 +432,7 @@ class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { } } - private def setScalaFieldImpl[TF, MF](scalaField: Expr[T => TF], value: Expr[M => MF]): Expr[ScalableBuilder[T, M]] = { + private def setScalaFieldImpl[TF, MF](scalaField: Expr[T => TF], value: Expr[(M => MF) | MF]): Expr[ScalableBuilder[T, M]] = { scalaField.asTerm match { case Inlined(_, _, Inlined(_, _, Block(List(DefDef(_, _, _, Some(Select(_, symbolName)))), _))) => val builderId = getBuilderId() @@ -445,7 +442,7 @@ class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { } } - private def setProtoFieldImpl[TF: Type, MF: Type](protoFieldSelector: Expr[M ⇒ MF], value: Expr[T ⇒ TF]): Expr[ProtoableBuilder[T, M]] = { + private def setProtoFieldImpl[TF: Type, MF: Type](protoFieldSelector: Expr[M ⇒ MF], value: Expr[(T ⇒ TF) | TF]): Expr[ProtoableBuilder[T, M]] = { val getter = "^get(\\w+)$".r val listGetter = "^get(\\w+)List$".r val mapGetter = "^get(\\w+)Map$".r @@ -455,9 +452,9 @@ class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { case mapGetter(n) if TypeRepr.of[MF] <:< TypeRepr.of[java.util.Map[_, _]] ⇒ n case listGetter(n) if TypeRepr.of[MF] <:< TypeRepr.of[java.util.List[_]] ⇒ n case getter(n) ⇒ n - case _ => report.errorAndAbort("Invalid setter") + case _ => report.errorAndAbort("Invalid field selector") } - case _ => report.errorAndAbort("Invalid setter") + case _ => report.errorAndAbort("Invalid field selector") } val builderId = Symbol.spliceOwner.owner.fullName @@ -497,10 +494,10 @@ object ProtoScalableMacro { protoScalableMacro.protoableBuilderApply } - inline def protoableBuilderSetField[T, M <: Message, MF, TF](inline protoFieldSelector: M ⇒ MF, inline value: T ⇒ TF): ProtoableBuilder[T, M] = + inline def protoableBuilderSetField[T, M <: Message, MF, TF](inline protoFieldSelector: M ⇒ MF, inline value: (T ⇒ TF) | TF): ProtoableBuilder[T, M] = ${ protoableBuilderSetFieldImpl[T, M, MF, TF]('protoFieldSelector, 'value) } - def protoableBuilderSetFieldImpl[T: Type, M <: Message: Type, MF: Type, TF: Type](protoFieldSelector: Expr[M ⇒ MF], value: Expr[T ⇒ TF])(using + def protoableBuilderSetFieldImpl[T: Type, M <: Message: Type, MF: Type, TF: Type](protoFieldSelector: Expr[M ⇒ MF], value: Expr[(T ⇒ TF) | TF])(using quotes: Quotes ): Expr[ProtoableBuilder[T, M]] = { val protoScalableMacro = new ProtoScalableMacro[T, M] @@ -514,10 +511,10 @@ object ProtoScalableMacro { protoScalableMacro.scalableBuilderApply } - inline def scalableBuilderSetField[T, M <: Message, TF, MF](inline scalaFieldSelector: T ⇒ TF, inline value: M ⇒ MF): ScalableBuilder[T, M] = + inline def scalableBuilderSetField[T, M <: Message, TF, MF](inline scalaFieldSelector: T ⇒ TF, inline value: (M ⇒ MF) | MF): ScalableBuilder[T, M] = ${ scalableBuilderSetFieldImpl[T, M, TF, MF]('scalaFieldSelector, 'value) } - def scalableBuilderSetFieldImpl[T: Type, M <: Message: Type, TF: Type, MF: Type](scalaFieldSelector: Expr[T ⇒ TF], value: Expr[M ⇒ MF])(using + def scalableBuilderSetFieldImpl[T: Type, M <: Message: Type, TF: Type, MF: Type](scalaFieldSelector: Expr[T ⇒ TF], value: Expr[(M ⇒ MF) | MF])(using quotes: Quotes ): Expr[ScalableBuilder[T, M]] = { val protoScalableMacro = new ProtoScalableMacro[T, M] diff --git a/pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala b/pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala index fcb1026..cc133ad 100644 --- a/pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala +++ b/pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala @@ -7,7 +7,8 @@ class ProtoableBuilder[T, M <: Message]() { inline def setField[TF, MF](inline protoFieldSelector: M ⇒ MF, inline value: T ⇒ TF): ProtoableBuilder[T, M] = ProtoScalableMacro.protoableBuilderSetField[T, M, MF, TF](protoFieldSelector, value) - def setFieldValue[TF, MF](protoFieldSelector: M ⇒ MF, value: TF): this.type = ??? // macro ProtoScalableMacro.setProtoFieldImpl[T, M, TF, MF] + inline def setFieldValue[TF, MF](inline protoFieldSelector: M ⇒ MF, inline value: TF): ProtoableBuilder[T, M] = + ProtoScalableMacro.protoableBuilderSetField[T, M, MF, TF](protoFieldSelector, value) inline def build: Protoable[T, M] = ProtoScalableMacro.buildProtoable[T, M] } diff --git a/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala b/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala index ec43362..be6731b 100644 --- a/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala +++ b/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala @@ -7,7 +7,8 @@ class ScalableBuilder[+T, M <: Message]() { inline def setField[TF, MF](inline scalaField: T ⇒ TF, inline value: M ⇒ MF): ScalableBuilder[T, M] = ProtoScalableMacro.scalableBuilderSetField[T, M, TF, MF](scalaField, value) - def setFieldValue[TF, MF](scalaField: T ⇒ TF, value: MF): ScalableBuilder[T, M] = ??? // macro ProtoScalableMacro.setScalaFieldImpl[T, M, TF, MF] + inline def setFieldValue[TF, MF](inline scalaField: T ⇒ TF, inline value: MF): ScalableBuilder[T, M] = + ProtoScalableMacro.scalableBuilderSetField[T, M, TF, MF](scalaField, value) inline def build: Scalable[T, M] = ProtoScalableMacro.buildScalable[T, M] } diff --git a/pbconverts/src/test/scala/pbconverts/ProtoableBuilderSpec.scala b/pbconverts/src/test/scala/pbconverts/ProtoableBuilderSpec.scala index 7c51f25..6e79557 100644 --- a/pbconverts/src/test/scala/pbconverts/ProtoableBuilderSpec.scala +++ b/pbconverts/src/test/scala/pbconverts/ProtoableBuilderSpec.scala @@ -2,6 +2,7 @@ package pbconverts import org.scalatest.funsuite.AnyFunSuite import pbconverts.ConversionTest.PBTestMessage +import pbconverts.ConversionTest.PBPerson class ProtoableBuilderSpec extends AnyFunSuite { test("test ProtoableBuilder") { @@ -9,6 +10,17 @@ class ProtoableBuilderSpec extends AnyFunSuite { assertTestMessage(TestMessage.zero) } + test("setFieldValue") { + val person = Person(1, "name", Some("123"), Seq("play")) + val pbPerson = ProtoableBuilder[Person, PBPerson] + .setFieldValue(_.getName, "my name") + .build + .toProto(person) + + assert(pbPerson.getName == "my name") + assert(pbPerson.getId == 1) + } + def assertTestMessage(testMessage: TestMessage) = { val pbTestMessage: PBTestMessage = ProtoableBuilder[TestMessage, PBTestMessage] .setField(_.getIntValue, _.intValue + 1) diff --git a/pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala b/pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala index f77747a..7f4ccdd 100644 --- a/pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala +++ b/pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala @@ -2,6 +2,7 @@ package pbconverts import org.scalatest.funsuite.AnyFunSuite import pbconverts.ConversionTest.PBTestMessage +import pbconverts.ConversionTest.PBPerson class ScalableBuilderSpec extends AnyFunSuite { test("test ScalableBuilder") { @@ -9,6 +10,18 @@ class ScalableBuilderSpec extends AnyFunSuite { assertTestMessage(TestMessage.zero) } + test("setFieldValue") { + val pbPerson = PBPerson.newBuilder.setId(1).setName("name").build + val person = ScalableBuilder[Person, PBPerson] + .setFieldValue(_.name, "my name") + .build + .toScala(pbPerson) + + assert(person.name == "my name") + assert(person.id == 1) + } + + def assertTestMessage(testMessage: TestMessage) = { val pbTestMessage = Protoable[TestMessage, PBTestMessage].toProto(testMessage) val testMessage2 = ScalableBuilder[TestMessage, PBTestMessage] From f2b391fb36f1a123fe9f0fbccf50c2b88be7173e Mon Sep 17 00:00:00 2001 From: changvvb Date: Sat, 18 Dec 2021 17:55:01 +0800 Subject: [PATCH 10/17] support scala 3 --- build.sbt | 114 +++-- .../pbconverts/MacroCache.scala | 2 +- .../scala-2/pbconverts/ProtoScalable.scala | 16 + .../pbconverts/ProtoScalableMacro.scala | 415 ++++++++++++++++++ .../main/scala-2/pbconverts/Protoable.scala | 77 ++++ .../scala-2/pbconverts/ProtoableBuilder.scala | 16 + .../main/scala-2/pbconverts/Scalable.scala | 54 +++ .../scala-2/pbconverts/ScalableBuilder.scala | 14 + .../pbconverts/ScalableImplicits.scala | 44 -- .../main/scala-3/pbconverts/MacroCache.scala | 7 + .../pbconverts/ProtoScalable.scala | 0 .../pbconverts/ProtoScalableMacro.scala | 0 .../pbconverts/Protoable.scala | 0 .../pbconverts/ProtoableBuilder.scala | 0 .../pbconverts/Scalable.scala | 0 .../pbconverts/ScalableBuilder.scala | 0 .../pbconverts/ScalableImplicits.scala | 0 .../src/main/scala/pbconverts/Converter.scala | 4 +- .../src/main/scala/pbconverts/Test.scala | 7 - .../scala/pbconverts/pbconverts/Test$.class | Bin 694 -> 0 bytes .../scala/pbconverts/pbconverts/Test.class | Bin 145 -> 0 bytes .../scala/pbconverts/pbconverts/Test.tasty | Bin 518 -> 0 bytes .../pbconverts/pbconverts/TestObj$.class | Bin 685 -> 0 bytes .../scala/pbconverts/pbconverts/TestObj.class | Bin 303 -> 0 bytes .../scala/pbconverts/pbconverts/TestObj.tasty | Bin 519 -> 0 bytes .../src/test/scala/pbconverts/MapSpec.scala | 1 - .../src/test/scala/pbconverts/Person.scala | 4 +- .../pbconverts/ScalableBuilderSpec.scala | 3 +- .../test/scala/pbconverts/TestMessage.scala | 4 +- 29 files changed, 663 insertions(+), 119 deletions(-) rename pbconverts/src/main/{scala => scala-2}/pbconverts/MacroCache.scala (76%) create mode 100644 pbconverts/src/main/scala-2/pbconverts/ProtoScalable.scala create mode 100644 pbconverts/src/main/scala-2/pbconverts/ProtoScalableMacro.scala create mode 100644 pbconverts/src/main/scala-2/pbconverts/Protoable.scala create mode 100644 pbconverts/src/main/scala-2/pbconverts/ProtoableBuilder.scala create mode 100644 pbconverts/src/main/scala-2/pbconverts/Scalable.scala create mode 100644 pbconverts/src/main/scala-2/pbconverts/ScalableBuilder.scala delete mode 100644 pbconverts/src/main/scala-3.00/pbconverts/ScalableImplicits.scala create mode 100644 pbconverts/src/main/scala-3/pbconverts/MacroCache.scala rename pbconverts/src/main/{scala => scala-3}/pbconverts/ProtoScalable.scala (100%) rename pbconverts/src/main/{scala => scala-3}/pbconverts/ProtoScalableMacro.scala (100%) rename pbconverts/src/main/{scala => scala-3}/pbconverts/Protoable.scala (100%) rename pbconverts/src/main/{scala => scala-3}/pbconverts/ProtoableBuilder.scala (100%) rename pbconverts/src/main/{scala => scala-3}/pbconverts/Scalable.scala (100%) rename pbconverts/src/main/{scala => scala-3}/pbconverts/ScalableBuilder.scala (100%) rename pbconverts/src/main/{scala => scala-3}/pbconverts/ScalableImplicits.scala (100%) delete mode 100644 pbconverts/src/main/scala/pbconverts/Test.scala delete mode 100644 pbconverts/src/main/scala/pbconverts/pbconverts/Test$.class delete mode 100644 pbconverts/src/main/scala/pbconverts/pbconverts/Test.class delete mode 100644 pbconverts/src/main/scala/pbconverts/pbconverts/Test.tasty delete mode 100644 pbconverts/src/main/scala/pbconverts/pbconverts/TestObj$.class delete mode 100644 pbconverts/src/main/scala/pbconverts/pbconverts/TestObj.class delete mode 100644 pbconverts/src/main/scala/pbconverts/pbconverts/TestObj.tasty diff --git a/build.sbt b/build.sbt index 4cf09f9..23af30a 100644 --- a/build.sbt +++ b/build.sbt @@ -1,79 +1,77 @@ import sbt._ -//lazy val scala213 = "2.13.4" -//lazy val scala212 = "2.12.12" +lazy val scala213 = "2.13.6" +lazy val scala212 = "2.12.14" lazy val scala3 = "3.1.0" -//lazy val supportedScalaVersions = List(scala212, scala213) +lazy val supportedScalaVersions = List(scala212, scala213) val commonSettings = Seq( scalaVersion := scala3, scalacOptions += "-language:experimental.macros", organization := "com.github.changvvb", -// crossScalaVersions := supportedScalaVersions, + crossScalaVersions := supportedScalaVersions, releasePublishArtifactsAction := PgpKeys.publishSigned.value ) -// lazy val `scala-protobuf-java-macro` = project.in(file("pbconverts-macro")) -// // .settings(libraryDependencies ++= Seq("org.scala-lang" % "scala-reflect" % scalaVersion.value)) -// .settings(commonSettings) -// .enablePlugins(ProtobufPlugin) - lazy val `scala-protobuf-java` = project.in(file("pbconverts")) .settings(libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.9" % "test") + .settings(libraryDependencies ++= { + CrossVersion.partialVersion(scalaVersion.value) match { + case Some((2, _)) => Seq("org.scala-lang" % "scala-reflect" % scalaVersion.value) + case _ => Nil + } + }) .settings(commonSettings) - // .dependsOn(`scala-protobuf-java-macro`) .enablePlugins(ProtobufTestPlugin) lazy val root = project.in(file(".")).withId("root") .aggregate(`scala-protobuf-java`) .settings(publishArtifact := false) -//scalafmtOnCompile in ThisBuild := true - -// publish - -// releasePublishArtifactsAction in ThisBuild := releaseStepCommandAndRemaining("+publishSigned") - -// publishTo in ThisBuild := { -// val nexus = "https://oss.sonatype.org/" -// if (version.value.trim.endsWith("SNAPSHOT")) -// Some("snapshots" at nexus + "content/repositories/snapshots") -// else -// Some("releases" at nexus + "service/local/staging/deploy/maven2") -// } - -// publishMavenStyle in ThisBuild := true - -// credentials in ThisBuild += Credentials(Path.userHome / ".ivy2" / ".credentials_sonatype") - -// publishArtifact in Test := false - -// pomIncludeRepository in ThisBuild := { _ => false } - -// homepage in ThisBuild := Some(url("https://github.com/changvvb/scala-protobuf-java")) - -// pomExtra in ThisBuild := { -// -// -// The Apache Software License, Version 2.0 -// http://www.apache.org/licenses/LICENSE-2.0.txt -// repo -// -// -// -// scm:git:git@github.com:changvvb/scala-protobuf-java.git -// scm:git:git@github.com:changvvb/scala-protobuf-java.git -// https://github.com/changvvb/scala-protobuf-java -// -// -// -// changvvb -// Weiwei Chang -// changvvb@gmail.com -// -// -// } - -// publishConfiguration in ThisBuild := publishConfiguration.value.withOverwrite(true) -// publishLocalConfiguration in ThisBuild := publishLocalConfiguration.value.withOverwrite(true) +ThisBuild / scalafmtOnCompile := true + +ThisBuild / releasePublishArtifactsAction := releaseStepCommandAndRemaining("+publishSigned") + +ThisBuild / publishTo := { + val nexus = "https://oss.sonatype.org/" + if (version.value.trim.endsWith("SNAPSHOT")) + Some("snapshots" at nexus + "content/repositories/snapshots") + else + Some("releases" at nexus + "service/local/staging/deploy/maven2") +} + +ThisBuild / publishMavenStyle := true + +ThisBuild / credentials += Credentials(Path.userHome / ".ivy2" / ".credentials_sonatype") + +Test / publishArtifact := false + +ThisBuild / pomIncludeRepository := { _ => false } + +ThisBuild / homepage := Some(url("https://github.com/changvvb/scala-protobuf-java")) + +ThisBuild / pomExtra := { + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + scm:git:git@github.com:changvvb/scala-protobuf-java.git + scm:git:git@github.com:changvvb/scala-protobuf-java.git + https://github.com/changvvb/scala-protobuf-java + + + + changvvb + Weiwei Chang + changvvb@gmail.com + + +} + +ThisBuild / publishConfiguration := publishConfiguration.value.withOverwrite(true) +ThisBuild / publishLocalConfiguration := publishLocalConfiguration.value.withOverwrite(true) diff --git a/pbconverts/src/main/scala/pbconverts/MacroCache.scala b/pbconverts/src/main/scala-2/pbconverts/MacroCache.scala similarity index 76% rename from pbconverts/src/main/scala/pbconverts/MacroCache.scala rename to pbconverts/src/main/scala-2/pbconverts/MacroCache.scala index 295e531..14da99b 100644 --- a/pbconverts/src/main/scala/pbconverts/MacroCache.scala +++ b/pbconverts/src/main/scala-2/pbconverts/MacroCache.scala @@ -9,5 +9,5 @@ object MacroCache { def getBuilderId: Int = builderCount.synchronized { builderCount += 1; builderCount } def getIdentityId: Int = identityCount.synchronized { identityCount += 1; identityCount } - lazy val builderFunctionTrees: mutable.Map[String, mutable.Map[String, Any]] = mutable.Map.empty + lazy val builderFunctionTrees: mutable.Map[Int, mutable.Map[String, Any]] = mutable.Map.empty } diff --git a/pbconverts/src/main/scala-2/pbconverts/ProtoScalable.scala b/pbconverts/src/main/scala-2/pbconverts/ProtoScalable.scala new file mode 100644 index 0000000..189dd7c --- /dev/null +++ b/pbconverts/src/main/scala-2/pbconverts/ProtoScalable.scala @@ -0,0 +1,16 @@ +package pbconverts + +trait ProtoScalable[S, P] extends Protoable[S, P] with Scalable[S, P] + +object ProtoScalable { + + def apply[S <: Product, P]: ProtoScalable[S, P] = macro ProtoScalableMacro.convertsImpl[S, P] + + def apply[S, P](toProtoFun: S ⇒ P, toScalaFun: P ⇒ S): ProtoScalable[S, P] = + new ProtoScalable[S, P] { + + override def toScala(proto: P): S = toScalaFun(proto) + + override def toProto(entity: S): P = toProtoFun(entity) + } +} diff --git a/pbconverts/src/main/scala-2/pbconverts/ProtoScalableMacro.scala b/pbconverts/src/main/scala-2/pbconverts/ProtoScalableMacro.scala new file mode 100644 index 0000000..aefc355 --- /dev/null +++ b/pbconverts/src/main/scala-2/pbconverts/ProtoScalableMacro.scala @@ -0,0 +1,415 @@ +package pbconverts + +import com.google.protobuf.ByteString + +import scala.collection.mutable +import scala.reflect.macros.whitebox + +// scalastyle:off number.of.methods +class ProtoScalableMacro(val c: whitebox.Context) { + import c.universe._ + + private[this] def packageName: Tree = q"_root_.pbconverts" + private[this] def builderIdent = Ident(TermName("builder")) + private[this] def entityIdent = Ident(TermName("entity")) + private[this] def protoIdent = Ident(TermName("proto")) + private[this] def implicitlyProtoable(entityType: Type, protoType: Type) = q"implicitly[$packageName.Protoable[$entityType,$protoType]]" + + private[this] def implicitlyScalable(entityType: Type, protoType: Type) = q"implicitly[$packageName.Scalable[$entityType,$protoType]]" + + private[this] def isOption(tpe: Type): Boolean = tpe <:< typeOf[Option[_]] + + private[this] def isIterable(tpe: Type): Boolean = + (tpe <:< typeOf[Iterable[_]] + || tpe <:< typeOf[Array[_]] + || tpe <:< typeOf[java.lang.Iterable[_]]) && !(tpe <:< typeOf[Map[_, _]] || tpe <:< typeOf[ByteString]) + + private[this] def isMap(tpe: Type): Boolean = tpe <:< typeOf[Map[_, _]] || tpe <:< typeOf[java.util.Map[_, _]] + + private[this] def getBuilderType(protoType: Type): Type = { + protoType.companion.member(TermName("newBuilder")).asTerm.alternatives.head.asMethod.returnType + } + + trait Processor { + + def caseClassType: Type + def protoType: Type + + def scalaTreeType: Type + def protoValueType: Type + + def resolvedCaseClassFieldType: Type = resolveFieldType(caseClassType, scalaTreeType) + + def tree: Option[Tree] + } + + // Convert expr (`scalaTree` in this class) to protobuf value + class ToProtoProcessor( + scalaTree: Tree, + override val scalaTreeType: Type, + override val caseClassType: Type, + override val protoType: Type, + override val protoFieldName: String + ) extends ProtoFieldAnalyst { + + private[this] def toProto(t1: Type, t2: Type): Tree = { + if (t1 <:< t2) { + scalaTree + } else { + q"${implicitlyProtoable(t1, t2)}.toProto($scalaTree)" + } + } + + override def protoValueType: Type = protoValueSetterType + + def optTree(optFieldType: Type): c.universe.Tree = { + val tree = if (isIterable(protoValueType)) { + seqTree(optFieldType) + } else if (isMap(protoValueType)) { + mapTree(optFieldType) + } else { + defaultTree(optFieldType) + } + If(q"$scalaTree.isDefined", tree, EmptyTree) + } + + def seqTree(iterableType: Type): c.universe.Tree = { + val listType = builderType.member(addAllMethodName).asMethod.paramLists.head.head.typeSignature + val valueTree = toProto(iterableType, listType) + q"${builderIdent}.$addAllMethodName($valueTree)" + } + + def mapTree(mapType: Type): c.universe.Tree = { + val putAllMapType = builderType.member(putAllMethodName).asMethod.paramLists.head.head.typeSignature + val valueTree = toProto(mapType, putAllMapType) + q"${builderIdent}.$putAllMethodName($valueTree)" + } + + def defaultTree(fieldType: Type): c.universe.Tree = { + val valueTree = toProto(fieldType, protoValueType) + q"${builderIdent}.$setField(${valueTree})" + } + + override def tree: Option[Tree] = { + if (protoValueType == NoType) { + None + } else { + val _tree = if (isOption(scalaTreeType)) { + optTree(resolvedCaseClassFieldType) + } else if (isIterable(protoValueType)) { + seqTree(resolvedCaseClassFieldType) + } else if (isMap(protoValueType)) { + mapTree(resolvedCaseClassFieldType) + } else { + defaultTree(resolvedCaseClassFieldType) + } + + if (scalaTreeType <:< typeOf[AnyRef]) { + val notNullCondition = q"$scalaTree ne null" + Some(If(notNullCondition, _tree, EmptyTree)) + } else { + Some(_tree) + } + } + } + } + + // Convert expr (`protoValueTree` in this class) to case class filed value + case class ToScalaProcessor(caseClassSelector: MethodSymbol, protoValueTree: Tree, protoValueType: Type, caseClassType: Type, protoType: Type) + extends AbstractToScalaProcessor + + trait AbstractToScalaProcessor extends Processor { + + def caseClassSelector: MethodSymbol + + def protoValueTree: Tree + + override def scalaTreeType: Type = caseClassSelector.returnType + + protected def toScala(t1: Type, t2: Type, value: Tree) = { + if (t2 <:< t1) { + value + } else { + q"${implicitlyScalable(t1, t2)}.toScala($value)" + } + } + + def optTree(optType: Type): c.universe.Tree = defaultTree(optType) + + def defaultTree(fieldType: Type): Tree = { + q"$caseClassSelector = ${toScala(fieldType, protoValueType, protoValueTree)}" + } + + override def tree: Option[Tree] = + if (protoValueType == NoType) { + None + } else { + if (isOption(scalaTreeType)) { + Some(optTree(resolvedCaseClassFieldType)) + } else { + Some(defaultTree(resolvedCaseClassFieldType)) + } + } + } + + // Contain some methods and vals to analyze Protobuf fields + trait ProtoFieldAnalyst extends Processor { + def protoFieldName: String + + val builderType = getBuilderType(protoType) + + def addAllMethodName: TermName = TermName(s"addAll$protoFieldName") + def putAllMethodName: TermName = TermName(s"putAll$protoFieldName") + + def addField: TermName = TermName(s"add$protoFieldName") + def putField: TermName = TermName(s"put$protoFieldName") + def setField: TermName = TermName(s"set$protoFieldName") + def getField: TermName = TermName(s"get$protoFieldName") + def getMapField: TermName = TermName(s"get${protoFieldName}Map") + def getListField: TermName = TermName(s"get${protoFieldName}List") + def builderSetter: TermName = if (isIterable(scalaTreeType)) addAllMethodName else setField + + val protoValueTree: Tree = { + if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 + q"$protoIdent.$getListField" + } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map + q"$protoIdent.$getMapField" + } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 + q"$protoIdent.$getField" + } else { + q"" + } + } + + lazy val protoValueSetterType: Type = { + val pbBuilderType = typeOf[com.google.protobuf.Message.Builder] + val setterOpt = if (builderType.member(addField) != NoSymbol) { + Some(builderType.member(addAllMethodName)) + } else if (builderType.member(putField) != NoSymbol) { + Some(builderType.member(putAllMethodName)) + } else if (builderType.member(setField) != NoSymbol) { + Some(builderType.member(setField)) + } else { + None + } + setterOpt.fold(NoType)(_.alternatives.map(_.asMethod.paramLists.head.head.typeSignature).find(t ⇒ !(t <:< pbBuilderType)).get) + } + + lazy val protoValueGetterType: Type = { + if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 + protoType.member(getListField).typeSignature.resultType + } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map + protoType.member(getMapField).typeSignature.resultType + } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 + protoType.member(getField).typeSignature.resultType + } else { + NoType + } + } + + } + + // Convert scala clase class field value to protobuf value + case class ToProtoFieldProcessor(accessor: MethodSymbol, override val caseClassType: Type, override val protoType: Type) + extends ToProtoProcessor(q"$entityIdent.$accessor", accessor.returnType, caseClassType, protoType, accessor.name.toString.capitalize) + + // Convert protobuf value to case class filed value + case class ToScalaFieldProcessor(accessor: MethodSymbol, override val caseClassType: Type, override val protoType: Type) + extends AbstractToScalaProcessor + with ProtoFieldAnalyst { + + override def caseClassSelector: MethodSymbol = accessor + + override def protoFieldName: String = accessor.name.toString.capitalize + + override def protoValueType: Type = protoValueGetterType + + override def optTree(optType: Type): c.universe.Tree = { + val hasProtoField = TermName(s"has$protoFieldName") + if (protoType.member(hasProtoField) == NoSymbol) { + defaultTree(optType) + } else { + q"$caseClassSelector = if (${protoIdent}.$hasProtoField) ${toScala(optType, protoValueType, protoValueTree)} else None" + } + } + } + + private[this] def resolveFieldType(entityType: Type, originType: Type): Type = + originType.asSeenFrom(entityType, entityType.typeSymbol.asClass) + + private[this] def resolveType[T: WeakTypeTag]: Type = { + val tpe = weakTypeOf[T] + tpe.dealias + } + + private[this] def getCaseAccessors(caseClassType: Type): Seq[MethodSymbol] = { + caseClassType.members.collect { case m: MethodSymbol if m.isCaseAccessor ⇒ m }.toSeq.reverse + } + + private[this] def defaultProtoableFieldConvertTrees(caseClassType: Type, protoType: Type): Map[String, Tree] = { + getCaseAccessors(caseClassType).flatMap { a ⇒ + val p = ToProtoFieldProcessor(a, caseClassType, protoType) + p.tree.map(p.protoFieldName -> _) + }.toMap + } + + private[this] def protoableBody(caseClassType: Type, protoType: Type, protoableFieldConvertTrees: Iterable[Tree]): Tree = { + q""" + override def toProto(${entityIdent.name.toTermName}: $caseClassType): $protoType = { + val ${builderIdent} = ${protoType.typeSymbol.companion}.newBuilder() + ..$protoableFieldConvertTrees + $builderIdent.build() + } + """ + } + + private def defalutScalableFieldConvertTrees(caseClassType: Type, protoType: Type): Map[String, Tree] = { + getCaseAccessors(caseClassType).flatMap(accessor ⇒ ToScalaFieldProcessor(accessor, caseClassType, protoType).tree.map(accessor.name.toString -> _)).toMap + } + + private def scalableBody(caseClassType: Type, protoType: Type, scalableFieldConvertTrees: Iterable[Tree]): Tree = { + q""" + override def toScala(${protoIdent.name.toTermName} :$protoType): $caseClassType = { + new ${caseClassType.typeSymbol} ( + ..${scalableFieldConvertTrees} + ) + } + """ + } + + def scalasImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { + val caseClassType = resolveType[T] + val protoType = resolveType[M] + val scalableFieldConvertTrees = defalutScalableFieldConvertTrees(caseClassType, protoType).values + scalasImpl(caseClassType, protoType, scalableFieldConvertTrees, Nil) + } + + private[this] def scalasImpl(caseClassType: Type, protoType: Type, scalableFieldConvertTrees: Iterable[Tree], perTrees: Iterable[Tree]): Tree = { + q""" + ..$perTrees + new $packageName.Scalable[$caseClassType, $protoType] { ${scalableBody(caseClassType, protoType, scalableFieldConvertTrees)} } + """ + } + + def protosImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { + val caseClassType = resolveType[T] + val protoType = resolveType[M] + protosImpl(caseClassType, protoType, defaultProtoableFieldConvertTrees(caseClassType, protoType).values, Nil) + } + + private[this] def protosImpl(caseClassType: Type, protoType: Type, protoableFieldConvertTrees: Iterable[Tree], perTrees: Iterable[Tree]): Tree = { + q""" + ..$perTrees + new $packageName.Protoable[$caseClassType,$protoType] { ${protoableBody(caseClassType, protoType, protoableFieldConvertTrees)} } + """ + } + + def convertsImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { + val caseClassType = resolveType[T] + val protoType = resolveType[M] + q""" + new $packageName.ProtoScalable[${resolveType[T]}, ${resolveType[M]}] { + ${scalableBody(caseClassType, protoType, defalutScalableFieldConvertTrees(caseClassType, protoType).values)} + ${protoableBody(caseClassType, protoType, defaultProtoableFieldConvertTrees(caseClassType, protoType).values)} + } + """ + } + + def buildProtoableImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { + val caseClassType = resolveType[T] + val protoType = resolveType[M] + val customTrees = MacroCache.builderFunctionTrees.getOrElse(getBuilderId(), mutable.Map.empty) + val (fixedCustomTrees, preTrees) = customTrees.map { case (key, tree) ⇒ + tree match { // setField + case buildFunction: Function ⇒ + val functionName = TermName("builderFunction$" + MacroCache.getIdentityId) + val fromType = buildFunction.tpe.typeArgs.last // buildFunction 的返回值 + val buildExpr = new ToProtoProcessor(q"$functionName($entityIdent)", fromType, caseClassType, protoType, key).tree.get + (key -> buildExpr) -> q"val $functionName = $buildFunction" + case value: Tree ⇒ // setFieldValue + val identity = TermName("identity$" + MacroCache.getIdentityId) + val buildExpr = new ToProtoProcessor(q"$identity", value.tpe, caseClassType, protoType, key).tree.get + (key -> buildExpr) -> q"val $identity = $value" + } + }.unzip + val protoableFieldConvertTrees = (defaultProtoableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values + protosImpl(caseClassType, protoType, protoableFieldConvertTrees, preTrees) + } + + def buildScalableImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { + val caseClassType = resolveType[T] + val protoType = resolveType[M] + val builderId = getBuilderId() + val customTrees = MacroCache.builderFunctionTrees.getOrElse(builderId, mutable.Map.empty) + val entityType = resolveType[T] + + val (fixedCustomTrees, preTrees) = customTrees.map { case (key, tree) ⇒ + val selector = entityType.member(TermName(key)) + tree match { + case buildFunction: Function ⇒ // setField + val functionName = TermName("builderFunction$" + MacroCache.getIdentityId) + val expr = new ToScalaProcessor(selector.asMethod, q"$functionName($protoIdent)", buildFunction.body.tpe, resolveType[T], resolveType[M]).tree.get + (key -> expr) -> q"val $functionName = $buildFunction" + case value: Tree ⇒ // setFieldValue + val identity = TermName("identity$" + MacroCache.getIdentityId) + val expr = new ToScalaProcessor(selector.asMethod, q"$identity", value.tpe, resolveType[T], resolveType[M]).tree.get + (key -> expr) -> q"val $identity = $value" + } + }.unzip + + val scalableFieldConvertTrees = (defalutScalableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values + scalasImpl(caseClassType, protoType, scalableFieldConvertTrees, preTrees) + } + + def setScalaFieldImpl[T: WeakTypeTag, M: WeakTypeTag, TF: WeakTypeTag, MF: WeakTypeTag](scalaField: Tree, value: Tree): Tree = { + val Function(_, Select(_, termName)) = scalaField + val builderId = getBuilderId() + MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(termName.toString, value) + q"new ${c.prefix.actualType}" + } + + def setProtoFieldImpl[T: WeakTypeTag, M: WeakTypeTag, TF: WeakTypeTag, MF: WeakTypeTag](protoFieldSelector: Tree, value: Tree): Tree = { + val getter = "^get(\\w+)$".r + val listGetter = "^get(\\w+)List$".r + val mapGetter = "^get(\\w+)Map$".r + val setter = protoFieldSelector.find { + case _: Select ⇒ true + case _: Tree ⇒ false + } match { + case Some(select: Select) ⇒ + select.name.toString match { + case mapGetter(n) if select.tpe.resultType <:< typeOf[java.util.Map[_, _]] ⇒ n + case listGetter(n) if select.tpe.resultType <:< typeOf[java.util.List[_]] ⇒ n + case getter(n) ⇒ n + case _ ⇒ c.abort(protoFieldSelector.pos, "Invalid setter") + } + case _ ⇒ c.abort(protoFieldSelector.pos, "Invalid setter") + } + val builderId = getBuilderId() + MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(setter, value) + q"new ${c.prefix.actualType}" + } + + val annoBuilderPrefix = "AnonBuilder$" + + def scalableBuilderApply[T: WeakTypeTag, M: WeakTypeTag]: Tree = { + val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) + q""" + class $className extends $packageName.ScalableBuilder[${resolveType[T]}, ${resolveType[M]}] + new $className + """ + } + + def protoableBuilderApply[T: WeakTypeTag, M: WeakTypeTag]: Tree = { + val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) + q""" + class $className extends $packageName.ProtoableBuilder[${resolveType[T]}, ${resolveType[M]}] + new $className + """ + } + + private[this] def getBuilderId() = { + c.prefix.actualType.toString.replace(annoBuilderPrefix, "").toInt + } + +} diff --git a/pbconverts/src/main/scala-2/pbconverts/Protoable.scala b/pbconverts/src/main/scala-2/pbconverts/Protoable.scala new file mode 100644 index 0000000..7d7cb8f --- /dev/null +++ b/pbconverts/src/main/scala-2/pbconverts/Protoable.scala @@ -0,0 +1,77 @@ +package pbconverts + +import java.time.ZonedDateTime + +import com.google.protobuf.{BoolValue, DoubleValue, FloatValue, Int32Value, Int64Value, StringValue, Timestamp} + +import scala.collection.JavaConverters._ + +trait Protoable[-S, +P] { + def toProto(entity: S): P +} + +object Protoable { + + def apply[S <: Product, P]: Protoable[S, P] = macro ProtoScalableMacro.protosImpl[S, P] + + def apply[S, P](convert: S ⇒ P): Protoable[S, P] = x => convert(x) + + implicit val javaDoubleProtoable = Protoable[Double, java.lang.Double](_.toDouble) + implicit val javaFloatProtoable = Protoable[Float, java.lang.Float](_.toFloat) + implicit val javaIntergerProtoable = Protoable[Int, java.lang.Integer](_.toInt) + implicit val javaLongProtoable = Protoable[Long, java.lang.Long](_.toLong) + implicit val javaCharacterProtoable = Protoable[Char, java.lang.Character](_.toChar) + implicit val javaByteProtoable = Protoable[Byte, java.lang.Byte](_.toByte) + + implicit val stringValueProtoable = Protoable[String, StringValue](StringValue.of) + implicit val doubleValueProtoable = Protoable[Double, DoubleValue](DoubleValue.of) + implicit val floatValueProtoable = Protoable[Float, FloatValue](FloatValue.of) + implicit val int32ValueProtoable = Protoable[Int, Int32Value](Int32Value.of) + implicit val boolValueProtoable = Protoable[Boolean, BoolValue](BoolValue.of) + implicit val int64ValueProtoable = Protoable[Long, Int64Value](Int64Value.of) + + implicit val zonedDateTimeProtoable = Protoable[ZonedDateTime, Timestamp] { entity ⇒ + Timestamp.newBuilder().setSeconds(entity.toEpochSecond).setNanos(entity.getNano).build() + } + + implicit def iterableProtoable[S, P](implicit protoable: Protoable[S, P]): Protoable[scala.Iterable[S], java.util.List[P]] = + Protoable[scala.Iterable[S], java.util.List[P]] { entity ⇒ + entity.toList.map(protoable.toProto).asJava + } + + implicit def iterableProtoable2[S]: Protoable[scala.Iterable[S], java.util.List[S]] = + Protoable[scala.Iterable[S], java.util.List[S]] { entity ⇒ entity.toList.asJava } + + implicit def arrayProtoable[S]: Protoable[Array[S], java.util.List[S]] = + Protoable[Array[S], java.util.List[S]] { entity ⇒ entity.toList.asJava } + + implicit def arrayProtoable2[S, P](implicit protoable: Protoable[S, P]): Protoable[Array[S], java.lang.Iterable[P]] = + Protoable[Array[S], java.util.List[P]] { entity ⇒ + entity.toList.map(protoable.toProto).asJava + } + + implicit def optProtoable[F, Target <: Any](implicit protoable: Protoable[F, Target]): Protoable[Option[F], Target] = + Protoable[Option[F], Target] { entity: Option[F] ⇒ + entity.map(protoable.toProto).getOrElse(None.orNull.asInstanceOf[Target]) + } + + implicit def optProtoable2[T]: Protoable[Option[T], T] = + Protoable[Option[T], T] { opt: Option[T] => opt.getOrElse(None.orNull.asInstanceOf[T]) } + + implicit def mapProtoable1[K, V]: Protoable[Map[K, V], java.util.Map[K, V]] = + Protoable[Map[K, V], java.util.Map[K, V]] { m ⇒ m.asJava } + + implicit def mapProtoable2[K1, K2, V](implicit kProtoable: Protoable[K1, K2]): Protoable[Map[K1, V], java.util.Map[K2, V]] = + Protoable[Map[K1, V], java.util.Map[K2, V]] { m ⇒ m.map { case (k, v) ⇒ kProtoable.toProto(k) -> v }.asJava } + + implicit def mapProtoable3[K, V1, V2](implicit vProtoable: Protoable[V1, V2]): Protoable[Map[K, V1], java.util.Map[K, V2]] = + Protoable[Map[K, V1], java.util.Map[K, V2]] { m ⇒ m.map { case (k, v) ⇒ k -> vProtoable.toProto(v) }.asJava } + + implicit def mapProtoable4[K1, K2, V1, V2](implicit + kProtoable: Protoable[K1, K2], + vProtoable: Protoable[V1, V2] + ): Protoable[Map[K1, V1], java.util.Map[K2, V2]] = + Protoable[Map[K1, V1], java.util.Map[K2, V2]] { m ⇒ + m.map { case (k, v) ⇒ kProtoable.toProto(k) -> vProtoable.toProto(v) }.asJava + } +} diff --git a/pbconverts/src/main/scala-2/pbconverts/ProtoableBuilder.scala b/pbconverts/src/main/scala-2/pbconverts/ProtoableBuilder.scala new file mode 100644 index 0000000..3f1ba0f --- /dev/null +++ b/pbconverts/src/main/scala-2/pbconverts/ProtoableBuilder.scala @@ -0,0 +1,16 @@ +package pbconverts + +import com.google.protobuf.Message + +class ProtoableBuilder[S, P <: Message]() { + + def setField[SF, PF](protoFieldSelector: P ⇒ PF, value: S ⇒ SF): this.type = macro ProtoScalableMacro.setProtoFieldImpl[S, P, SF, PF] + + def setFieldValue[SF, PF](protoFieldSelector: P ⇒ PF, value: SF): this.type = macro ProtoScalableMacro.setProtoFieldImpl[S, P, SF, PF] + + def build: Protoable[S, P] = macro ProtoScalableMacro.buildProtoableImpl[S, P] +} + +object ProtoableBuilder { + def apply[S, P <: Message]: ProtoableBuilder[S, P] = macro ProtoScalableMacro.protoableBuilderApply[S, P] +} diff --git a/pbconverts/src/main/scala-2/pbconverts/Scalable.scala b/pbconverts/src/main/scala-2/pbconverts/Scalable.scala new file mode 100644 index 0000000..a65efab --- /dev/null +++ b/pbconverts/src/main/scala-2/pbconverts/Scalable.scala @@ -0,0 +1,54 @@ +package pbconverts + +import java.time.{Instant, ZoneId, ZonedDateTime} + +import com.google.protobuf.{BoolValue, DoubleValue, FloatValue, Int32Value, Int64Value, StringValue, Timestamp} + +import scala.collection.JavaConverters._ +import scala.reflect.ClassTag + +trait Scalable[+S, -P] { + def toScala(proto: P): S +} + +object Scalable extends ScalableImplicits { + + def apply[S <: Product, P]: Scalable[S, P] = macro ProtoScalableMacro.scalasImpl[S, P] + + def apply[S, P](convert: P ⇒ S): Scalable[S, P] = x => convert(x) + + implicit val javaIntegerScalable = Scalable[Int, java.lang.Integer](_.toInt) + implicit val javaLongScalable = Scalable[Long, java.lang.Long](_.toLong) + implicit val javaDoubleScalable = Scalable[Double, java.lang.Double](_.toDouble) + implicit val javaFloatScalable = Scalable[Float, java.lang.Float](_.toFloat) + implicit val javaCharacterScalable = Scalable[Char, java.lang.Character](_.toChar) + implicit val javaByteScalable = Scalable[Byte, java.lang.Byte](_.toByte) + + implicit val stringValueScalable = Scalable[String, StringValue](_.getValue) + implicit val int32ValueScalable = Scalable[Int, Int32Value](_.getValue) + implicit val int64ValueScalable = Scalable[Long, Int64Value](_.getValue) + implicit val doubleValueScalable = Scalable[Double, DoubleValue](_.getValue) + implicit val floatValueScalable = Scalable[Float, FloatValue](_.getValue) + implicit val boolValueScalable = Scalable[Boolean, BoolValue](_.getValue) + + implicit val zonedDateTimeProtoable = Scalable[ZonedDateTime, Timestamp] { proto ⇒ + Instant.ofEpochSecond(proto.getSeconds, proto.getNanos).atZone(ZoneId.systemDefault()) + } + + // java.lang.Iterable[M] => Array[T] + implicit def arrayScalable[S: ClassTag, P](implicit scalable: Scalable[S, P]): Scalable[Array[S], java.lang.Iterable[P]] = + Scalable { proto ⇒ + proto.asScala.map(scalable.toScala).toArray + } + + implicit def arrayScalable2[T: ClassTag]: Scalable[Array[T], java.lang.Iterable[T]] = Scalable { proto ⇒ proto.asScala.toArray } + + // M => Option[T] + implicit def optScalable[S, P](implicit scalable: Scalable[S, P]): Scalable[Option[S], P] = + Scalable { proto ⇒ + Option(scalable.toScala(proto)) + } + + implicit def optScalable2[T]: Scalable[Option[T], T] = Scalable(Option(_)) + +} diff --git a/pbconverts/src/main/scala-2/pbconverts/ScalableBuilder.scala b/pbconverts/src/main/scala-2/pbconverts/ScalableBuilder.scala new file mode 100644 index 0000000..2e1ebca --- /dev/null +++ b/pbconverts/src/main/scala-2/pbconverts/ScalableBuilder.scala @@ -0,0 +1,14 @@ +package pbconverts + +class ScalableBuilder[+S, P]() { + + def setField[SF, PF](scalaField: S ⇒ SF, value: P ⇒ PF): ScalableBuilder[S, P] = macro ProtoScalableMacro.setScalaFieldImpl[S, P, SF, PF] + + def setFieldValue[SF, PF](scalaField: S ⇒ SF, value: PF): ScalableBuilder[S, P] = macro ProtoScalableMacro.setScalaFieldImpl[S, P, SF, PF] + + def build: Scalable[S, P] = macro ProtoScalableMacro.buildScalableImpl[S, P] +} + +object ScalableBuilder { + def apply[S, P]: ScalableBuilder[S, P] = macro ProtoScalableMacro.scalableBuilderApply[S, P] +} diff --git a/pbconverts/src/main/scala-3.00/pbconverts/ScalableImplicits.scala b/pbconverts/src/main/scala-3.00/pbconverts/ScalableImplicits.scala deleted file mode 100644 index febbf52..0000000 --- a/pbconverts/src/main/scala-3.00/pbconverts/ScalableImplicits.scala +++ /dev/null @@ -1,44 +0,0 @@ -package pbconverts - -import scala.collection.BuildFrom -import scala.collection.JavaConverters._ -import scala.reflect.ClassTag - -trait ScalableImplicits { - - // java.lang.Iterable[M] => That[T] - implicit def iterableScalable[That[_], T, M](implicit - scalable: Scalable[T, M], - bf: BuildFrom[Seq[_], T, That[T]] - ): Scalable[That[T], java.lang.Iterable[M]] = - Scalable { proto ⇒ - bf.fromSpecific(Seq.empty)(proto.asScala.iterator.map(scalable.toScala)) - } - - implicit def iterableScalable2[That[T], T](implicit bf: BuildFrom[Seq[T], T, That[T]]): Scalable[That[T], java.lang.Iterable[T]] = - Scalable { proto ⇒ - bf.fromSpecific(Seq.empty)(proto.asScala) - } - - // // Repr[M] => That[T] - implicit def iterableSelfScalable[That, Repr <: Iterable[M], T, M](implicit - scalable: Scalable[T, M], - bf: BuildFrom[Iterable[_], T, That] - ): Scalable[That, Repr] = { proto ⇒ - bf.newBuilder(proto.map(scalable.toScala)).result() - } - - implicit def mapScalable4[K1, K2, V1, V2](implicit kScalable: Scalable[K1, K2], vScalable: Scalable[V1, V2]): Scalable[Map[K1, V1], java.util.Map[K2, V2]] = - Scalable[Map[K1, V1], java.util.Map[K2, V2]] { m ⇒ - m.asScala.map { case (k, v) ⇒ kScalable.toScala(k) -> vScalable.toScala(v) }.toMap - } - - implicit def mapScalable3[K, V1, V2](implicit vScalable: Scalable[V1, V2]): Scalable[Map[K, V1], java.util.Map[K, V2]] = - Scalable[Map[K, V1], java.util.Map[K, V2]] { m ⇒ m.asScala.map { case (k, v) ⇒ k -> vScalable.toScala(v) }.toMap } - - implicit def mapScalable2[K1, K2, V](implicit kScalable: Scalable[K1, K2]): Scalable[Map[K1, V], java.util.Map[K2, V]] = - Scalable[Map[K1, V], java.util.Map[K2, V]] { m ⇒ m.asScala.map { case (k, v) ⇒ kScalable.toScala(k) -> v }.toMap } - - implicit def mapScalable1[K, V]: Scalable[Map[K, V], java.util.Map[K, V]] = - Scalable[Map[K, V], java.util.Map[K, V]] { m ⇒ m.asScala.toMap } -} diff --git a/pbconverts/src/main/scala-3/pbconverts/MacroCache.scala b/pbconverts/src/main/scala-3/pbconverts/MacroCache.scala new file mode 100644 index 0000000..c63169a --- /dev/null +++ b/pbconverts/src/main/scala-3/pbconverts/MacroCache.scala @@ -0,0 +1,7 @@ +package pbconverts + +import scala.collection.mutable + +object MacroCache { + lazy val builderFunctionTrees: mutable.Map[String, mutable.Map[String, Any]] = mutable.Map.empty +} diff --git a/pbconverts/src/main/scala/pbconverts/ProtoScalable.scala b/pbconverts/src/main/scala-3/pbconverts/ProtoScalable.scala similarity index 100% rename from pbconverts/src/main/scala/pbconverts/ProtoScalable.scala rename to pbconverts/src/main/scala-3/pbconverts/ProtoScalable.scala diff --git a/pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala b/pbconverts/src/main/scala-3/pbconverts/ProtoScalableMacro.scala similarity index 100% rename from pbconverts/src/main/scala/pbconverts/ProtoScalableMacro.scala rename to pbconverts/src/main/scala-3/pbconverts/ProtoScalableMacro.scala diff --git a/pbconverts/src/main/scala/pbconverts/Protoable.scala b/pbconverts/src/main/scala-3/pbconverts/Protoable.scala similarity index 100% rename from pbconverts/src/main/scala/pbconverts/Protoable.scala rename to pbconverts/src/main/scala-3/pbconverts/Protoable.scala diff --git a/pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala b/pbconverts/src/main/scala-3/pbconverts/ProtoableBuilder.scala similarity index 100% rename from pbconverts/src/main/scala/pbconverts/ProtoableBuilder.scala rename to pbconverts/src/main/scala-3/pbconverts/ProtoableBuilder.scala diff --git a/pbconverts/src/main/scala/pbconverts/Scalable.scala b/pbconverts/src/main/scala-3/pbconverts/Scalable.scala similarity index 100% rename from pbconverts/src/main/scala/pbconverts/Scalable.scala rename to pbconverts/src/main/scala-3/pbconverts/Scalable.scala diff --git a/pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala b/pbconverts/src/main/scala-3/pbconverts/ScalableBuilder.scala similarity index 100% rename from pbconverts/src/main/scala/pbconverts/ScalableBuilder.scala rename to pbconverts/src/main/scala-3/pbconverts/ScalableBuilder.scala diff --git a/pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala b/pbconverts/src/main/scala-3/pbconverts/ScalableImplicits.scala similarity index 100% rename from pbconverts/src/main/scala/pbconverts/ScalableImplicits.scala rename to pbconverts/src/main/scala-3/pbconverts/ScalableImplicits.scala diff --git a/pbconverts/src/main/scala/pbconverts/Converter.scala b/pbconverts/src/main/scala/pbconverts/Converter.scala index ea35e68..e27b012 100644 --- a/pbconverts/src/main/scala/pbconverts/Converter.scala +++ b/pbconverts/src/main/scala/pbconverts/Converter.scala @@ -2,8 +2,8 @@ package pbconverts object Converter { - def toProto[T, M](d: T)(using protoable: Protoable[T, M]): M = protoable.toProto(d) + def toProto[T, M](d: T)(implicit protoable: Protoable[T, M]): M = protoable.toProto(d) - def toScala[T, M](m: M)(using scalable: Scalable[T, M]): T = scalable.toScala(m) + def toScala[T, M](m: M)(implicit scalable: Scalable[T, M]): T = scalable.toScala(m) } diff --git a/pbconverts/src/main/scala/pbconverts/Test.scala b/pbconverts/src/main/scala/pbconverts/Test.scala deleted file mode 100644 index badc1fd..0000000 --- a/pbconverts/src/main/scala/pbconverts/Test.scala +++ /dev/null @@ -1,7 +0,0 @@ -package pbconverts - -object Test { - - given Int = 1 - implicitly[Int].toString -} diff --git a/pbconverts/src/main/scala/pbconverts/pbconverts/Test$.class b/pbconverts/src/main/scala/pbconverts/pbconverts/Test$.class deleted file mode 100644 index c70f63aac58b20f4d0d4f8f68dc4434b0d0645b3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 694 zcmZ8e*-qO)6g}f4m<(oVfELQumXrn_YN7HL)CZt_3X2F(@i=itFleyRcnmFH#UeFQ zk@^AssH%5tL{Vhfck!8X?mhG8@2}qg*3e)WyXZtod?}4h!vmSxx(`O(GjSV>!ZXlk#|)Rwxv-*t83BG(np1XyQ3e|NNB;}Z|`m$w!YLEYOQ|uCd0tGik1D$ zP--k61>hLsC?jAf+f$V?46a8yM{sxu0t}*BrR)X6cpn>$M&ph%O!n)zKTUUZvWf}3 zqyb}jwUH^^m4^0cEVuqI*tSN+Cxo8DG$-_HhTzI5EBEDv7Ln}77lzOxOZmQ`$zrR{ zWw@PmGcBL2u_}r8O!EDQk9kM&OmS0-G;J2kzu{QGTUvfI>5|lFOT}_0JMTzy;M{c{ zCS>c8AjheGZ1Q%JnMi(B4pC`4-?2(2l|lZ}JMCPfD=txw45rQ^Ri7v_ij|cfhHokH zP^Yi+*+I+nyr(QEKp4p>su+DDSjmwaMW&Wt_VJS!X_&^c=09PoCf&c&j diff --git a/pbconverts/src/main/scala/pbconverts/pbconverts/Test.class b/pbconverts/src/main/scala/pbconverts/pbconverts/Test.class deleted file mode 100644 index 811fc5e044f5adef918d51e031776371189143ce..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 145 zcmX^0Z`VEs1_l!bPDTd)f~4g9yt34yl4AXk)Z!9$21Z5(fvm)`ME#t^ymWp4q^#6r zpeQpV0~bhMuQ)j|ClSaA&Mz%WPIb%7No8bU4RH((i3HNYAV~&81||j;pamen%)kaD hnHX3Z*nzYFL&EgGq48D>4BBe@HD?@TVBi2L0s!~JAol50M;2-Fa5hf&r5>>FFnz%$_KtfbWyHzq*_dr)U=gK~(lmYCs<6P{P zgfwjo4QWb$LP2C=VL)9N5gT(CCZviXBN0xSU%k)s%vvCNwrklZ&H9RruJMUX+BB1TL)W0_A@W!~O|YQaFZo$@<*KiEnjqIl(wLySdi zL0DoI8HYsMdH%W!wQ+bFl<|5Hl}yLd@m*qIh!CYFy8x%gT@ZvaY*A#${Oz91_xmaO zpbOFXp8MZjpD}GRF0nxr%yJo1X1jmfbJg=&-1J$ZdO{4snl@Ea>J$D?zk4d8fmqj^ zSdEmu$_s1-O3cF`>on9R@4U=9E#Tm3x5<5FeJn^yV z^ws^86CP^HnR0gT==e+2avNKo+w6I+FP)3v=&=3#Ac6R})@zO6{qO#>(Qqhzk7McA UaM+iA3_is>t&Ne`9=h+`e-W|Y@&Et; diff --git a/pbconverts/src/main/scala/pbconverts/pbconverts/TestObj$.class b/pbconverts/src/main/scala/pbconverts/pbconverts/TestObj$.class deleted file mode 100644 index 889fa39998d2d6a9481422816e2bbd57c7c2fb42..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 685 zcmZ`$TTk0C6#ksFqz&QL0t3cn1B56NL`b}Wco=L?0VWEScyv<>j7)+Y2R42ch=)o; z+7H-|nm7&>s;VuLee6%?yZGeK-(SB0>|lkVe%p@IG7XzTORnStZ!6)U%-~!0Ru*%`8N8#D!}I9tD#KLt4})EXp*@*M zv(MnJH(CLF4Erb{U?`a@nK4xMVpVkba1aEjpjxHV1VeDIr4gs%R`FO+qV+~J7?t$b ziX@@V6C-a#c$9W>CEi0DnI_+L`s1gEDJ#*ZaG-dW?Y?FD;A0vy^tMFYf61ll2t8=n zG+HK?WJn3;Dg8m(p-^LyOvG`1(-!*7PKcovr8Jrrr>W7s2l~x4*Rl8}ZAZCjXNPTi zWeGGOTC?`q^ruRM(S!(Dq+3Xp{7~NLV&sVq4wh)Q1i-^5+JmB<=@Y;+T7<@C=|`i!H(+Hha}gpE15$+p^Ly|2|G%aE*O$AN)5sN&hGwoMQ^`~! zo4zVtywtmwIFqC+rJE`EEy+W0=W~k&gsaO1omMd82KbBE;CGf+rfmV1YU;WV$50)=5&)4@GYWY2oa?^|Hs8S&mka`V@8oCi~hbW4tg=#iP6Is z5Kf*>{%>5%=mwc|Fd#_l^Ugnik<#b_i^dW3nja}Pn_H4_Megy7d@bOC<>hJyD);YZT-hXsH9!sC2 aNIDyj`_k9ZyJ+YhZT_*OlUmgpT7LnvRo&D8 diff --git a/pbconverts/src/test/scala/pbconverts/MapSpec.scala b/pbconverts/src/test/scala/pbconverts/MapSpec.scala index e204f96..affaab1 100644 --- a/pbconverts/src/test/scala/pbconverts/MapSpec.scala +++ b/pbconverts/src/test/scala/pbconverts/MapSpec.scala @@ -20,7 +20,6 @@ class MapSpec extends AnyFunSuite { case class TestBytes(m: Map[String, Int]) test("test conversion between bytes in protobuf and Map in case class") { - PBTestBytes.newBuilder().setTestBytes val pbTest1 = ProtoableBuilder[TestBytes, PBTestBytes] .setField(_.getTestBytes, x => ByteString.copyFromUtf8(x.m.keys.mkString(","))) .build diff --git a/pbconverts/src/test/scala/pbconverts/Person.scala b/pbconverts/src/test/scala/pbconverts/Person.scala index ad99548..bae02f5 100644 --- a/pbconverts/src/test/scala/pbconverts/Person.scala +++ b/pbconverts/src/test/scala/pbconverts/Person.scala @@ -7,5 +7,5 @@ case class Person(id: Long, name: String, phone: Option[String], hobbies: Seq[St object Person { def default = Person(1L, "name", Some("123"), hobbies = Seq("ping pong")) - given ProtoScalable[Person, PBPerson] = ProtoScalable[Person, PBPerson] -} \ No newline at end of file + implicit val protoScalable: ProtoScalable[Person, PBPerson] = ProtoScalable[Person, PBPerson] +} diff --git a/pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala b/pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala index 7f4ccdd..b8122d8 100644 --- a/pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala +++ b/pbconverts/src/test/scala/pbconverts/ScalableBuilderSpec.scala @@ -21,7 +21,6 @@ class ScalableBuilderSpec extends AnyFunSuite { assert(person.id == 1) } - def assertTestMessage(testMessage: TestMessage) = { val pbTestMessage = Protoable[TestMessage, PBTestMessage].toProto(testMessage) val testMessage2 = ScalableBuilder[TestMessage, PBTestMessage] @@ -42,4 +41,4 @@ class ScalableBuilderSpec extends AnyFunSuite { ) ) } -} \ No newline at end of file +} diff --git a/pbconverts/src/test/scala/pbconverts/TestMessage.scala b/pbconverts/src/test/scala/pbconverts/TestMessage.scala index e801c6f..1a47775 100644 --- a/pbconverts/src/test/scala/pbconverts/TestMessage.scala +++ b/pbconverts/src/test/scala/pbconverts/TestMessage.scala @@ -29,7 +29,7 @@ case class TestMessage( object TestMessage { - def apply():TestMessage = ??? + def apply(): TestMessage = ??? def default = TestMessage( @@ -82,4 +82,4 @@ object TestMessage { stringIntKV = Map.empty, longIntKV = Map.empty ) -} \ No newline at end of file +} From 34bc9c36117ba8a3dc042519536818d3cae87dc5 Mon Sep 17 00:00:00 2001 From: changvvb Date: Sat, 18 Dec 2021 17:59:15 +0800 Subject: [PATCH 11/17] update --- .../main/scala/pbconverts/MacroCache.scala | 13 - .../scala/pbconverts/ProtoScalableMacro.scala | 422 ------------------ .../test/resources/MessageWithTypeSpec.scala | 29 -- .../test/resources/ProtoableBuilderSpec.scala | 34 -- .../test/resources/ScalableBuilderSpec.scala | 32 -- .../pbconverts}/ProtoableSpec.scala | 0 6 files changed, 530 deletions(-) delete mode 100644 pbconverts-macro/src/main/scala/pbconverts/MacroCache.scala delete mode 100644 pbconverts-macro/src/main/scala/pbconverts/ProtoScalableMacro.scala delete mode 100644 pbconverts/src/test/resources/MessageWithTypeSpec.scala delete mode 100644 pbconverts/src/test/resources/ProtoableBuilderSpec.scala delete mode 100644 pbconverts/src/test/resources/ScalableBuilderSpec.scala rename pbconverts/src/test/{resources => scala/pbconverts}/ProtoableSpec.scala (100%) diff --git a/pbconverts-macro/src/main/scala/pbconverts/MacroCache.scala b/pbconverts-macro/src/main/scala/pbconverts/MacroCache.scala deleted file mode 100644 index 14da99b..0000000 --- a/pbconverts-macro/src/main/scala/pbconverts/MacroCache.scala +++ /dev/null @@ -1,13 +0,0 @@ -package pbconverts - -import scala.collection.mutable - -object MacroCache { - private var builderCount = 0 - private var identityCount = 0 - - def getBuilderId: Int = builderCount.synchronized { builderCount += 1; builderCount } - def getIdentityId: Int = identityCount.synchronized { identityCount += 1; identityCount } - - lazy val builderFunctionTrees: mutable.Map[Int, mutable.Map[String, Any]] = mutable.Map.empty -} diff --git a/pbconverts-macro/src/main/scala/pbconverts/ProtoScalableMacro.scala b/pbconverts-macro/src/main/scala/pbconverts/ProtoScalableMacro.scala deleted file mode 100644 index cfee82e..0000000 --- a/pbconverts-macro/src/main/scala/pbconverts/ProtoScalableMacro.scala +++ /dev/null @@ -1,422 +0,0 @@ -//package pbconverts -// -//import com.google.protobuf.ByteString -// -//import scala.collection.mutable -//import scala.reflect.macros.whitebox -//import scala.quoted -//import _root_.quoted.Expr -// -//// scalastyle:off number.of.methods -//object ProtoScalableMacro { -// -// private[this] def packageName: Tree = q"_root_.pbconverts" -// private[this] def builderIdent = Ident(TermName("builder")) -// private[this] def entityIdent = Ident(TermName("entity")) -// private[this] def protoIdent = Ident(TermName("proto")) -// private[this] def implicitlyProtoable(entityType: Type, protoType: Type) = q"implicitly[$packageName.Protoable[$entityType,$protoType]]" -// -// private[this] def implicitlyScalable(entityType: Type, protoType: Type) = q"implicitly[$packageName.Scalable[$entityType,$protoType]]" -// -// private[this] def isOption(tpe: Type): Boolean = tpe <:< typeOf[Option[_]] -// -// private[this] def isIterable(tpe: Type): Boolean = -// (tpe <:< typeOf[Iterable[_]] -// || tpe <:< typeOf[Array[_]] -// || tpe <:< typeOf[java.lang.Iterable[_]]) && !(tpe <:< typeOf[Map[_, _]] || tpe <:< typeOf[ByteString]) -// -// private[this] def isMap(tpe: Type): Boolean = tpe <:< typeOf[Map[_, _]] || tpe <:< typeOf[java.util.Map[_, _]] -// -// private[this] def getBuilderType(protoType: Type): Type = { -// protoType.companion.member(TermName("newBuilder")).asTerm.alternatives.head.asMethod.returnType -// } -// -// trait Processor { -// -// def caseClassType: Type -// def protoType: Type -// -// def scalaTreeType: Type -// def protoValueType: Type -// -// def resolvedCaseClassFieldType: Type = resolveFieldType(caseClassType, scalaTreeType) -// -// def tree: Option[Tree] -// } -// -// // Convert expr (`scalaTree` in this class) to protobuf value -// class ToProtoProcessor( -// scalaTree: Tree, -// override val scalaTreeType: Type, -// override val caseClassType: Type, -// override val protoType: Type, -// override val protoFieldName: String -// ) extends ProtoFieldAnalyst { -// -// private[this] def toProto(t1: Type, t2: Type): Tree = { -// if (t1 <:< t2) { -// scalaTree -// } else { -// q"${implicitlyProtoable(t1, t2)}.toProto($scalaTree)" -// } -// } -// -// override def protoValueType: Type = protoValueSetterType -// -// def optTree(optFieldType: Type): c.universe.Tree = { -// val tree = if (isIterable(protoValueType)) { -// seqTree(optFieldType) -// } else if (isMap(protoValueType)) { -// mapTree(optFieldType) -// } else { -// defaultTree(optFieldType) -// } -// If(q"$scalaTree.isDefined", tree, EmptyTree) -// } -// -// def seqTree(iterableType: Type): c.universe.Tree = { -// val listType = builderType.member(addAllMethodName).asMethod.paramLists.head.head.typeSignature -// val valueTree = toProto(iterableType, listType) -// q"${builderIdent}.$addAllMethodName($valueTree)" -// } -// -// def mapTree(mapType: Type): c.universe.Tree = { -// val putAllMapType = builderType.member(putAllMethodName).asMethod.paramLists.head.head.typeSignature -// val valueTree = toProto(mapType, putAllMapType) -// q"${builderIdent}.$putAllMethodName($valueTree)" -// } -// -// def defaultTree(fieldType: Type): c.universe.Tree = { -// val valueTree = toProto(fieldType, protoValueType) -// q"${builderIdent}.$setField(${valueTree})" -// } -// -// override def tree: Option[Tree] = { -// if (protoValueType == NoType) { -// None -// } else { -// val _tree = if (isOption(scalaTreeType)) { -// optTree(resolvedCaseClassFieldType) -// } else if (isIterable(protoValueType)) { -// seqTree(resolvedCaseClassFieldType) -// } else if (isMap(protoValueType)) { -// mapTree(resolvedCaseClassFieldType) -// } else { -// defaultTree(resolvedCaseClassFieldType) -// } -// -// if (scalaTreeType <:< typeOf[AnyRef]) { -// val notNullCondition = q"$scalaTree ne null" -// Some(If(notNullCondition, _tree, EmptyTree)) -// } else { -// Some(_tree) -// } -// } -// } -// } -// -// // Convert expr (`protoValueTree` in this class) to case class filed value -// case class ToScalaProcessor(caseClassSelector: MethodSymbol, protoValueTree: Tree, protoValueType: Type, caseClassType: Type, protoType: Type) -// extends AbstractToScalaProcessor -// -// trait AbstractToScalaProcessor extends Processor { -// -// def caseClassSelector: MethodSymbol -// -// def protoValueTree: Tree -// -// override def scalaTreeType: Type = caseClassSelector.returnType -// -// protected def toScala(t1: Type, t2: Type, value: Tree) = { -// if (t2 <:< t1) { -// value -// } else { -// q"${implicitlyScalable(t1, t2)}.toScala($value)" -// } -// } -// -// def optTree(optType: Type): c.universe.Tree = defaultTree(optType) -// -// def defaultTree(fieldType: Type): Tree = { -// q"$caseClassSelector = ${toScala(fieldType, protoValueType, protoValueTree)}" -// } -// -// override def tree: Option[Tree] = -// if (protoValueType == NoType) { -// None -// } else { -// if (isOption(scalaTreeType)) { -// Some(optTree(resolvedCaseClassFieldType)) -// } else { -// Some(defaultTree(resolvedCaseClassFieldType)) -// } -// } -// } -// -// // Contain some methods and vals to analyze Protobuf fields -// trait ProtoFieldAnalyst extends Processor { -// def protoFieldName: String -// -// val builderType = getBuilderType(protoType) -// -//// def addAllMethodName: TermName = TermName(s"addAll$protoFieldName") -//// def putAllMethodName: TermName = TermName(s"putAll$protoFieldName") -//// -//// def addField: TermName = TermName(s"add$protoFieldName") -//// def putField: TermName = TermName(s"put$protoFieldName") -//// def setField: TermName = TermName(s"set$protoFieldName") -//// def getField: TermName = TermName(s"get$protoFieldName") -//// def getMapField: TermName = TermName(s"get${protoFieldName}Map") -//// def getListField: TermName = TermName(s"get${protoFieldName}List") -//// def builderSetter: TermName = if (isIterable(scalaTreeType)) addAllMethodName else setField -// -// val protoValueTree: Tree = { -//// if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 -//// q"$protoIdent.$getListField" -//// } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map -//// q"$protoIdent.$getMapField" -//// } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 -//// q"$protoIdent.$getField" -//// } else { -//// q"" -//// } -// ??? -// } -// -// lazy val protoValueSetterType: TypeRepr = { -//// val pbBuilderType = typeOf[com.google.protobuf.Message.Builder] -//// val setterOpt = if (builderType.member(addField) != NoSymbol) { -//// Some(builderType.member(addAllMethodName)) -//// } else if (builderType.member(putField) != NoSymbol) { -//// Some(builderType.member(putAllMethodName)) -//// } else if (builderType.member(setField) != NoSymbol) { -//// Some(builderType.member(setField)) -//// } else { -//// None -//// } -//// setterOpt.fold(NoType)(_.alternatives.map(_.asMethod.paramLists.head.head.typeSignature).find(t ⇒ !(t <:< pbBuilderType)).get) -// ??? -// } -// -// lazy val protoValueGetterType: TypeRepr = { -//// if (builderType.member(addField) != NoSymbol) { // 有 addXXX 方法,说明 XXX 是一个数组 -//// protoType.member(getListField).typeSignature.resultType -//// } else if (builderType.member(putField) != NoSymbol) { // 有 putXXX 方法,说明 XXX 是一个 map -//// protoType.member(getMapField).typeSignature.resultType -//// } else if (builderType.member(setField) != NoSymbol) { // 有 setXXX 方法 -//// protoType.member(getField).typeSignature.resultType -//// } else { -//// NoType -//// } -// ??? -// } -// -// } -// -// // Convert scala clase class field value to protobuf value -// case class ToProtoFieldProcessor(accessor: MethodSymbol, override val caseClassType: Type, override val protoType: Type) -// extends ToProtoProcessor(q"$entityIdent.$accessor", accessor.returnType, caseClassType, protoType, accessor.name.toString.capitalize) -// -// // Convert protobuf value to case class filed value -// case class ToScalaFieldProcessor(accessor: MethodSymbol, override val caseClassType: Type, override val protoType: Type) -// extends AbstractToScalaProcessor -// with ProtoFieldAnalyst { -// -// override def caseClassSelector: MethodSymbol = accessor -// -// override def protoFieldName: String = accessor.name.toString.capitalize -// -// override def protoValueType: Type = protoValueGetterType -// -// override def optTree(optType: Type): c.universe.Tree = { -// val hasProtoField = TermName(s"has$protoFieldName") -// if (protoType.member(hasProtoField) == NoSymbol) { -// defaultTree(optType) -// } else { -// q"$caseClassSelector = if (${protoIdent}.$hasProtoField) ${toScala(optType, protoValueType, protoValueTree)} else None" -// } -// } -// } -// -// private[this] def resolveFieldType(entityType: Type, originType: Type): Type = -// originType.asSeenFrom(entityType, entityType.typeSymbol.asClass) -// -// private[this] def resolveType[T: WeakTypeTag]: Type = { -// val tpe = weakTypeOf[T] -// tpe.dealias -// } -// -// private[this] def getCaseAccessors(caseClassType: TypeRepr): Seq[Symbole] = { -// caseClassType.members.collect { case m: MethodSymbol if m.isCaseAccessor ⇒ m }.toSeq.reverse -// } -// -// private[this] def defaultProtoableFieldConvertTrees(caseClassType: TypeRepr, protoType: TypeRepr): Map[String, Tree] = { -// getCaseAccessors(caseClassType).flatMap { a ⇒ -// val p = ToProtoFieldProcessor(a, caseClassType, protoType) -// p.tree.map(p.protoFieldName -> _) -// }.toMap -// } -// -// private[this] def protoableBody(caseClassType: TypeRepr, protoType: TypeRepr, protoableFieldConvertTrees: Iterable[Tree]): Tree = { -//// q""" -//// override def toProto(${entityIdent.name.toTermName}: $caseClassType): $protoType = { -//// val ${builderIdent} = ${protoType.typeSymbol.companion}.newBuilder() -//// ..$protoableFieldConvertTrees -//// $builderIdent.build() -//// } -//// """ -// ??? -// } -// -// private def defalutScalableFieldConvertTrees(caseClassType: Type, protoType: Type): Map[String, Tree] = { -// getCaseAccessors(caseClassType).flatMap(accessor ⇒ ToScalaFieldProcessor(accessor, caseClassType, protoType).tree.map(accessor.name.toString -> _)).toMap -// } -// -// private def scalableBody(caseClassType: Type, protoType: Type, scalableFieldConvertTrees: Iterable[Tree]): Tree = { -// q""" -// override def toScala(${protoIdent.name.toTermName} :$protoType): $caseClassType = { -// new ${caseClassType.typeSymbol} ( -// ..${scalableFieldConvertTrees} -// ) -// } -// """ -// } -// -// def scalasImpl[T, M]: Expr[Scalable] = { -// val caseClassType = resolveType[T] -// val protoType = resolveType[M] -// val scalableFieldConvertTrees = defalutScalableFieldConvertTrees(caseClassType, protoType).values -// scalasImpl(caseClassType, protoType, scalableFieldConvertTrees, Nil) -// } -// -// private[this] def scalasImpl(caseClassType: Type, protoType: Type, scalableFieldConvertTrees: Iterable[Tree], perTrees: Iterable[Tree]): Tree = { -// q""" -// ..$perTrees -// new $packageName.Scalable[$caseClassType, $protoType] { ${scalableBody(caseClassType, protoType, scalableFieldConvertTrees)} } -// """ -// } -// -// def protosImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { -// val caseClassType = resolveType[T] -// val protoType = resolveType[M] -// protosImpl(caseClassType, protoType, defaultProtoableFieldConvertTrees(caseClassType, protoType).values, Nil) -// } -// -// private[this] def protosImpl(caseClassType: Type, protoType: Type, protoableFieldConvertTrees: Iterable[Tree], perTrees: Iterable[Tree]): Tree = { -// q""" -// ..$perTrees -// new $packageName.Protoable[$caseClassType,$protoType] { ${protoableBody(caseClassType, protoType, protoableFieldConvertTrees)} } -// """ -// } -// -// def convertsImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { -// val caseClassType = resolveType[T] -// val protoType = resolveType[M] -// q""" -// new $packageName.ProtoScalable[${resolveType[T]}, ${resolveType[M]}] { -// ${scalableBody(caseClassType, protoType, defalutScalableFieldConvertTrees(caseClassType, protoType).values)} -// ${protoableBody(caseClassType, protoType, defaultProtoableFieldConvertTrees(caseClassType, protoType).values)} -// } -// """ -// } -// -// def buildProtoableImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { -// val caseClassType = resolveType[T] -// val protoType = resolveType[M] -// val customTrees = MacroCache.builderFunctionTrees.getOrElse(getBuilderId(), mutable.Map.empty) -// val (fixedCustomTrees, preTrees) = customTrees.map { -// case (key, tree) ⇒ -// tree match { // setField -// case buildFunction: Function ⇒ -// val functionName = TermName("builderFunction$" + MacroCache.getIdentityId) -// val fromType = buildFunction.tpe.typeArgs.last // buildFunction 的返回值 -// val buildExpr = new ToProtoProcessor(q"$functionName($entityIdent)", fromType, caseClassType, protoType, key).tree.get -// (key -> buildExpr) -> q"val $functionName = $buildFunction" -// case value: Tree ⇒ // setFieldValue -// val identity = TermName("identity$" + MacroCache.getIdentityId) -// val buildExpr = new ToProtoProcessor(q"$identity", value.tpe, caseClassType, protoType, key).tree.get -// (key -> buildExpr) -> q"val $identity = $value" -// } -// }.unzip -// val protoableFieldConvertTrees = (defaultProtoableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values -// protosImpl(caseClassType, protoType, protoableFieldConvertTrees, preTrees) -// } -// -// def buildScalableImpl[T: WeakTypeTag, M: WeakTypeTag]: Tree = { -// val caseClassType = resolveType[T] -// val protoType = resolveType[M] -// val builderId = getBuilderId() -// val customTrees = MacroCache.builderFunctionTrees.getOrElse(builderId, mutable.Map.empty) -// val entityType = resolveType[T] -// -// val (fixedCustomTrees, preTrees) = customTrees.map { -// case (key, tree) ⇒ -// val selector = entityType.member(TermName(key)) -// tree match { -// case buildFunction: Function ⇒ // setField -// val functionName = TermName("builderFunction$" + MacroCache.getIdentityId) -// val expr = new ToScalaProcessor(selector.asMethod, q"$functionName($protoIdent)", buildFunction.body.tpe, resolveType[T], resolveType[M]).tree.get -// (key -> expr) -> q"val $functionName = $buildFunction" -// case value: Tree ⇒ // setFieldValue -// val identity = TermName("identity$" + MacroCache.getIdentityId) -// val expr = new ToScalaProcessor(selector.asMethod, q"$identity", value.tpe, resolveType[T], resolveType[M]).tree.get -// (key -> expr) -> q"val $identity = $value" -// } -// }.unzip -// -// val scalableFieldConvertTrees = (defalutScalableFieldConvertTrees(caseClassType, protoType) ++ fixedCustomTrees.toMap).values -// scalasImpl(caseClassType, protoType, scalableFieldConvertTrees, preTrees) -// } -// -// def setScalaFieldImpl[T: WeakTypeTag, M: WeakTypeTag, TF: WeakTypeTag, MF: WeakTypeTag](scalaField: Tree, value: Tree): Tree = { -// val Function(_, Select(_, termName)) = scalaField -// val builderId = getBuilderId() -// MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(termName.toString, value) -// q"new ${c.prefix.actualType}" -// } -// -// def setProtoFieldImpl[T: WeakTypeTag, M: WeakTypeTag, TF: WeakTypeTag, MF: WeakTypeTag](protoFieldSelector: Tree, value: Tree): Tree = { -// val getter = "^get(\\w+)$".r -// val listGetter = "^get(\\w+)List$".r -// val mapGetter = "^get(\\w+)Map$".r -// val setter = protoFieldSelector.find { -// case _: Select ⇒ true -// case _: Tree ⇒ false -// } match { -// case Some(select: Select) ⇒ -// select.name.toString match { -// case mapGetter(n) if select.tpe.resultType <:< typeOf[java.util.Map[_, _]] ⇒ n -// case listGetter(n) if select.tpe.resultType <:< typeOf[java.util.List[_]] ⇒ n -// case getter(n) ⇒ n -// case _ ⇒ c.abort(protoFieldSelector.pos, "Invalid setter") -// } -// case _ ⇒ c.abort(protoFieldSelector.pos, "Invalid setter") -// } -// val builderId = getBuilderId() -// MacroCache.builderFunctionTrees.getOrElseUpdate(builderId, mutable.Map.empty).update(setter, value) -// q"new ${c.prefix.actualType}" -// } -// -// val annoBuilderPrefix = "AnonBuilder$" -// -// def scalableBuilderApply[T: WeakTypeTag, M: WeakTypeTag]: Tree = { -// val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) -// q""" -// class $className extends $packageName.ScalableBuilder[${resolveType[T]}, ${resolveType[M]}] -// new $className -// """ -// } -// -// def protoableBuilderApply[T: WeakTypeTag, M: WeakTypeTag]: Tree = { -// val className = TypeName(annoBuilderPrefix + MacroCache.getBuilderId) -// q""" -// class $className extends $packageName.ProtoableBuilder[${resolveType[T]}, ${resolveType[M]}] -// new $className -// """ -// } -// -// private[this] def getBuilderId() = { -// c.prefix.actualType.toString.replace(annoBuilderPrefix, "").toInt -// } -// -//} diff --git a/pbconverts/src/test/resources/MessageWithTypeSpec.scala b/pbconverts/src/test/resources/MessageWithTypeSpec.scala deleted file mode 100644 index dd97008..0000000 --- a/pbconverts/src/test/resources/MessageWithTypeSpec.scala +++ /dev/null @@ -1,29 +0,0 @@ -package pbconverts - -import org.scalatest.funsuite.AnyFunSuite -import pbconverts.ConversionTest.{IntMessage, StringMessage} - -class MessageWithTypeSpec extends AnyFunSuite { - - test("test message with type parameter") { - locally { - val intMessage = MessageWithType(5) - val proto = Protoable[MessageWithType[Int], IntMessage].toProto(intMessage) - assert(proto.getValue == 5) - - val intMessage2 = Scalable[MessageWithType[Int], IntMessage].toScala(proto) - assert(intMessage == intMessage2) - } - - locally { - val stringMessage = MessageWithType("test") - val proto = Protoable[MessageWithType[String], StringMessage].toProto(stringMessage) - assert(proto.getValue == "test") - - val stringMessage2 = Scalable[MessageWithType[String], StringMessage].toScala(proto) - assert(stringMessage == stringMessage2) - } - - } - -} diff --git a/pbconverts/src/test/resources/ProtoableBuilderSpec.scala b/pbconverts/src/test/resources/ProtoableBuilderSpec.scala deleted file mode 100644 index 7c51f25..0000000 --- a/pbconverts/src/test/resources/ProtoableBuilderSpec.scala +++ /dev/null @@ -1,34 +0,0 @@ -package pbconverts - -import org.scalatest.funsuite.AnyFunSuite -import pbconverts.ConversionTest.PBTestMessage - -class ProtoableBuilderSpec extends AnyFunSuite { - test("test ProtoableBuilder") { - assertTestMessage(TestMessage.default) - assertTestMessage(TestMessage.zero) - } - - def assertTestMessage(testMessage: TestMessage) = { - val pbTestMessage: PBTestMessage = ProtoableBuilder[TestMessage, PBTestMessage] - .setField(_.getIntValue, _.intValue + 1) - .build - .toProto(testMessage) - - assert(pbTestMessage.getIntValue == testMessage.intValue + 1) - val testMessage2 = Scalable[TestMessage, PBTestMessage].toScala(pbTestMessage) - - assert(testMessage2.intArray.sameElements(testMessage.intArray)) - assert(testMessage2.stringArray.sameElements(testMessage.stringArray)) - assert(testMessage2.personArray.sameElements(testMessage.personArray)) - - assert( - testMessage == testMessage2.copy( - intValue = testMessage2.intValue - 1, - intArray = testMessage.intArray, - stringArray = testMessage.stringArray, - personArray = testMessage.personArray - ) - ) - } -} diff --git a/pbconverts/src/test/resources/ScalableBuilderSpec.scala b/pbconverts/src/test/resources/ScalableBuilderSpec.scala deleted file mode 100644 index 88f98b5..0000000 --- a/pbconverts/src/test/resources/ScalableBuilderSpec.scala +++ /dev/null @@ -1,32 +0,0 @@ -package pbconverts - -import org.scalatest.funsuite.AnyFunSuite -import pbconverts.ConversionTest.PBTestMessage - -class ScalableBuilderSpec extends AnyFunSuite { - test("test ScalableBuilder") { - assertTestMessage(TestMessage.default) - assertTestMessage(TestMessage.zero) - } - - def assertTestMessage(testMessage: TestMessage) = { - val pbTestMessage = Protoable[TestMessage, PBTestMessage].toProto(testMessage) - val testMessage2 = ScalableBuilder[TestMessage, PBTestMessage] - .setField(_.intOpt, m => if (m.hasIntOpt) Some(m.getIntOpt.getValue + 1) else None) - .build - .toScala(pbTestMessage) - - assert(testMessage2.intArray.sameElements(testMessage.intArray)) - assert(testMessage2.stringArray.sameElements(testMessage.stringArray)) - assert(testMessage2.personArray.sameElements(testMessage.personArray)) - - assert( - testMessage == testMessage2.copy( - intOpt = testMessage2.intOpt.map(_ - 1), - intArray = testMessage.intArray, - stringArray = testMessage.stringArray, - personArray = testMessage.personArray - ) - ) - } -} diff --git a/pbconverts/src/test/resources/ProtoableSpec.scala b/pbconverts/src/test/scala/pbconverts/ProtoableSpec.scala similarity index 100% rename from pbconverts/src/test/resources/ProtoableSpec.scala rename to pbconverts/src/test/scala/pbconverts/ProtoableSpec.scala From f6cc018aa9160c89360aa81e63d5f24121d1616d Mon Sep 17 00:00:00 2001 From: changvvb Date: Sat, 18 Dec 2021 18:02:17 +0800 Subject: [PATCH 12/17] update --- build.sbt | 2 +- .../src/main/scala-3/pbconverts/ProtoScalableMacro.scala | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/build.sbt b/build.sbt index 23af30a..a6296a5 100644 --- a/build.sbt +++ b/build.sbt @@ -4,7 +4,7 @@ lazy val scala213 = "2.13.6" lazy val scala212 = "2.12.14" lazy val scala3 = "3.1.0" -lazy val supportedScalaVersions = List(scala212, scala213) +lazy val supportedScalaVersions = List(scala212, scala213, scala3) val commonSettings = Seq( scalaVersion := scala3, diff --git a/pbconverts/src/main/scala-3/pbconverts/ProtoScalableMacro.scala b/pbconverts/src/main/scala-3/pbconverts/ProtoScalableMacro.scala index a2f3b55..a4efb15 100644 --- a/pbconverts/src/main/scala-3/pbconverts/ProtoScalableMacro.scala +++ b/pbconverts/src/main/scala-3/pbconverts/ProtoScalableMacro.scala @@ -12,11 +12,11 @@ import scala.quoted.Exprs class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { import quotas.reflect._ - private val scalaClassType = quotas.reflect.TypeRepr.of[T].dealias - private val protoClassType = quotas.reflect.TypeRepr.of[M].dealias + private val scalaClassType = TypeRepr.of[T].dealias + private val protoClassType = TypeRepr.of[M].dealias - private val scalaClassSymbol: quotas.reflect.Symbol = scalaClassType.typeSymbol - private val protoClassSymbol: quotas.reflect.Symbol = protoClassType.typeSymbol + private val scalaClassSymbol = scalaClassType.typeSymbol + private val protoClassSymbol = protoClassType.typeSymbol private val protoCompanionIdent = Ref(protoClassSymbol.companionModule) private val newBuilder = Select.overloaded(protoCompanionIdent, "newBuilder", Nil, Nil) From d3640229436fbc30bb0de41cd3b6b2ab4299211d Mon Sep 17 00:00:00 2001 From: changvvb Date: Sat, 18 Dec 2021 18:23:31 +0800 Subject: [PATCH 13/17] update --- .../pbconverts/ProtoScalableMacro.scala | 126 +++++++++--------- .../main/scala-3/pbconverts/Protoable.scala | 14 +- .../scala-3/pbconverts/ProtoableBuilder.scala | 14 +- .../main/scala-3/pbconverts/Scalable.scala | 16 +-- .../scala-3/pbconverts/ScalableBuilder.scala | 14 +- .../src/test/scala/pbconverts/TestMain.scala | 19 --- 6 files changed, 91 insertions(+), 112 deletions(-) delete mode 100644 pbconverts/src/test/scala/pbconverts/TestMain.scala diff --git a/pbconverts/src/main/scala-3/pbconverts/ProtoScalableMacro.scala b/pbconverts/src/main/scala-3/pbconverts/ProtoScalableMacro.scala index a4efb15..651a472 100644 --- a/pbconverts/src/main/scala-3/pbconverts/ProtoScalableMacro.scala +++ b/pbconverts/src/main/scala-3/pbconverts/ProtoScalableMacro.scala @@ -9,11 +9,11 @@ import scala.quoted.ToExpr.NoneToExpr import scala.quoted.Exprs // scalastyle:off number.of.methods -class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { +class ProtoScalableMacro[S: Type, P <: Message: Type](using quotas: Quotes) { import quotas.reflect._ - private val scalaClassType = TypeRepr.of[T].dealias - private val protoClassType = TypeRepr.of[M].dealias + private val scalaClassType = TypeRepr.of[S].dealias + private val protoClassType = TypeRepr.of[P].dealias private val scalaClassSymbol = scalaClassType.typeSymbol private val protoClassSymbol = protoClassType.typeSymbol @@ -321,15 +321,15 @@ class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { } } - private[this] def protoableBody(scalaEntityIdent: Ident, protoableFieldConvertTrees: (Ident, Ident) => List[Term]): Expr[M] = { - builderBuildeWithTerms(protoableFieldConvertTrees(scalaEntityIdent, _)).asExprOf[M] + private[this] def protoableBody(scalaEntityIdent: Ident, protoableFieldConvertTrees: (Ident, Ident) => List[Term]): Expr[P] = { + builderBuildeWithTerms(protoableFieldConvertTrees(scalaEntityIdent, _)).asExprOf[P] } private def defalutScalableFieldConvertTrees(protoIdent: Ident): Map[String, Term] = { getCaseAccessors().flatMap(accessor ⇒ ToScalaFieldProcessor(protoIdent, accessor).tree.map(accessor.name.toString -> _)).toMap } - private def scalableBody(protoIdent: Ident, scalableFieldConvertTrees: Ident => Iterable[Term]): Expr[T] = { + private def scalableBody(protoIdent: Ident, scalableFieldConvertTrees: Ident => Iterable[Term]): Expr[S] = { val args = scalableFieldConvertTrees(protoIdent).toList val types = scalaClassType match { @@ -338,50 +338,50 @@ class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { } val scalaCompanionIdent = Ref(scalaClassType.typeSymbol.companionModule) - Select.overloaded(scalaCompanionIdent, "apply", types, args).asExprOf[T] + Select.overloaded(scalaCompanionIdent, "apply", types, args).asExprOf[S] } - def scalasImpl: Expr[Scalable[T, M]] = { + def scalasImpl: Expr[Scalable[S, P]] = { scalasImpl { protoIdent => val args = defalutScalableFieldConvertTrees(protoIdent) getCaseAccessors().flatMap(a => args.get(a.name)) } } - private[this] def scalasImpl(scalableFieldConvertTrees: Ident => List[Term]): Expr[Scalable[T, M]] = { + private[this] def scalasImpl(scalableFieldConvertTrees: Ident => List[Term]): Expr[Scalable[S, P]] = { '{ - new Scalable[T, M] { - def toScala(proto: M): T = ${ scalableBody('{ proto }.asTerm.asInstanceOf[Ident], scalableFieldConvertTrees) } + new Scalable[S, P] { + def toScala(proto: P): S = ${ scalableBody('{ proto }.asTerm.asInstanceOf[Ident], scalableFieldConvertTrees) } } } } - private def protosImpl: Expr[Protoable[T, M]] = { + private def protosImpl: Expr[Protoable[S, P]] = { protosImpl((scalaEntityIdent, protoBuilderIdent) => defaultProtoableFieldConvertTrees(scalaEntityIdent, protoBuilderIdent).map(_._2)) } - private[this] def protosImpl(protoableFieldConvertTrees: (Ident, Ident) => List[Term]): Expr[Protoable[T, M]] = { + private[this] def protosImpl(protoableFieldConvertTrees: (Ident, Ident) => List[Term]): Expr[Protoable[S, P]] = { '{ - new Protoable[T, M] { - def toProto(scalaEntity: T): M = ${ protoableBody('{ scalaEntity }.asTerm.asInstanceOf[Ident], protoableFieldConvertTrees) } + new Protoable[S, P] { + def toProto(scalaEntity: S): P = ${ protoableBody('{ scalaEntity }.asTerm.asInstanceOf[Ident], protoableFieldConvertTrees) } } } } - def protoScalableImpl: Expr[ProtoScalable[T, M]] = { + def protoScalableImpl: Expr[ProtoScalable[S, P]] = { '{ - new ProtoScalable[T, M] { - def toScala(proto: M) = ${ scalableBody('{ proto }.asTerm.asInstanceOf[Ident], defalutScalableFieldConvertTrees(_).values) } + new ProtoScalable[S, P] { + def toScala(proto: P) = ${ scalableBody('{ proto }.asTerm.asInstanceOf[Ident], defalutScalableFieldConvertTrees(_).values) } - def toProto(scalaEntity: T): M = ${ + def toProto(scalaEntity: S): P = ${ val scalaEntityIdent = '{ scalaEntity }.asTerm.asInstanceOf[Ident] - builderBuildeWithTerms(defaultProtoableFieldConvertTrees(scalaEntityIdent, _).map(_._2)).asExprOf[M] + builderBuildeWithTerms(defaultProtoableFieldConvertTrees(scalaEntityIdent, _).map(_._2)).asExprOf[P] } } } } - private def buildProtoableImpl: Expr[Protoable[T, M]] = { + private def buildProtoableImpl: Expr[Protoable[S, P]] = { val customTrees = MacroCache.builderFunctionTrees.getOrElse(getBuilderId(), mutable.Map.empty) def getCustomTrees(scalaIdent: Ident, protoBuilderIdent: Ident): Map[String, Term] = customTrees.map { case (key, tree) ⇒ tree match { // setField @@ -403,7 +403,7 @@ class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { }) } - private def buildScalableImpl: Expr[Scalable[T, M]] = { + private def buildScalableImpl: Expr[Scalable[S, P]] = { val builderId = getBuilderId() val customTrees = MacroCache.builderFunctionTrees.getOrElse(builderId, mutable.Map.empty) @@ -432,7 +432,7 @@ class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { } } - private def setScalaFieldImpl[TF, MF](scalaField: Expr[T => TF], value: Expr[(M => MF) | MF]): Expr[ScalableBuilder[T, M]] = { + private def setScalaFieldImpl[TF, MF](scalaField: Expr[S => TF], value: Expr[(P => MF) | MF]): Expr[ScalableBuilder[S, P]] = { scalaField.asTerm match { case Inlined(_, _, Inlined(_, _, Block(List(DefDef(_, _, _, Some(Select(_, symbolName)))), _))) => val builderId = getBuilderId() @@ -442,7 +442,7 @@ class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { } } - private def setProtoFieldImpl[TF: Type, MF: Type](protoFieldSelector: Expr[M ⇒ MF], value: Expr[(T ⇒ TF) | TF]): Expr[ProtoableBuilder[T, M]] = { + private def setProtoFieldImpl[TF: Type, MF: Type](protoFieldSelector: Expr[P ⇒ MF], value: Expr[(S ⇒ TF) | TF]): Expr[ProtoableBuilder[S, P]] = { val getter = "^get(\\w+)$".r val listGetter = "^get(\\w+)List$".r val mapGetter = "^get(\\w+)Map$".r @@ -464,12 +464,12 @@ class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { val annoBuilderPrefix = "AnonBuilder$" - private def scalableBuilderApply: Expr[ScalableBuilder[T, M]] = { - '{ ScalableBuilder._default.asInstanceOf[ScalableBuilder[T, M]] } + private def scalableBuilderApply: Expr[ScalableBuilder[S, P]] = { + '{ ScalableBuilder._default.asInstanceOf[ScalableBuilder[S, P]] } } - private def protoableBuilderApply: Expr[ProtoableBuilder[T, M]] = { - '{ ProtoableBuilder._default.asInstanceOf[ProtoableBuilder[T, M]] } + private def protoableBuilderApply: Expr[ProtoableBuilder[S, P]] = { + '{ ProtoableBuilder._default.asInstanceOf[ProtoableBuilder[S, P]] } } private[this] def getBuilderId(): String = { @@ -480,74 +480,74 @@ class ProtoScalableMacro[T: Type, M <: Message: Type](using quotas: Quotes) { object ProtoScalableMacro { - inline def protoable[T, M <: Message]: Protoable[T, M] = ${ protosImpl[T, M] } + inline def protoable[S, P <: Message]: Protoable[S, P] = ${ protosImpl[S, P] } - def protosImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[Protoable[T, M]] = { - val protoScalableMacro = new ProtoScalableMacro[T, M] + def protosImpl[S: Type, P <: Message: Type](using quotes: Quotes): Expr[Protoable[S, P]] = { + val protoScalableMacro = new ProtoScalableMacro[S, P] protoScalableMacro.protosImpl } - inline def protoableBuilder[T, M <: Message]: ProtoableBuilder[T, M] = ${ protoableBuilderImpl[T, M] } + inline def protoableBuilder[S, P <: Message]: ProtoableBuilder[S, P] = ${ protoableBuilderImpl[S, P] } - def protoableBuilderImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[ProtoableBuilder[T, M]] = { - val protoScalableMacro = new ProtoScalableMacro[T, M] + def protoableBuilderImpl[S: Type, P <: Message: Type](using quotes: Quotes): Expr[ProtoableBuilder[S, P]] = { + val protoScalableMacro = new ProtoScalableMacro[S, P] protoScalableMacro.protoableBuilderApply } - inline def protoableBuilderSetField[T, M <: Message, MF, TF](inline protoFieldSelector: M ⇒ MF, inline value: (T ⇒ TF) | TF): ProtoableBuilder[T, M] = - ${ protoableBuilderSetFieldImpl[T, M, MF, TF]('protoFieldSelector, 'value) } + inline def protoableBuilderSetField[S, P <: Message, SF, PF](inline protoFieldSelector: P ⇒ SF, inline value: (S ⇒ PF) | PF): ProtoableBuilder[S, P] = + ${ protoableBuilderSetFieldImpl[S, P, SF, PF]('protoFieldSelector, 'value) } - def protoableBuilderSetFieldImpl[T: Type, M <: Message: Type, MF: Type, TF: Type](protoFieldSelector: Expr[M ⇒ MF], value: Expr[(T ⇒ TF) | TF])(using + def protoableBuilderSetFieldImpl[S: Type, P <: Message: Type, PF: Type, SF: Type](protoFieldSelector: Expr[P ⇒ PF], value: Expr[(S ⇒ SF) | SF])(using quotes: Quotes - ): Expr[ProtoableBuilder[T, M]] = { - val protoScalableMacro = new ProtoScalableMacro[T, M] - protoScalableMacro.setProtoFieldImpl[TF, MF](protoFieldSelector, value) + ): Expr[ProtoableBuilder[S, P]] = { + val protoScalableMacro = new ProtoScalableMacro[S, P] + protoScalableMacro.setProtoFieldImpl[SF, PF](protoFieldSelector, value) } - inline def scalableBuilder[T, M <: Message]: ScalableBuilder[T, M] = ${ scalableBuilderImpl[T, M] } + inline def scalableBuilder[S, P <: Message]: ScalableBuilder[S, P] = ${ scalableBuilderImpl[S, P] } - def scalableBuilderImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[ScalableBuilder[T, M]] = { - val protoScalableMacro = new ProtoScalableMacro[T, M] + def scalableBuilderImpl[S: Type, P <: Message: Type](using quotes: Quotes): Expr[ScalableBuilder[S, P]] = { + val protoScalableMacro = new ProtoScalableMacro[S, P] protoScalableMacro.scalableBuilderApply } - inline def scalableBuilderSetField[T, M <: Message, TF, MF](inline scalaFieldSelector: T ⇒ TF, inline value: (M ⇒ MF) | MF): ScalableBuilder[T, M] = - ${ scalableBuilderSetFieldImpl[T, M, TF, MF]('scalaFieldSelector, 'value) } + inline def scalableBuilderSetField[S, P <: Message, SF, PF](inline scalaFieldSelector: S ⇒ SF, inline value: (P ⇒ PF) | PF): ScalableBuilder[S, P] = + ${ scalableBuilderSetFieldImpl[S, P, SF, PF]('scalaFieldSelector, 'value) } - def scalableBuilderSetFieldImpl[T: Type, M <: Message: Type, TF: Type, MF: Type](scalaFieldSelector: Expr[T ⇒ TF], value: Expr[(M ⇒ MF) | MF])(using + def scalableBuilderSetFieldImpl[S: Type, P <: Message: Type, SF: Type, PF: Type](scalaFieldSelector: Expr[S ⇒ SF], value: Expr[(P ⇒ PF) | PF])(using quotes: Quotes - ): Expr[ScalableBuilder[T, M]] = { - val protoScalableMacro = new ProtoScalableMacro[T, M] - protoScalableMacro.setScalaFieldImpl[TF, MF](scalaFieldSelector, value) + ): Expr[ScalableBuilder[S, P]] = { + val protoScalableMacro = new ProtoScalableMacro[S, P] + protoScalableMacro.setScalaFieldImpl[SF, PF](scalaFieldSelector, value) } - inline def buildScalable[T, M <: Message]: Scalable[T, M] = - ${ buildScalableImpl[T, M] } + inline def buildScalable[S, P <: Message]: Scalable[S, P] = + ${ buildScalableImpl[S, P] } - def buildScalableImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[Scalable[T, M]] = { - val protoScalableMacro = new ProtoScalableMacro[T, M] + def buildScalableImpl[S: Type, P <: Message: Type](using quotes: Quotes): Expr[Scalable[S, P]] = { + val protoScalableMacro = new ProtoScalableMacro[S, P] protoScalableMacro.buildScalableImpl } - inline def buildProtoable[T, M <: Message]: Protoable[T, M] = - ${ buildProtoableImpl[T, M] } + inline def buildProtoable[S, P <: Message]: Protoable[S, P] = + ${ buildProtoableImpl[S, P] } - def buildProtoableImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[Protoable[T, M]] = { - val protoScalableMacro = new ProtoScalableMacro[T, M] + def buildProtoableImpl[S: Type, P <: Message: Type](using quotes: Quotes): Expr[Protoable[S, P]] = { + val protoScalableMacro = new ProtoScalableMacro[S, P] protoScalableMacro.buildProtoableImpl } - inline def scalable[T, M <: Message]: Scalable[T, M] = ${ scalasImpl[T, M] } + inline def scalable[S, P <: Message]: Scalable[S, P] = ${ scalasImpl[S, P] } - def scalasImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[Scalable[T, M]] = { - val protoScalableMacro = new ProtoScalableMacro[T, M] + def scalasImpl[S: Type, P <: Message: Type](using quotes: Quotes): Expr[Scalable[S, P]] = { + val protoScalableMacro = new ProtoScalableMacro[S, P] protoScalableMacro.scalasImpl } - inline def protoScalable[T, M <: Message]: ProtoScalable[T, M] = ${ protoScalableImpl[T, M] } + inline def protoScalable[S, P <: Message]: ProtoScalable[S, P] = ${ protoScalableImpl[S, P] } - def protoScalableImpl[T: Type, M <: Message: Type](using quotes: Quotes): Expr[ProtoScalable[T, M]] = { - val protoScalableMacro = new ProtoScalableMacro[T, M] + def protoScalableImpl[S: Type, P <: Message: Type](using quotes: Quotes): Expr[ProtoScalable[S, P]] = { + val protoScalableMacro = new ProtoScalableMacro[S, P] protoScalableMacro.protoScalableImpl } } diff --git a/pbconverts/src/main/scala-3/pbconverts/Protoable.scala b/pbconverts/src/main/scala-3/pbconverts/Protoable.scala index 8230106..1161fd1 100644 --- a/pbconverts/src/main/scala-3/pbconverts/Protoable.scala +++ b/pbconverts/src/main/scala-3/pbconverts/Protoable.scala @@ -6,18 +6,18 @@ import com.google.protobuf.{BoolValue, DoubleValue, FloatValue, GeneratedMessage import scala.collection.JavaConverters._ -trait Protoable[-T, +M] { - def toProto(entity: T): M +trait Protoable[-S, +P] { + def toProto(entity: S): P } object Protoable { - inline def apply[T <: Product, M <: GeneratedMessageV3 with MessageOrBuilder]: Protoable[T, M] = - ProtoScalableMacro.protoable[T, M] + inline def apply[S <: Product, P <: GeneratedMessageV3 with MessageOrBuilder]: Protoable[S, P] = + ProtoScalableMacro.protoable[S, P] - def apply[T, M](f: T ⇒ M): Protoable[T, M] = - new Protoable[T, M] { - override def toProto(entity: T): M = f(entity) + def apply[S, P](f: S ⇒ P): Protoable[S, P] = + new Protoable[S, P] { + override def toProto(entity: S): P = f(entity) } given Protoable[Double, java.lang.Double] = Protoable(_.toDouble) diff --git a/pbconverts/src/main/scala-3/pbconverts/ProtoableBuilder.scala b/pbconverts/src/main/scala-3/pbconverts/ProtoableBuilder.scala index cc133ad..8303861 100644 --- a/pbconverts/src/main/scala-3/pbconverts/ProtoableBuilder.scala +++ b/pbconverts/src/main/scala-3/pbconverts/ProtoableBuilder.scala @@ -2,18 +2,18 @@ package pbconverts import com.google.protobuf.Message -class ProtoableBuilder[T, M <: Message]() { +class ProtoableBuilder[S, P <: Message]() { - inline def setField[TF, MF](inline protoFieldSelector: M ⇒ MF, inline value: T ⇒ TF): ProtoableBuilder[T, M] = - ProtoScalableMacro.protoableBuilderSetField[T, M, MF, TF](protoFieldSelector, value) + inline def setField[SF, PF](inline protoFieldSelector: P ⇒ PF, inline value: S ⇒ SF): ProtoableBuilder[S, P] = + ProtoScalableMacro.protoableBuilderSetField[S, P, PF, SF](protoFieldSelector, value) - inline def setFieldValue[TF, MF](inline protoFieldSelector: M ⇒ MF, inline value: TF): ProtoableBuilder[T, M] = - ProtoScalableMacro.protoableBuilderSetField[T, M, MF, TF](protoFieldSelector, value) + inline def setFieldValue[SF, PF](inline protoFieldSelector: P ⇒ PF, inline value: SF): ProtoableBuilder[S, P] = + ProtoScalableMacro.protoableBuilderSetField[S, P, PF, SF](protoFieldSelector, value) - inline def build: Protoable[T, M] = ProtoScalableMacro.buildProtoable[T, M] + inline def build: Protoable[S, P] = ProtoScalableMacro.buildProtoable[S, P] } object ProtoableBuilder { val _default = new ProtoableBuilder[Nothing, Nothing] - inline def apply[T, M <: Message]: ProtoableBuilder[T, M] = ProtoScalableMacro.protoableBuilder[T, M] + inline def apply[S, P <: Message]: ProtoableBuilder[S, P] = ProtoScalableMacro.protoableBuilder[S, P] } diff --git a/pbconverts/src/main/scala-3/pbconverts/Scalable.scala b/pbconverts/src/main/scala-3/pbconverts/Scalable.scala index eb86f71..c5143ad 100644 --- a/pbconverts/src/main/scala-3/pbconverts/Scalable.scala +++ b/pbconverts/src/main/scala-3/pbconverts/Scalable.scala @@ -8,28 +8,26 @@ import scala.concurrent.ExecutionContext import scala.reflect.ClassTag import com.google.protobuf.Message -trait Scalable[+T, -M] { - def toScala(proto: M): T +trait Scalable[+S, -P] { + def toScala(proto: P): S } object Scalable extends ScalableImplicits { - inline def apply[T <: Product, M <: Message]: Scalable[T, M] = ProtoScalableMacro.scalable[T, M] + inline def apply[S <: Product, P <: Message]: Scalable[S, P] = ProtoScalableMacro.scalable[S, P] - def apply[T, M](convert: M ⇒ T): Scalable[T, M] = - new Scalable[T, M] { - override def toScala(proto: M): T = convert(proto) + def apply[S, P](convert: P ⇒ S): Scalable[S, P] = + new Scalable[S, P] { + override def toScala(proto: P): S = convert(proto) } - given Int = 1 - given Scalable[Int, java.lang.Integer] = Scalable(_.toInt) given Scalable[Long, java.lang.Long] = Scalable(_.toLong) given Scalable[Double, java.lang.Double] = Scalable(_.toDouble) given Scalable[Float, java.lang.Float] = Scalable(_.toFloat) given Scalable[Char, java.lang.Character] = Scalable(_.toChar) - given javaByteScalable: Scalable[Byte, java.lang.Byte] = Scalable(_.toByte) + given Scalable[Byte, java.lang.Byte] = Scalable(_.toByte) given Scalable[String, StringValue] = Scalable(_.getValue) given Scalable[Int, Int32Value] = Scalable(_.getValue) diff --git a/pbconverts/src/main/scala-3/pbconverts/ScalableBuilder.scala b/pbconverts/src/main/scala-3/pbconverts/ScalableBuilder.scala index be6731b..3ccd523 100644 --- a/pbconverts/src/main/scala-3/pbconverts/ScalableBuilder.scala +++ b/pbconverts/src/main/scala-3/pbconverts/ScalableBuilder.scala @@ -2,18 +2,18 @@ package pbconverts import com.google.protobuf.Message -class ScalableBuilder[+T, M <: Message]() { +class ScalableBuilder[+S, P <: Message]() { - inline def setField[TF, MF](inline scalaField: T ⇒ TF, inline value: M ⇒ MF): ScalableBuilder[T, M] = - ProtoScalableMacro.scalableBuilderSetField[T, M, TF, MF](scalaField, value) + inline def setField[SF, PF](inline scalaField: S ⇒ SF, inline value: P ⇒ PF): ScalableBuilder[S, P] = + ProtoScalableMacro.scalableBuilderSetField[S, P, SF, PF](scalaField, value) - inline def setFieldValue[TF, MF](inline scalaField: T ⇒ TF, inline value: MF): ScalableBuilder[T, M] = - ProtoScalableMacro.scalableBuilderSetField[T, M, TF, MF](scalaField, value) + inline def setFieldValue[SF, PF](inline scalaField: S ⇒ SF, inline value: PF): ScalableBuilder[S, P] = + ProtoScalableMacro.scalableBuilderSetField[S, P, SF, PF](scalaField, value) - inline def build: Scalable[T, M] = ProtoScalableMacro.buildScalable[T, M] + inline def build: Scalable[S, P] = ProtoScalableMacro.buildScalable[S, P] } object ScalableBuilder { val _default = new ScalableBuilder[Nothing, Nothing] - inline def apply[T, M <: Message]: ScalableBuilder[T, M] = ProtoScalableMacro.scalableBuilder[T, M] + inline def apply[S, P <: Message]: ScalableBuilder[S, P] = ProtoScalableMacro.scalableBuilder[S, P] } diff --git a/pbconverts/src/test/scala/pbconverts/TestMain.scala b/pbconverts/src/test/scala/pbconverts/TestMain.scala deleted file mode 100644 index a8edce1..0000000 --- a/pbconverts/src/test/scala/pbconverts/TestMain.scala +++ /dev/null @@ -1,19 +0,0 @@ -package pbconverts - -import ConversionTest.PBTestMessage -import ConversionTest.StringMessage - -object TestMain extends App { - - // val testMessage = TestMessage.default - // val pbTestMessage: PBTestMessage = Protoable[TestMessage, PBTestMessage].toProto(testMessage) - // println(pbTestMessage.getIntValue) - - val stringMessage = MessageWithType("test") - // val x = Protoable[MessageWithType[String], StringMessage].toProto(stringMessage) - val x = StringMessage.newBuilder.setValue("Test").build -// val y = Scalable[MessageWithType[String], StringMessage].toScala(x) - - println(x.getValue) - // println(y) -} From 534723b94928e9dff32a6fa0c80e568192459a00 Mon Sep 17 00:00:00 2001 From: changvvb Date: Sat, 18 Dec 2021 18:28:58 +0800 Subject: [PATCH 14/17] upgrade sbt-scoverage --- project/plugins.sbt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project/plugins.sbt b/project/plugins.sbt index 3a60f9f..7685250 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,6 +1,6 @@ addSbtPlugin("com.github.gseitz" % "sbt-protobuf" % "0.6.5") -addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.6.1") +addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.9.2") addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.0") From cc86ec123458e4d059f8c0bc148f5bc0ec91dcf9 Mon Sep 17 00:00:00 2001 From: changvvb Date: Sat, 18 Dec 2021 18:33:49 +0800 Subject: [PATCH 15/17] Fix testgs --- project/plugins.sbt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project/plugins.sbt b/project/plugins.sbt index 7685250..3b32363 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,6 +1,6 @@ addSbtPlugin("com.github.gseitz" % "sbt-protobuf" % "0.6.5") -addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.9.2") +addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.0.0-M3") addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.0") From 1ed33a08b7ff60f5c288e7f68fafd117ded75271 Mon Sep 17 00:00:00 2001 From: changvvb Date: Mon, 20 Dec 2021 11:44:26 +0800 Subject: [PATCH 16/17] update --- build.sbt | 34 +++++++++++++++++++--------------- project/build.properties | 3 ++- release.sbt | 1 + 3 files changed, 22 insertions(+), 16 deletions(-) diff --git a/build.sbt b/build.sbt index a6296a5..a11337a 100644 --- a/build.sbt +++ b/build.sbt @@ -7,25 +7,29 @@ lazy val scala3 = "3.1.0" lazy val supportedScalaVersions = List(scala212, scala213, scala3) val commonSettings = Seq( - scalaVersion := scala3, - scalacOptions += "-language:experimental.macros", - organization := "com.github.changvvb", - crossScalaVersions := supportedScalaVersions, - releasePublishArtifactsAction := PgpKeys.publishSigned.value + scalaVersion := scala3, + scalacOptions += "-language:experimental.macros", + organization := "com.github.changvvb", + crossScalaVersions := supportedScalaVersions, + releasePublishArtifactsAction := PgpKeys.publishSigned.value ) -lazy val `scala-protobuf-java` = project.in(file("pbconverts")) + +lazy val `scala-protobuf-java` = project + .in(file("pbconverts")) .settings(libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.9" % "test") .settings(libraryDependencies ++= { CrossVersion.partialVersion(scalaVersion.value) match { case Some((2, _)) => Seq("org.scala-lang" % "scala-reflect" % scalaVersion.value) - case _ => Nil + case _ => Nil } }) .settings(commonSettings) .enablePlugins(ProtobufTestPlugin) -lazy val root = project.in(file(".")).withId("root") +lazy val root = project + .in(file(".")) + .withId("root") .aggregate(`scala-protobuf-java`) .settings(publishArtifact := false) @@ -34,16 +38,16 @@ ThisBuild / scalafmtOnCompile := true ThisBuild / releasePublishArtifactsAction := releaseStepCommandAndRemaining("+publishSigned") ThisBuild / publishTo := { - val nexus = "https://oss.sonatype.org/" - if (version.value.trim.endsWith("SNAPSHOT")) - Some("snapshots" at nexus + "content/repositories/snapshots") - else - Some("releases" at nexus + "service/local/staging/deploy/maven2") + val nexus = "https://oss.sonatype.org/" + if (version.value.trim.endsWith("SNAPSHOT")) + Some("snapshots" at nexus + "content/repositories/snapshots") + else + Some("releases" at nexus + "service/local/staging/deploy/maven2") } ThisBuild / publishMavenStyle := true -ThisBuild / credentials += Credentials(Path.userHome / ".ivy2" / ".credentials_sonatype") +ThisBuild / credentials += Credentials(Path.userHome / ".ivy2" / ".credentials_sonatype") Test / publishArtifact := false @@ -52,7 +56,7 @@ ThisBuild / pomIncludeRepository := { _ => false } ThisBuild / homepage := Some(url("https://github.com/changvvb/scala-protobuf-java")) ThisBuild / pomExtra := { - + The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt diff --git a/project/build.properties b/project/build.properties index 7d9ef1e..cb6a80e 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1 +1,2 @@ -sbt.version = 1.5.4 +sbt.version = 1.6.0-M1 + diff --git a/release.sbt b/release.sbt index e69de29..8b13789 100644 --- a/release.sbt +++ b/release.sbt @@ -0,0 +1 @@ + From 7595d4b553b1d4c812e6d7567547b8cd9f64d468 Mon Sep 17 00:00:00 2001 From: changvvb Date: Mon, 20 Dec 2021 11:47:22 +0800 Subject: [PATCH 17/17] test --- .github/workflows/scala.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/scala.yml b/.github/workflows/scala.yml index 0a661b1..8a3d5a3 100644 --- a/.github/workflows/scala.yml +++ b/.github/workflows/scala.yml @@ -15,6 +15,8 @@ jobs: - uses: actions/checkout@v2 - name: Setup protoc uses: arduino/setup-protoc@v1 + with: + version: '3.17.3' - name: Set up JDK 1.8 uses: actions/setup-java@v1 with: