ULID (Universally Unique Lexicographically Sortable Identifier) implementation for MoonBit
# Verify installation
moon versionmoon add paveg/ulid# Build the project
moon build
# Run tests
moon test
# Format code
moon fmt
# Check for errors without building
moon check// Create a generator with time source and random generator
let rand = @random.Rand::chacha8()
fn get_time() -> Int64 {
// Return current Unix timestamp in milliseconds
// This is runtime-dependent (see Design Notes below)
1234567890123L
}
let gen = @lib.Generator::new(get_time, rand)
let ulid = gen.generate()
println(ulid.to_string()) // e.g., "01ARYZ6S41DEADBEEFDEADBEEF"// Monotonic generator ensures strict ordering within same millisecond
let mono_gen = @lib.MonotonicGenerator::new(get_time, rand)
let ulid1 = mono_gen.generate()
let ulid2 = mono_gen.generate()
// ulid1 < ulid2 guaranteed (lexicographically)// Parse from string
match @lib.ULID::from_string("01ARYZ6S410000000000000000") {
Ok(ulid) => println(ulid.timestamp())
Err(e) => println(e)
}
// Validate without parsing
if @lib.is_valid("01ARYZ6S410000000000000000") {
println("Valid ULID")
}// Convert to 16-byte binary (big-endian)
let bytes = ulid.to_bytes()
// Create from binary
match @lib.ULID::from_bytes(bytes) {
Ok(ulid) => println(ulid.to_string())
Err(e) => println(e)
}let ulid1 = @lib.ULID::from_string("00000000000000000000000000").unwrap()
let ulid2 = @lib.ULID::from_string("01ARYZ6S410000000000000000").unwrap()
// Compare
if ulid1.compare(ulid2) < 0 {
println("ulid1 < ulid2")
}
// Equality
if ulid1 == ulid2 {
println("Equal")
}| Type | Description |
|---|---|
| ULID | ULID structure (48-bit timestamp + 80-bit randomness) |
| Generator | ULID generator with injectable time source |
| MonotonicGenerator | Monotonic ULID generator |
| Function | Description |
|---|---|
| ULID::from_parts(timestamp, randomness) | Create ULID from components |
| ULID::from_string(s) | Parse ULID from 26-character string |
| ULID::from_bytes(bytes) | Create ULID from 16-byte binary |
| ulid.to_string() | Convert to 26-character string |
| ulid.to_bytes() | Convert to 16-byte binary |
| ulid.timestamp() | Get timestamp (milliseconds) |
| ulid.randomness() | Get randomness bytes |
| ulid.compare(other) | Compare two ULIDs |
| is_valid(s) | Validate ULID string |
| Generator::new(get_time, rand) | Create generator |
| gen.generate() | Generate new ULID |
| MonotonicGenerator::new(get_time, rand) | Create monotonic generator |
fn get_time() -> Int64 {
// Implement based on your runtime environment:
// - Browser: Use JavaScript interop to call Date.now()
// - Node.js: Use JavaScript interop
// - Native: Use FFI to call system time functions
// - Testing: Return mock timestamps
}Install
Download zipULID (Universally Unique Lexicographically Sortable Identifier) implementation for MoonBit