object ProtoBufSchemaGenerator

Experimental generator of ProtoBuf schema that is compatible with serializable Kotlin classes and data encoded and decoded by ProtoBuf format.

The schema is generated based on provided SerialDescriptor and is compatible with proto2 schema definition. An arbitrary Kotlin class represent much wider object domain than the ProtoBuf specification, thus schema generator has the following list of restrictions:

  • Serial name of the class and all its fields should be a valid Proto identifier

  • Nullable values are allowed only for Kotlin nullable types, but not optional in order to properly distinguish "default" and "absent" values.

  • The name of the type without the package directive uniquely identifies the proto message type and two or more fields with the same serial name are considered to have the same type. Schema generator allows to specify a separate package directive for the pack of classes in order to mitigate this limitation.

  • Nested collections, e.g. List<List<Int>> are represented using the artificial wrapper message in order to distinguish repeated fields boundaries.

  • Default Kotlin values are not representable in proto schema. A special commentary is generated for properties with default values.

  • Empty nullable collections are not supported by the generated schema and will be prohibited in ProtoBuf as well due to their ambiguous nature.

Temporary restrictions:

  • Contextual data is represented as as bytes type

  • Polymorphic data is represented as a artificial KotlinxSerializationPolymorphic message.

Other types are mapped according to their specification: primitives as primitives, lists as 'repeated' fields and maps as 'repeated' map entries.

The name of messages and enums is extracted from SerialDescriptor.serialName in SerialDescriptor without the package directive, as substring after the last dot character, the '?' character is also removed if it is present at the end of the string.


Link copied to clipboard
fun generateSchemaText(    descriptors: List<SerialDescriptor>,     packageName: String? = null,     options: Map<String, String> = emptyMap()): String

Generate text of protocol buffers schema version 2 for the given serializable descriptors. packageName define common protobuf package for all messages and enum in the schema, it may contain 'a'..'z' letters in upper and lower case, decimal digits, '.' or '_' chars, but started only from a letter and not finished by dot.

fun generateSchemaText(    rootDescriptor: SerialDescriptor,     packageName: String? = null,     options: Map<String, String> = emptyMap()): String

Generate text of protocol buffers schema version 2 for the given rootDescriptor. The resulting schema will contain all types referred by rootDescriptor.