christophhagen / BinaryCodable

A binary encoder for Swift Codable types
MIT License
92 stars 7 forks source link

Add Oneof Protobuf Compatibility #2

Closed christophhagen closed 2 years ago

christophhagen commented 2 years ago

Adds support to encode and decode protobuf Oneof types.

A new protocol ProtobufOneOf signals that enums with associated values should be treated as a Oneof on the wire.

public protocol ProtobufOneOf { }

A protobuf definition of a oneof:

syntax = "proto3";
message ExampleOneOf {
   int32 field1 = 1;
   oneof alternatives {
       int64 id = 2;
       string name = 3;
   }
}

The corresponding Swift definition would be:

struct ExampleOneOf: Codable {

    let field1: Int32

    // The oneof field
    let alternatives: Alternatives

    // The OneOf definition
    enum Alternatives: Codable, ProtobufOneOf {
        case id(Int64)
        case name(String)

        // Field values, must not overlap with `ExampleOneOf.CodingKeys`
        enum CodingKeys: Int, CodingKey {
            case id = 2
            case name = 3
        }
    }

    enum CodingKeys: Int, CodingKey {
        case field1 = 1
        // The field id of the Oneof field is not used
        case alternatives = 123456
    }
 }