Skip to content

Commit

Permalink
Add files and license
Browse files Browse the repository at this point in the history
  • Loading branch information
kazk committed Dec 13, 2020
1 parent 04eccaf commit f0e5037
Show file tree
Hide file tree
Showing 14 changed files with 642 additions and 0 deletions.
44 changes: 44 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: CI

on:
push:
branches:
- main
pull_request:

jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
components: rustfmt, clippy
- uses: actions/cache@v2
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: cargo check
uses: actions-rs/cargo@v1
with:
command: check
- name: cargo test
uses: actions-rs/cargo@v1
with:
command: test
- name: cargo clippy
uses: actions-rs/cargo@v1
with:
command: clippy
args: -- -D warnings
- name: cargo fmt
uses: actions-rs/cargo@v1
with:
command: fmt
args: --all -- --check
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/target
Cargo.lock
42 changes: 42 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
[package]
name = "xid"
version = "0.1.0"
license = "MIT"
description = "Globally unique sortable id generator. A Rust port of https://github.com/rs/xid."
keywords = ["id"]
homepage = "https://github.com/kazk/xid-rs"
repository = "https://github.com/kazk/xid-rs"
readme = "README.md"
authors = ["kazk <kazk.dev@gmail.com>"]
edition = "2018"
exclude = [".github/"]

[dependencies]
crc32fast = "^1"
hostname = "^0.3"
md5 = "^0.7"
once_cell = "^1"
rand = "^0.7"
thiserror = "^1"

[target.'cfg(target_os = "macos")'.dependencies]
sysctl = "^0.4"

[target.'cfg(target_os = "windows")'.dependencies]
winreg = "^0.8"

[dev-dependencies]
criterion = "0.3"


[[bench]]
name = "xid_new"
harness = false

[[bench]]
name = "xid_new_to_string"
harness = false

[[bench]]
name = "xid_id_from_str"
harness = false
22 changes: 22 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2015 Olivier Poitrey <https://github.com/rs/xid>
Copyright (c) 2020 kazk

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# xid

Globally unique sortable id generator. A Rust port of https://github.com/rs/xid.

The binary representation is compatible with the Mongo DB 12-byte [ObjectId][object-id].
The value consists of:

- a 4-byte timestamp value in seconds since the Unix epoch
- a 3-byte value based on the machine identifier
- a 2-byte value based on the process id
- a 3-byte incrementing counter, initialized to a random value

The string representation is 20 bytes, using a base32 hex variant with characters `[0-9a-v]`
to retain the sortable property of the id.

See the original [`xid`] project for more details.

## Usage

```rust
use xid;

fn main() {
println!("{}", xid::new().to_string()); //=> bva9lbqn1bt68k8mj62g
}
```

## Examples

- [`cargo run --example gen`](./examples/gen.rs): Generate xid

[`xid`]: https://github.com/rs/xid
[object-id]: https://docs.mongodb.org/manual/reference/object-id/
14 changes: 14 additions & 0 deletions benches/xid_id_from_str.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use std::str::FromStr;

use criterion::{criterion_group, criterion_main, Criterion};

use xid::Id;

fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("xid::Id::from_str()", |b| {
b.iter(|| Id::from_str("9m4e2mr0ui3e8a215n4g"))
});
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
10 changes: 10 additions & 0 deletions benches/xid_new.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use criterion::{criterion_group, criterion_main, Criterion};

use xid;

fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("xid::new()", |b| b.iter(|| xid::new()));
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
12 changes: 12 additions & 0 deletions benches/xid_new_to_string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use criterion::{criterion_group, criterion_main, Criterion};

use xid;

fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("xid::new().to_string()", |b| {
b.iter(|| xid::new().to_string())
});
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
5 changes: 5 additions & 0 deletions examples/gen.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
use xid;

fn main() {
println!("{}", xid::new().to_string());
}
63 changes: 63 additions & 0 deletions src/generator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use once_cell::sync::OnceCell;
use rand::RngCore;

use crate::id::{Id, RAW_LEN};
use crate::machine_id;
use crate::pid;

#[derive(Debug)]
pub struct Generator {
counter: AtomicU32,
machine_id: [u8; 3],
pid: [u8; 2],
}

pub fn get() -> &'static Generator {
static INSTANCE: OnceCell<Generator> = OnceCell::new();

INSTANCE.get_or_init(|| Generator {
counter: AtomicU32::new(init_random()),
machine_id: machine_id::get(),
pid: pid::get().to_be_bytes(),
})
}

impl Generator {
pub fn new_id(&self) -> Id {
self.with_time(&SystemTime::now())
}

fn with_time(&self, time: &SystemTime) -> Id {
// Panic if the time is before the epoch.
let unix_ts = time
.duration_since(UNIX_EPOCH)
.expect("Clock may have gone backwards");
self.generate(unix_ts.as_secs() as u32)
}

fn generate(&self, unix_ts: u32) -> Id {
let counter = self.counter.fetch_add(1, Ordering::SeqCst);

let mut raw = [0u8; RAW_LEN];
// 4 bytes of Timestamp (big endian)
raw[0..=3].copy_from_slice(&unix_ts.to_be_bytes());
// 3 bytes of Machine ID
raw[4..=6].copy_from_slice(&self.machine_id);
// 2 bytes of PID
raw[7..=8].copy_from_slice(&self.pid);
// 3 bytes of increment counter (big endian)
raw[9..].copy_from_slice(&counter.to_be_bytes()[1..]);

Id(raw)
}
}

// https://github.com/rs/xid/blob/efa678f304ab65d6d57eedcb086798381ae22206/id.go#L136
fn init_random() -> u32 {
let mut bs = [0u8; 3];
rand::thread_rng().fill_bytes(&mut bs);
u32::from_be_bytes([0, bs[0], bs[1], bs[2]])
}

0 comments on commit f0e5037

Please sign in to comment.