use std::fmt;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use uuid::Uuid;
pub mod generator;
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Id(u128);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseIdError(pub String);
impl fmt::Display for ParseIdError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid id string: {}", self.0)
}
}
impl std::error::Error for ParseIdError {}
impl Id {
#[inline]
pub const fn from_u128(value: u128) -> Self {
Id(value)
}
#[inline]
pub const fn as_u128(&self) -> u128 {
self.0
}
#[inline]
pub const fn nil() -> Self {
Id(0)
}
#[inline]
pub const fn is_nil(&self) -> bool {
self.0 == 0
}
#[inline]
pub fn to_uuid_v8(&self) -> Uuid {
Uuid::from_u128(self.0)
}
#[inline]
pub fn from_uuid_v8(uuid: Uuid) -> Self {
Id(uuid.as_u128())
}
#[inline]
pub fn to_uuid(&self) -> Uuid {
self.to_uuid_v8()
}
#[inline]
pub fn from_uuid(uuid: Uuid) -> Self {
Id::from_uuid_v8(uuid)
}
#[inline]
pub const fn to_i64(&self) -> i64 {
self.0 as i64
}
#[inline]
pub const fn from_i64(value: i64) -> Self {
Id(value as u128)
}
#[inline]
pub const fn for_test(seed: u64) -> Self {
Id(seed as u128)
}
pub fn test_new() -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::OnceLock;
static COUNTER: OnceLock<AtomicU64> = OnceLock::new();
let counter = COUNTER.get_or_init(|| AtomicU64::new(rand::random::<u64>() | 1));
Id(counter.fetch_add(1, Ordering::Relaxed) as u128)
}
#[inline]
pub fn as_nebulaid(&self) -> nebulaid::core::Id {
nebulaid::core::Id::from_u128(self.0)
}
#[inline]
pub fn generate() -> Id {
generator::generate()
}
}
impl From<nebulaid::core::Id> for Id {
#[inline]
fn from(id: nebulaid::core::Id) -> Self {
Id(id.as_u128())
}
}
impl From<Id> for nebulaid::core::Id {
#[inline]
fn from(id: Id) -> Self {
nebulaid::core::Id::from_u128(id.0)
}
}
impl From<Uuid> for Id {
#[inline]
fn from(uuid: Uuid) -> Self {
Id(uuid.as_u128())
}
}
impl From<Id> for Uuid {
#[inline]
fn from(id: Id) -> Self {
Uuid::from_u128(id.0)
}
}
impl PartialEq<Uuid> for Id {
#[inline]
fn eq(&self, other: &Uuid) -> bool {
self.0 == other.as_u128()
}
}
impl Default for Id {
#[inline]
fn default() -> Self {
Id::nil()
}
}
impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.is_nil() {
return f.write_str("00000000-0000-0000-0000-000000000000");
}
write!(f, "{}", self.as_nebulaid())
}
}
impl fmt::Debug for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
mod from_str;
impl Serialize for Id {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Id {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
s.parse().map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_nil_default_and_is_nil() {
assert!(Id::nil().is_nil());
assert!(Id::default().is_nil());
assert_eq!(Id::nil(), Id::default());
assert_eq!(Id::nil().as_u128(), 0);
}
#[test]
fn test_u128_roundtrip() {
let id = Id::from_u128(12345678901234567890u128);
assert_eq!(id.as_u128(), 12345678901234567890u128);
}
#[test]
fn test_uuid_roundtrip_preserves_bytes() {
let uuid = Uuid::new_v4();
let id = Id::from_uuid_v8(uuid);
assert_eq!(id.to_uuid_v8(), uuid);
}
#[test]
fn test_uuidv8_shape_displays_as_hyphenated_uuid() {
let mut bytes = [0u8; 16];
bytes[6] = 0x80; bytes[8] = 0x80; let uuid = Uuid::from_bytes(bytes);
let id = Id::from_uuid_v8(uuid);
let rendered = id.to_string();
assert_eq!(rendered.len(), 36, "v8 形态应渲染为 36 位 UUID 字符串");
assert_eq!(rendered.matches('-').count(), 4);
assert_eq!(rendered, uuid.to_string());
}
#[test]
fn test_numeric_id_displays_as_decimal() {
let id = Id::from_u128(12345);
assert_eq!(id.to_string(), "12345");
}
#[test]
fn test_from_str_uuid_and_numeric() {
let uuid = Uuid::new_v4();
let parsed: Id = uuid.to_string().parse().unwrap();
assert_eq!(parsed.to_uuid_v8(), uuid);
let num: Id = "9876543210".parse().unwrap();
assert_eq!(num.as_u128(), 9876543210u128);
}
#[test]
fn test_from_str_invalid() {
assert!("not-an-id".parse::<Id>().is_err());
assert!("".parse::<Id>().is_err());
}
#[test]
fn test_serde_uuid_string_roundtrip() {
let mut bytes = [0u8; 16];
bytes[6] = 0x80;
bytes[8] = 0x80;
let id = Id::from_uuid(Uuid::from_bytes(bytes));
let json = serde_json::to_string(&id).unwrap();
assert!(json.starts_with('"') && json.ends_with('"'));
assert_eq!(json.matches('-').count(), 4);
let back: Id = serde_json::from_str(&json).unwrap();
assert_eq!(back, id);
}
#[test]
fn test_nebulaid_conversions_roundtrip() {
let neb = nebulaid::core::Id::from_u128(42);
let id: Id = neb.into();
assert_eq!(id.as_u128(), 42);
let back: nebulaid::core::Id = id.into();
assert_eq!(back.as_u128(), 42);
assert_eq!(id.as_nebulaid().as_u128(), 42);
}
#[test]
fn test_is_hashable_and_copyable() {
use std::collections::HashMap;
let a = Id::for_test(1);
let b = a; let mut map = HashMap::new();
map.insert(a, "x");
assert_eq!(map[&b], "x"); }
#[test]
fn test_ordering() {
assert!(Id::for_test(1) < Id::for_test(2));
}
#[test]
fn test_uuid_aliases_equivalence() {
let uuid = Uuid::new_v4();
let id = Id::from_uuid(uuid);
assert_eq!(id.to_uuid(), id.to_uuid_v8());
assert_eq!(id.to_uuid(), uuid);
assert_eq!(Id::from_uuid(id.to_uuid()), id);
}
#[test]
fn test_i64_and_for_test_conversions() {
let id = Id::from_i64(42);
assert_eq!(id.to_i64(), 42);
assert_eq!(id.as_u128(), 42u128);
let a = Id::for_test(7);
let b = Id::for_test(7);
assert_eq!(a, b);
assert!(!a.is_nil());
}
#[test]
fn test_new_is_unique_and_nonzero() {
let a = Id::test_new();
let b = Id::test_new();
assert!(!a.is_nil() && !b.is_nil(), "test_new 必须非 nil");
assert_ne!(a, b, "同进程连续两次 test_new 必须唯一");
}
#[test]
fn test_nebulaid_and_uuid_cross_conversions() {
let id = Id::from_u128(0x0000_0000_0000_0000_0000_0000_0000_002a_u128); assert_eq!(id.as_nebulaid().as_u128(), 42u128);
let neb: nebulaid::core::Id = id.into();
assert_eq!(neb.as_u128(), 42u128);
let as_uuid: Uuid = id.into();
assert_eq!(as_uuid, id.to_uuid_v8());
assert!(id == as_uuid);
assert!(id != Uuid::nil());
}
}