a2 / MessagePack.swift

It's like JSON, but fast and small…and Swift! – msgpack.org[Swift]
http://msgpack.org
MIT License
283 stars 60 forks source link

Make `Numeric` convenience properties more strict in their type conversions #62

Closed mgadda closed 6 years ago

mgadda commented 6 years ago

This pull request has arisen from my work on what is now an alternative implementation to pull request https://github.com/a2/MessagePack.swift/pull/61. I realized the need for more precision in the decoding process of integers (signed and unsigned) and floating point numbers. This patch does not modify the packing or unpacking process. It only provides a more robust and specific set of convenience properties for each width of integer, float, or double, requiring the value be exactly representable by the target type if the packed value is not already of the correct type.

I believe this approach might result in less decoding errors. For example, previously, if you have a Double precision float point number, and accidentally invoke MessagePackValue.floatValue you would get back a nicely truncated float. This loss of precision could easily go unnoticed. Instead, MessagePackValue.floatValue will only return non-nil if the underlying Double can truly be represented by a float (in many cases, it cannot). While this might seem somewhat inconvenient initially, it offers a nice forcing function to ensure the correct data type is being decoded earlier in the development process. If one is okay with loss of precision, a simple truncating is no more difficult (but entirely more clear to the reader) than:

var value: MessagePackValue
Float(value.doubleValue)

I think this stricter typing in the convenience property API is more in line with the strict typing promoted by swift itself.