christophhagen / BinaryCodable

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

Add `Oneof` protobuf compatibility #1

Closed christophhagen closed 2 years ago

christophhagen commented 2 years ago

Currently, the Protocol Buffer feature Oneof is not supported.

The feature allows different data types to share storage on the wire, and is implemented in [swift-protobuf]() as an enum with associated values. The message definition:

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

becomes:

enum OneOf_Alternatives {
     case id(Int64)
     case name(String)
}

It would be possible to support this with ProtobufEncoder and ProtobufDecoder, but this would require labelling the enum in some way.

One way would be to add a protocol:

public protocol ProtobufOneOf { }

which could be added to the enum definition:

enum ExampleOneOf: ProtobufOneOf {
    ...
}

and could then be used to distinguish during encoding:

func encode<T>(_ value: T, forKey key: Key) throws where T : Encodable {
    if value is ProtobufOneOf {
        // Encode oneOf differently
        ...
    }
    ...
}

and decoding:

func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
    if type is ProtobufOneOf.Type {
        // Decode oneOf differently
        ...
    }
    ...
}