├── .gitignore ├── LICENSE ├── README.md └── src └── PushId.swift /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata/ 19 | 20 | ## Other 21 | *.moved-aside 22 | *.xcuserstate 23 | 24 | ## Obj-C/Swift specific 25 | *.hmap 26 | *.ipa 27 | *.dSYM.zip 28 | *.dSYM 29 | 30 | ## Playgrounds 31 | timeline.xctimeline 32 | playground.xcworkspace 33 | 34 | # Swift Package Manager 35 | # 36 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 37 | # Packages/ 38 | .build/ 39 | 40 | # CocoaPods 41 | # 42 | # We recommend against adding the Pods directory to your .gitignore. However 43 | # you should judge for yourself, the pros and cons are mentioned at: 44 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 45 | # 46 | # Pods/ 47 | 48 | # Carthage 49 | # 50 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 51 | # Carthage/Checkouts 52 | 53 | Carthage/Build 54 | 55 | # fastlane 56 | # 57 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 58 | # screenshots whenever they are needed. 59 | # For more information about the recommended setup visit: 60 | # https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md 61 | 62 | fastlane/report.xml 63 | fastlane/Preview.html 64 | fastlane/screenshots 65 | fastlane/test_output 66 | 67 | .DS_Store 68 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Alex Usbergo 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PushID 2 | [![Swift](https://img.shields.io/badge/swift-5.1-orange.svg?style=flat)](#) 3 | [![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)](https://opensource.org/licenses/MIT) 4 | 5 | 6 | Robust and thread-safe generator for UUIDs with guaranteed chronological ordering based on [Firebase's PushID](https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html). 7 | 8 | ID generator that creates 20-character string identifiers with the following properties: 9 | 1. They're based on timestamp so that they sort *after* any existing ids. 10 | 2. They contain 72-bits of random data after the timestamp so that IDs won't collide with other clients' IDs. 11 | 3. They sort *lexicographically* (so the timestamp is converted to characters that will sort properly). 12 | 4. They're monotonically increasing. Even if you generate more than one in the same timestamp, the latter ones will sort after the former ones. We do this by using the previous random bits but "incrementing" them by 1 (only in the case of a timestamp collision). 13 | 14 | 15 | ### Usage 16 | 17 | ``` swift 18 | let id = makePushID() //-Kk6Xfa37VrgLYFtTygJ 19 | ``` 20 | 21 | ### Credit 22 | 23 | Original javascript implementation [here](https://gist.github.com/mikelehen/3596a30bd69384624c11). 24 | 25 | ### Other languages 26 | 27 | [C](https://gist.github.com/whatvn/15f5266d59320113d978) | 28 | [Java](https://gist.github.com/swftvsn/438b4ed68619ad1f5d1c251dc3a5af6f) | 29 | [Go](https://github.com/kjk/betterguid) | 30 | [C#](https://gist.github.com/kiliman/ca1d9f4135078a6b24c5005113bbeea4) | 31 | [Obj-C](https://gist.github.com/kcmoffat/af856ab4b605a00216d3b5f627e50a84) | 32 | [Typescript](https://gist.github.com/episage/0fa8fcf71a28985197c9ba1d51f84408) | 33 | [Ruby](https://gist.github.com/azell/b96d27e4091f5a966bae) | 34 | [Python](https://gist.github.com/risent/4cab3878d995bec7d1c2) | 35 | [Elm](https://github.com/ryanucode/firebase-effect-manager) | 36 | [SQL](https://gist.github.com/DimuDesigns/2fd0adf5b56a5ebf7cc27f64bff13fd2) | 37 | [Lua](https://github.com/tst2005/lua-firebase_pushid/blob/master/firebase_pushid.lua) 38 | 39 | 40 | -------------------------------------------------------------------------------- /src/PushId.swift: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2017-present Alex Usbergo (github/alexdrone). 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 5 | * and associated documentation files (the "Software"), to deal in the Software without restriction, 6 | * including without limitation the rights to use, copy, modify, merge, publish, distribute, 7 | * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 8 | * furnished to do so, subject to the following conditions: 9 | * The above copyright notice and this permission notice shall be included in all copies or 10 | * substantial portions of the Software. 11 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 12 | * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 13 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 14 | * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 15 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 16 | */ 17 | 18 | import Foundation 19 | 20 | /** Shorthand to PushID's 'make' function. */ 21 | public func makePushID() -> String { 22 | return PushID.default.make() 23 | } 24 | 25 | /** ID generator that creates 20-character string identifiers with the following properties: 26 | * 1. They're based on timestamp so that they sort *after* any existing ids. 27 | * 2. They contain 72-bits of random data after the timestamp so that IDs won't collide with 28 | * other clients' IDs. 29 | * 3. They sort *lexicographically* (so the timestamp is converted to characters that will 30 | * sort properly). 31 | * 4. They're monotonically increasing. Even if you generate more than one in the same timestamp, 32 | * the latter ones will sort after the former ones. We do this by using the previous random bits 33 | * but "incrementing" them by 1 (only in the case of a timestamp collision). 34 | */ 35 | public class PushID { 36 | 37 | // MARK: Static constants 38 | 39 | // Modeled after base64 web-safe chars, but ordered by ASCII. 40 | private static let ascChars = Array( 41 | "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".characters) 42 | private static let descChars = Array(ascChars.reversed()) 43 | 44 | public static let `default` = PushID() 45 | 46 | // MARK: State 47 | 48 | // Timestamp of last push, used to prevent local collisions if you push twice in one ms. 49 | private var lastPushTime: UInt64 = 0 50 | 51 | // We generate 72-bits of randomness which get turned into 12 characters and appended to the 52 | // timestamp to prevent collisions with other clients. We store the last characters we 53 | // generated because in the event of a collision, we'll use those same characters except 54 | // "incremented" by one. 55 | private var lastRandChars = Array(repeating: 0, count: 12) 56 | 57 | // For testability purposes. 58 | private let dateProvider: (Void) -> Date 59 | 60 | // Ensure the generator synchronization. 61 | private let lock = NSLock() 62 | 63 | public init(dateProvider: @escaping (Void) -> Date = { Date() }) { 64 | self.dateProvider = dateProvider 65 | } 66 | 67 | /** Generate a new push UUID. */ 68 | public func make(ascending: Bool = true) -> String { 69 | let pushChars = ascending ? PushID.ascChars : PushID.descChars 70 | precondition(pushChars.count > 0) 71 | var timeStampChars = Array(repeating: pushChars.first!, count: 8) 72 | 73 | self.lock.lock() 74 | 75 | var now = UInt64(self.dateProvider().timeIntervalSince1970 * 1000) 76 | let duplicateTime = (now == self.lastPushTime) 77 | 78 | self.lastPushTime = now 79 | 80 | for i in stride(from: 7, to: 0, by: -1) { 81 | timeStampChars[i] = pushChars[Int(now % 64)] 82 | now >>= 6 83 | } 84 | 85 | assert(now == 0, "The whole timestamp should be now converted.") 86 | var id = String(timeStampChars) 87 | 88 | if !duplicateTime { 89 | for i in 0..<12 { 90 | self.lastRandChars[i] = Int(64 * Double(arc4random()) / Double(UInt32.max)) 91 | } 92 | } else { 93 | // If the timestamp hasn't changed since last push, use the same random number, 94 | // except incremented by 1. 95 | var index: Int = 0 96 | for i in stride(from: 11, to: 0, by: -1) { 97 | index = i 98 | guard self.lastRandChars[i] == 63 else { break } 99 | self.lastRandChars[i] = 0 100 | } 101 | self.lastRandChars[index] += 1 102 | } 103 | 104 | // Appends the random characters. 105 | for i in 0..<12 { 106 | id.append(pushChars[self.lastRandChars[i]]) 107 | } 108 | assert(id.lengthOfBytes(using: .utf8) == 20, "The id lenght should be 20.") 109 | 110 | self.lock.unlock() 111 | return id 112 | } 113 | } 114 | --------------------------------------------------------------------------------