Skip to content

Instantly share code, notes, and snippets.

@ddddxxx
ddddxxx / KeyPath+fieldName.swift
Last active April 28, 2023 10:24
KeyPath Introspection
// This file is based largely on the Runtime package - https://github.com/wickwirew/Runtime
extension KeyPath {
var fieldName: String? {
guard let offset = MemoryLayout<Root>.offset(of: self) else {
return nil
}
let typePtr = unsafeBitCast(Root.self, to: UnsafeMutableRawPointer.self)
let metadata = typePtr.assumingMemoryBound(to: StructMetadata.self)
@ddddxxx
ddddxxx / Clamp.swift
Created September 28, 2018 07:59
Range+Clamp
extension Comparable {
func clamped(to range: ClosedRange<Self>) -> Self {
return max(min(self, range.upperBound), range.lowerBound)
}
func clamped(to range: PartialRangeFrom<Self>) -> Self {
return max(self, range.lowerBound)
}
public func hash_combine(seed: inout Int, value: Int) {
if MemoryLayout<Int>.size == 64 {
// 64 bit hash_combine
let mul: UInt64 = 0x9ddfea08eb382d69
let s = UInt64(bitPattern: Int64(seed))
let v = UInt64(bitPattern: Int64(value))
var a = (v ^ s) &* mul
a ^= (a >> 47)
var b = (s ^ a) &* mul
b ^= (b >> 47)