Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Unsafe Swift

Ray Fix
March 02, 2017

Unsafe Swift

Case study of using unsafe to implement hashable type. Presented at try! Swift 2017 Tokyo, Japan.

Ray Fix

March 02, 2017
Tweet

More Decks by Ray Fix

Other Decks in Programming

Transcript

  1. 7

  2. struct Angle: Hashable { var radians: Double … var hashValue:

    Int { return radians.hashValue } } ANGLE 10
  3. struct Point: Hashable { var x, y: Double var hashValue:

    Int { return x.hashValue ^ y.hashValue } } ^ COMPOSITION 11
  4. struct Point: Hashable { var x, y: Double var hashValue:

    Int { return "\(x),\(y)".hashValue } } FAKE IT Heap Allocations are Expensive! 12
  5. protocol HashAlgorithm { init() // 1 mutating func consume(bytes:) //

    2 var finalValue: Int // 3 } ROBUST COMPOSITION13
  6. struct FVN1AHash: HashAlgorithm { private var hash: UInt64 = 0xcbf29ce484222325

    private let prime: UInt64 = 0x100000001b3 mutating func consume<S: Sequence>(bytes: S) where S.Iterator.Element == UInt8 { for byte in bytes { hash = (hash ^ UInt64(byte)) &* prime } } var finalValue: Int { return Int(truncatingBitPattern: hash) } } HASH ALGO AUTHORS14
  7. var hashValue: Int { var hash = FVN1AHash() hash.consume(x) hash.consume(y)

    return hash.finalValue } SAFE EASY CLIENT CODE15
  8. UNSAFE CODE SAFELY HIDDEN AWAY extension HashAlgorithm { mutating func

    consume<I: Integer>(_ value: I) { var temp = value withUnsafeBytes(of: &temp) { rawBufferPointer in consume(bytes: rawBufferPointer) } } } 16
  9. Safe, Swifty API for Users Safe Customization Points for Library

    Developers Well Tested Unsafe Code UNSAFE CODE SAFELY HIDDEN AWAY 17
  10. 18