Skip to content

Instantly share code, notes, and snippets.

@MatrixSenpai
Created July 10, 2019 06:25
Show Gist options
  • Save MatrixSenpai/ae32e9d4637107657a1d2b8c3d306eb6 to your computer and use it in GitHub Desktop.
Save MatrixSenpai/ae32e9d4637107657a1d2b8c3d306eb6 to your computer and use it in GitHub Desktop.
Twitter Snowflake implementation in Swift
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)
}
}
@MatrixSenpai
Copy link
Author

MatrixSenpai commented Jul 10, 2019

I'm still getting the hang of bitwise operators, so if anyone has any improvements, suggestions, or critiques, I'm open to them!

Taken from/inspired by Discord's Dev Documentation

@Sidetalker
Copy link

Snowflake doc says it should be a UInt64. It looks like offset 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment