Created
July 10, 2019 06:25
-
-
Save MatrixSenpai/ae32e9d4637107657a1d2b8c3d306eb6 to your computer and use it in GitHub Desktop.
Twitter Snowflake implementation in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
public typealias Snowflake = Int64 | |
extension Snowflake { | |
public static var offset: Date? = nil | |
private static var increment: Int = 0 | |
public static func generate(offset: Date? = nil, workerID: Int = 0, processID: Int = 0, increment: Int = 0) -> Snowflake { | |
var timestamp: Double | |
if let offset = offset { | |
timestamp = Date().timeIntervalSince(offset) | |
} else { timestamp = Date().timeIntervalSince1970 } | |
timestamp = (timestamp * 1000.0).rounded() | |
let tst = Int64(timestamp) << 22 | |
let wor = Int64(workerID) << 17 | |
let pro = Int64(processID) << 12 | |
let inc = Int64(increment) | |
return (tst + wor + pro + inc) | |
} | |
public func fromConfig(workerID: Int = 0, processID: Int = 0) -> Snowflake { | |
defer { Snowflake.increment += 1 } | |
return Snowflake.generate(offset: Snowflake.offset, workerID: workerID, processID: processID, increment: Snowflake.increment) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Snowflake doc says it should be a
UInt64
. It looks likeoffset
is always going to be nil?Other than that it seems sound. Gotta say I don't have much experience with bitshifting outside of some old college course.