Home

Awesome

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 ---/

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

Comparison

NameBinary SizeString SizeFeatures
UUID16 bytes36 charsconfiguration free, not sortable
shortuuid16 bytes22 charsconfiguration free, not sortable
Snowflake8 bytesup to 20 charsneeds machine/DC configuration, needs central server, sortable
MongoID12 bytes24 charsconfiguration free, sortable
xid12 bytes20 charsconfiguration 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