Swift Xid - Xid uses MongoDB Object ID algorighm1 to generate globally unique ids with base32 serialzation to produce shorter strings

Related tags

Utility swiftpm xid
Overview

Swift Xid

license

A globally unique id generator.

This is a swift implementation of the Golang package found at: https://github.com/rs/xid

Xid uses MongoDB Object ID algorighm1 to generate globally unique ids with base32 serialzation to produce shorter strings.

Binary representation

+---+----+----+----+----+----+----+----+----+----+-----+-----+
| 0 |  1 |  2 |  3 |  4 |  5 |  6 |  7 |  8 |  9 |  10 |  11 |
+---+----+----+----+----+----+----+----+----+----+-----+-----+
 \----- time -----/ \ machine id / \- pid -/ \--- counter ---/
  • 4-byte value representing the seconds since the Unix epoch,
  • 3-byte machine identifier,
  • 2-byte process id, and
  • 3-byte counter, starting with a random value.

The binary representation of the id is compatible with MongoDB's 12 bytes Object IDs. The string representation is using base32hex (w/o padding)2 for better space efficiency when stored in string form (20 bytes). The hex variant of base32 is used to retain the sortable property of the id.

Features

  • Size: 12 bytes (96 bits), smaller than UUID, larger than Twitter Snowflake3
  • Base32hex encoded by default (20 chars when transported as printable string, still sortable)
  • Configuration free: there is no need to set a unique machine and/or data center id
  • K-ordered
  • Embedded time with 1 second precision
  • Unicity guaranteed for 16,777,216 (24 bits) unique ids per second and per host/process
  • Lock-free (unlike UUIDv1 and v2)

Comparison

Name Binary Size String Size Features
UUID 16 bytes 36 chars configuration free, not sortable
shortuuid 16 bytes 22 chars configuration free, not sortable
Snowflake 8 bytes up to 20 chars needs machine/DC configuration, needs central server, sortable
MongoID 12 bytes 24 chars configuration free, sortable
xid 12 bytes 20 chars configuration free, sortable

Usage

let id: String = NewXid() // or let id: Id = NewXid()
print(id)
// Output: caia5ng890f0tr46f690
var xid = Xid()
print(xid.next())
// Output: caia5ng890f0tr00hgtg
// Get embedded info
let id = xid.next()

id.time()
id.machineId()
id.pid()
id.counter()

// Access raw bytes
print(id.data as NSData)
// Output: {length = 12, bytes = 0x62a4a4a108481e0f9b83781f}

Encoding and Decoding

The Id structure complies with Codable protocol and can be converted into and out of an external representation (e.g. JSON).

Decoding from JSON

struct User: Decodable {
  var id: Id
  var name: String
}

let data = """
{
  "id": "caia5ng890f0tr00hgtg",
  "name": "Jane Smith"
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: data)

print(user.id)
// Output: caia5ng890f0tr00hgtg

Encoding into JSON

struct User: Encodable {
  var id: Id
  var name: String
}

let user = User(id: NewXid(), name: "Jane Smith")

let encoder = JSONEncoder()
let data = try encoder.encode(user)

print(String(data: data, encoding: .utf8)!)
// Output: {"id":"caia5ng890f0tr00hgtg","name":"Jane Smith"}

Footnotes

  1. https://www.mongodb.com/docs/manual/reference/method/ObjectId/

  2. https://datatracker.ietf.org/doc/html/rfc4648#section-7

  3. https://blog.twitter.com/2010/announcing-snowflake

You might also like...
Generate a privacy policy for your iOS app
Generate a privacy policy for your iOS app

PrivacyFlash Pro To easily run PrivacyFlash Pro get the latest packaged release. Learn more about PrivacyFlash Pro in our research paper. PrivacyFlash

A utility to generate PreviewDevice presets from the available devices

SwiftUIGen A utility to generate PreviewDevice presets from the available devices Installation Manual Go to the GitHub page for the latest release Dow

An extension for Xcode to generate builders from structs

Swift Struct Builder Generator Xcode Source Editor Extension An Xcode extension (plugin) to generate struct builders automatically. Install Swift Stru

Minecraft-silicon - Generate Apple Silicon-native versions of Minecraft
Minecraft-silicon - Generate Apple Silicon-native versions of Minecraft

Minecraft Silicon A dead simple utility to generate Apple Silicon-native Minecra

Generate and Preview Passbook Passes
Generate and Preview Passbook Passes

Note: This project is no longer being maintained. Passbook is an iOS 6 feature that manages boarding passes, movie tickets, retail coupons, & loyalty

BCSwiftTor - Opinionated pure Swift controller for Tor, including full support for Swift 5.5 and Swift Concurrency

BCSwiftTor Opinionated pure Swift controller for Tor, including full support for

Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer documentation.

Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer docum

Cross-Platform, Protocol-Oriented Programming base library to complement the Swift Standard Library. (Pure Swift, Supports Linux)

SwiftFoundation Cross-Platform, Protocol-Oriented Programming base library to complement the Swift Standard Library. Goals Provide a cross-platform in

Releases(v0.2.1)
Owner
Uditha Atukorala
Uditha Atukorala
A Swift collection of unique, ordered objects

Introduction OrderedSet is essentially the Swift equivalent of Foundation's NSOrderedSet/NSMutableOrderedSet. It was created so Swift would have a uni

Weebly 248 Sep 14, 2022
Store values using unique, randomly generated identifiers

Storage Store values using unique, randomly generated identifiers. This packages consists of three types: A Storage class, a UniqueIdentifiable protoc

Jordan Baird 1 Feb 23, 2022
This is a app developed in Swift, using Object Oriented Programing, UIKit user interface programmatically, API Request and Kingfisher to load remote images

iOS NOW ⭐ This is a app developed in Swift, using Object Oriented Programing, UIKit user interface programmatically, API Request and Kingfisher to loa

William Tristão de Paula 1 Dec 7, 2021
Framework for easily parsing your JSON data directly to Swift object.

Server sends the all JSON data in black and white format i.e. its all strings & we make hard efforts to typecast them into their respective datatypes

Mukesh 11 Oct 17, 2022
A declarative, thread safe, and reentrant way to define code that should only execute at most once over the lifetime of an object.

SwiftRunOnce SwiftRunOnce allows a developer to mark a block of logic as "one-time" code – code that will execute at most once over the lifetime of an

Thumbtack 8 Aug 17, 2022
Transform strings easily in Swift.

swift-string-transform Transform strings easily in Swift. Table of Contents Installation How to use Contribution Installation Swift Package Manager (R

null 18 Apr 21, 2022
A simple Swift utility for producing pseudolocalized strings.

Build your App UI to adapt and respond to translations, and find localization bugs!

Reece Como 2 Sep 28, 2021
Generate protobuf message definitions from Swift structs

SwiftProtobufGen Generates protobuf definitions from Swift structs Building For some reason Xcode builds don't work at all but swiftpm command line bu

null 3 Nov 1, 2021
An eject button for Interface Builder to generate swift code

Eject Eject is a utility to transition from Interface Builder to programatic view layout. This is done by using code generation to create a .swift fil

Rightpoint 524 Dec 29, 2022
Generate Markdown documentation from source code

SourceDocs SourceDocs is a command line tool that generates markdown documentation files from inline source code comments. Similar to Sphinx or Jazzy,

Eneko Alonso 349 Dec 10, 2022