simpleflake

Simpleflake for nim

Pure Nim score 15/100 · tests present · no docs generated

Summary

Latest Version 0.2.1
License MIT
CI Status Failing
Downloads 0
Last Indexed 2026-09-01 07:18

Authors

  • An Long

Installation

nimble install simpleflake
choosenim install simpleflake
git clone https://github.com/aisk/simpleflake.nim

OS Compatibility

Platform Linux macOS Windows FreeBSD OpenBSD NetBSD Android iOS WASM Embedded
simpleflake - - - - - - -

Dependencies

Package Version Optional
nim >= 1.2.4 No

Source

Repository https://github.com/aisk/simpleflake.nim
Homepage https://github.com/aisk/simpleflake.nim
Registry Source nimble_official

README

simpleflake.nim

Pure nim implementation of the python's simpleflake ID generator.

For more, see the origin blog post of simpleflake: http://engineering.custommade.com/simpleflake-distributed-id-generation-for-the-lazy.

Usage

import simpleflake
import times

let flake = gen()
let parsed = parse(flake)

# A timestamp and the 23 random bits can be supplied explicitly.
let explicitFlake = gen(fromUnix(1_594_308_519), 1234)

# A custom epoch is supported by generation and parsing.
let epoch = fromUnix(1_577_836_800)
let customFlake = gen(epoch + initDuration(seconds = 10), 42, epoch)
let customParsed = parseTime(customFlake, epoch)

# Use parseTime when an exact millisecond timestamp is needed.
let precise = parseTime(explicitFlake)

# Inspect fields and serialize IDs without losing uint64 precision.
let timestampBits = extractBits(flake, SIMPLEFLAKE_TIMESTAMP_SHIFT,
  SIMPLEFLAKE_TIMESTAMP_LENGTH)
let bits = binary(flake)
let decimal = encodeDecimal(flake)
let hexadecimal = encodeHex(flake)
let base36 = encodeBase36(flake)

doAssert decodeDecimal(decimal) == flake
doAssert decodeHex(hexadecimal) == flake
doAssert decodeBase36(base36) == flake

Relative to the selected epoch, the timestamp must fit in the 41-bit millisecond field. With the default epoch, the final supported timestamp is 2069-09-06T20:47:35.551Z. Invalid timestamps, random bits, bit ranges, and encoded strings raise ValueError.

The format constants are exported as SIMPLEFLAKE_EPOCH, SIMPLEFLAKE_TIMESTAMP_LENGTH, SIMPLEFLAKE_RANDOM_LENGTH, their corresponding shift values, and maximum field values.

Uniqueness

A Simpleflake ID contains a 41-bit millisecond timestamp and 23 random bits. Generation is thread-safe, but uniqueness is probabilistic rather than guaranteed. Applications generating many IDs in the same millisecond should detect collisions or use an ID scheme with a deterministic sequence field.

License

MIT