Friday, July 28, 2017

A Binary Coder for Swift

Mike Ash:

This coder serializes fields by writing them out sequentially as raw bytes, with no metadata.

[…]

Now we can see why I implemented BinaryEncoder’s encode method with a big switch statement instead of using separate implementations for all of the various supported types. Overloaded methods are resolved at compile time based on the static type that’s available at the call site. The above call to encoder.encode(value) will always call func encode(_ encodable: Encodable) even if the actual value passed in is, say, a Double or a Bool. In order to allow for this simple wrapper, the implementation in BinaryEncoder has to work with a single entry point, which means it needs to be a big switch statement.

[…]

Swift’s new Codable protocols are a welcome addition to the language to eliminate a lot of boilerplate code. It’s flexible enough to make it straightforward to use/abuse it for things well beyond JSON and property list parsing. Unsophisticated binary formats such as this are not often called for, but they have their uses, and it’s interesting to see how Codable can be used for something so different from the built-in facilities. The Encoder and Decoder protocols are large, but judicious use of generics can cut down a lot of the repetitive code, and implementation is relatively simple in the end.

See also: HashingSingleValueEncodingContainer, MinimalDecoder (via Stephen Celis).

Previously: Swift.Codable.

Update (2017-07-31): See also: Hacker News.

Comments RSS · Twitter

Leave a Comment