Compare commits
10 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
c94d95f5fb | ||
|
07e0d3938a | ||
|
21892e977f | ||
|
cc05fc9a40 | ||
|
7b1834479f | ||
|
ea194a1fd1 | ||
|
5b4dff402c | ||
|
0697e61f35 | ||
|
a89f9aff15 | ||
|
51a7a48962 |
35
Cargo.toml
35
Cargo.toml
@@ -9,22 +9,31 @@ crate-type = ["dylib", "rlib"]
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
aes = "0.8.3"
|
||||
base64 = "0.21.2"
|
||||
blockhash = "0.5.0"
|
||||
aes = "0.8.4"
|
||||
base64 = "0.22.1"
|
||||
blake2b_simd = "1.0.3"
|
||||
blake3 = { version = "1.8.2", features = ["serde", "digest"] }
|
||||
blockhash = "1.0.0"
|
||||
cbc = { version = "0.1.2", features = ["std"] }
|
||||
chrono = "0.4.26"
|
||||
cipher = "0.4.4"
|
||||
des = "0.8.1"
|
||||
hex = "0.4.3"
|
||||
hmac-sha256 = "1.1.7"
|
||||
hmac-sha512 = "1.1.5"
|
||||
image = "0.24.6"
|
||||
md-5 = "0.10.5"
|
||||
once_cell = "1.18.0"
|
||||
hmac-sha256 = "1.1.12"
|
||||
hmac-sha512 = "1.1.7"
|
||||
image = "0.25.8"
|
||||
md-5 = "0.10.6"
|
||||
rand = "0.8.5"
|
||||
rsa = { version = "0.9.2", features = ["sha2"] }
|
||||
sha1 = "0.10.5"
|
||||
sha2 = "0.10.7"
|
||||
thiserror = "1.0.40"
|
||||
uuid = { version = "1.4.0", features = ["v4", "fast-rng"] }
|
||||
sha1 = "0.10.6"
|
||||
sha2 = "0.10.9"
|
||||
thiserror = "2.0.17"
|
||||
time = { version = "0.3.44", features = [
|
||||
"formatting",
|
||||
"local-offset",
|
||||
"macros",
|
||||
"parsing",
|
||||
"rand",
|
||||
"serde",
|
||||
"serde-human-readable",
|
||||
] }
|
||||
uuid = { version = "1.18.1", features = ["v4", "fast-rng"] }
|
||||
|
16
README.md
16
README.md
@@ -21,13 +21,18 @@ Rust 中可以使用的常用辅助功能工具箱。主要配备以下功能:
|
||||
- [x] 2048 位长
|
||||
- [x] KeyPair 生成器
|
||||
- 散列算法。
|
||||
- [x] Sha512 散列算法
|
||||
- [x] Sha1 散列算法
|
||||
- [x] MD5 散列算法
|
||||
- [x] 图像感知散列算法
|
||||
- [x] Sha512 散列算法(便捷封装)
|
||||
- [x] Sha1 散列算法(便捷封装)
|
||||
- [x] MD5 散列算法(便捷封装)
|
||||
- [x] 图像感知散列算法(便捷封装)
|
||||
- [x] BLAKE2b 校验和算法(便捷封装)
|
||||
- [x] BLAKE3 校验和算法(便捷封装)
|
||||
- 唯一序列号生成器
|
||||
- [x] 冰雹 ID 生成器(短主机精简日期版雪花 ID)
|
||||
- [x] UUID 生成器
|
||||
- [x] UUIDv4 生成器
|
||||
- [x] UUIDv7 生成器(自定义时间戳分布式版本)
|
||||
- [x] UUIDv7 比较及排序
|
||||
- [x] 基于 Base36 的 short UUIDv7 转换器
|
||||
- [x] short UUID 生成器
|
||||
- 签名算法
|
||||
- [x] RSA 签名算法
|
||||
@@ -35,6 +40,7 @@ Rust 中可以使用的常用辅助功能工具箱。主要配备以下功能:
|
||||
- [x] 随机验证码生成算法
|
||||
- 序列化算法
|
||||
- [x] Base64 算法
|
||||
- [x] Base36 算法
|
||||
- [x] Hex 直转
|
||||
- 常用工具函数
|
||||
- [x] 日期时间函数
|
||||
|
97
src/hash/blake2b/mod.rs
Normal file
97
src/hash/blake2b/mod.rs
Normal file
@@ -0,0 +1,97 @@
|
||||
use blake2b_simd::{blake2b as blake2b_hasher, Params, State};
|
||||
use std::fs::File;
|
||||
use std::io::{self, Read};
|
||||
use std::path::Path;
|
||||
|
||||
/// 根据给定的位数返回一个Blake2b散列实例。
|
||||
fn hasher_select(bit_size: usize) -> State {
|
||||
match bit_size {
|
||||
224 => Params::new().hash_length(28).to_state(), // 224 bits = 28 bytes
|
||||
384 => Params::new().hash_length(48).to_state(), // 384 bits = 48 bytes
|
||||
512 => Params::new().hash_length(64).to_state(), // 512 bits = 64 bytes
|
||||
256 | _ => Params::new().hash_length(32).to_state(), // 256 bits = 32 bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake2b校验和,返回字节数组。
|
||||
pub fn blake2b(data: &[u8]) -> Vec<u8> {
|
||||
blake2b_hasher(data).as_bytes().to_vec()
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake2b/256校验和,返回字节数组。
|
||||
pub fn blake2b_256(data: &[u8]) -> Vec<u8> {
|
||||
let mut hasher = hasher_select(256);
|
||||
hasher.update(data);
|
||||
hasher.finalize().as_bytes().to_vec()
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake2b/384校验和,返回字节数组。
|
||||
pub fn blake2b_384(data: &[u8]) -> Vec<u8> {
|
||||
let mut hasher = hasher_select(384);
|
||||
hasher.update(data);
|
||||
hasher.finalize().as_bytes().to_vec()
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake2b/224校验和,返回字节数组。
|
||||
pub fn blake2b_224(data: &[u8]) -> Vec<u8> {
|
||||
let mut hasher = hasher_select(224);
|
||||
hasher.update(data);
|
||||
hasher.finalize().as_bytes().to_vec()
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake2b校验和,返回十六进制字符串。
|
||||
pub fn blake2b_hex(data: &[u8]) -> String {
|
||||
hex::encode(blake2b(data))
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake2b/256校验和,返回十六进制字符串。
|
||||
pub fn blake2b_256_hex(data: &[u8]) -> String {
|
||||
hex::encode(blake2b_256(data))
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake2b/384校验和,返回十六进制字符串。
|
||||
pub fn blake2b_384_hex(data: &[u8]) -> String {
|
||||
hex::encode(blake2b_384(data))
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake2b/224校验和,返回十六进制字符串。
|
||||
pub fn blake2b_224_hex(data: &[u8]) -> String {
|
||||
hex::encode(blake2b_224(data))
|
||||
}
|
||||
|
||||
/// 根据给定位数计算一个字节数组的Blake2b校验和,返回字节数组。
|
||||
pub fn sum(data: &[u8], bit_size: Option<usize>) -> Vec<u8> {
|
||||
let size = bit_size.unwrap_or(512);
|
||||
let mut hasher = hasher_select(size);
|
||||
hasher.update(data);
|
||||
hasher.finalize().as_bytes().to_vec()
|
||||
}
|
||||
|
||||
/// 根据给定位数计算一个字节数组的Blake2b校验和,返回十六进制字符串。
|
||||
pub fn sum_hex(data: &[u8], bit_size: Option<usize>) -> String {
|
||||
hex::encode(sum(data, bit_size))
|
||||
}
|
||||
|
||||
/// 根据给定位数计算一个文件的Blake2b校验和,返回字节数组。
|
||||
pub fn sum_file<P: AsRef<Path>>(file_path: P, bit_size: Option<usize>) -> io::Result<Vec<u8>> {
|
||||
let size = bit_size.unwrap_or(512);
|
||||
let mut file = File::open(file_path)?;
|
||||
let mut hasher = hasher_select(size);
|
||||
|
||||
let mut buffer = [0; 8192];
|
||||
loop {
|
||||
let bytes_read = file.read(&mut buffer)?;
|
||||
if bytes_read == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..bytes_read]);
|
||||
}
|
||||
|
||||
Ok(hasher.finalize().as_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// 根据给定位数计算一个文件的Blake2b校验和,返回十六进制字符串。
|
||||
pub fn sum_file_hex<P: AsRef<Path>>(file_path: P, bit_size: Option<usize>) -> io::Result<String> {
|
||||
let hash = sum_file(file_path, bit_size)?;
|
||||
Ok(hex::encode(hash))
|
||||
}
|
109
src/hash/blake3/mod.rs
Normal file
109
src/hash/blake3/mod.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
use blake3::Hasher;
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Result as IoResult};
|
||||
use std::path::Path;
|
||||
|
||||
/// 计算给定字节数组的Blake3/512校验和,返回字节数组。
|
||||
pub fn blake3(data: &[u8]) -> Vec<u8> {
|
||||
let mut hasher = Hasher::new();
|
||||
hasher.update(data);
|
||||
let mut out = vec![0u8, 64];
|
||||
hasher.finalize_xof().fill(&mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake3/256校验和,返回字节数组。
|
||||
pub fn blake3_256(data: &[u8]) -> Vec<u8> {
|
||||
let mut hasher = Hasher::new();
|
||||
hasher.update(data);
|
||||
hasher.finalize().as_bytes().to_vec()
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake3/384校验和,返回字节数组。
|
||||
pub fn blake3_384(data: &[u8]) -> Vec<u8> {
|
||||
let mut hasher = Hasher::new();
|
||||
hasher.update(data);
|
||||
let mut out = vec![0u8, 48];
|
||||
hasher.finalize_xof().fill(&mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake3/224校验和,返回字节数组。
|
||||
pub fn blake3_224(data: &[u8]) -> Vec<u8> {
|
||||
let mut hasher = Hasher::new();
|
||||
hasher.update(data);
|
||||
let mut out = vec![0u8, 28];
|
||||
hasher.finalize_xof().fill(&mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake3校验和,返回十六进制字符串。
|
||||
pub fn blake3_hex(data: &[u8]) -> String {
|
||||
hex::encode(blake3(data))
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake3/256校验和,返回十六进制字符串。
|
||||
pub fn blake3_256_hex(data: &[u8]) -> String {
|
||||
hex::encode(blake3_256(data))
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake3/384校验和,返回十六进制字符串。
|
||||
pub fn blake3_384_hex(data: &[u8]) -> String {
|
||||
hex::encode(blake3_384(data))
|
||||
}
|
||||
|
||||
/// 计算给定字节数组的Blake3/224校验和,返回十六进制字符串。
|
||||
pub fn blake3_224_hex(data: &[u8]) -> String {
|
||||
hex::encode(blake3_224(data))
|
||||
}
|
||||
|
||||
/// 根据给定位数计算一个字节数组的Blake3校验和,返回字节数组。
|
||||
pub fn sum(data: &[u8], bit_size: Option<usize>) -> Vec<u8> {
|
||||
match bit_size {
|
||||
Some(bit_size) => match bit_size {
|
||||
224 => blake3_224(data),
|
||||
256 => blake3_256(data),
|
||||
384 => blake3_384(data),
|
||||
512 | _ => blake3(data),
|
||||
},
|
||||
None => blake3(data),
|
||||
}
|
||||
}
|
||||
|
||||
/// 根据给定位数计算一个字节数组的Blake3校验和,返回十六进制字符串。
|
||||
pub fn sum_hex(data: &[u8], bit_size: Option<usize>) -> String {
|
||||
hex::encode(sum(data, bit_size))
|
||||
}
|
||||
|
||||
/// 根据给定位数计算一个文件的Blake3校验和,返回字节数组。
|
||||
pub fn sum_file<P: AsRef<Path>>(file: P, bit_size: Option<usize>) -> IoResult<Vec<u8>> {
|
||||
let mut f = File::open(file)?;
|
||||
let mut hasher = Hasher::new();
|
||||
|
||||
let mut buffer = [0; 8192];
|
||||
loop {
|
||||
let bytes_read = f.read(&mut buffer)?;
|
||||
if bytes_read == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..bytes_read]);
|
||||
}
|
||||
|
||||
let mut out = match bit_size {
|
||||
Some(bit_size) => match bit_size {
|
||||
224 => vec![0u8, 28],
|
||||
256 => vec![0u8, 32],
|
||||
384 => vec![0u8, 48],
|
||||
512 | _ => vec![0u8, 64],
|
||||
},
|
||||
None => vec![0u8, 64],
|
||||
};
|
||||
hasher.finalize_xof().fill(&mut out);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 根据给定位数计算一个文件的Blake3校验和,返回十六进制字符串。
|
||||
pub fn sum_file_hex<P: AsRef<Path>>(file: P, bit_size: Option<usize>) -> IoResult<String> {
|
||||
let hash = sum_file(file, bit_size)?;
|
||||
Ok(hex::encode(hash))
|
||||
}
|
@@ -93,3 +93,6 @@ pub mod image_hash {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod blake2b;
|
||||
pub mod blake3;
|
||||
|
@@ -1,22 +1,20 @@
|
||||
use core::time;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::{Arc, LazyLock, Mutex, OnceLock};
|
||||
|
||||
use chrono::NaiveDateTime;
|
||||
use once_cell::sync::{Lazy, OnceCell};
|
||||
use ::time::{macros::datetime, OffsetDateTime};
|
||||
use thiserror::Error;
|
||||
|
||||
const HAIL_PERIOD_START: Lazy<i64> = Lazy::new(|| {
|
||||
const HAIL_PERIOD_START: LazyLock<i64> = LazyLock::new(|| {
|
||||
crate::time::date(2022, 2, 22)
|
||||
.map(|d| d.and_hms_opt(22, 22, 22))
|
||||
.flatten()
|
||||
.map(|dt| crate::time::attach_asia_shanghai(dt))
|
||||
.map(|dt| dt.timestamp())
|
||||
.unwrap_or_else(|| NaiveDateTime::MIN.timestamp())
|
||||
.map(|d| d.with_hms_nano(22, 22, 22, 222_222_222).unwrap())
|
||||
.map(crate::time::attach_asia_shanghai)
|
||||
.map(OffsetDateTime::unix_timestamp)
|
||||
.unwrap_or_else(|| datetime!(1970-01-01 0:00 +8).unix_timestamp())
|
||||
});
|
||||
type TimestampValidator = fn(i64) -> bool;
|
||||
type TimestampGenerator = fn() -> i64;
|
||||
|
||||
static INSTANCE: OnceCell<HailSerialCodeAlgorithm> = OnceCell::new();
|
||||
static INSTANCE: OnceLock<HailSerialCodeAlgorithm> = OnceLock::new();
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum HailSerialCodeAlgorithmError {
|
||||
@@ -65,7 +63,7 @@ impl HailSerialCodeAlgorithm {
|
||||
|
||||
/// 生成一个自计时起点以来的时间戳。
|
||||
fn generate_timestamp(&self) -> i64 {
|
||||
let current_time = crate::time::now_asia_shanghai().timestamp();
|
||||
let current_time = crate::time::now_asia_shanghai().unix_timestamp();
|
||||
current_time - *HAIL_PERIOD_START
|
||||
}
|
||||
|
||||
|
@@ -1,4 +1,5 @@
|
||||
pub mod hail;
|
||||
pub mod uuidv7;
|
||||
|
||||
pub mod uuid {
|
||||
/// 生成一个UUID v4字符串。
|
||||
|
291
src/serial_code/uuidv7.rs
Normal file
291
src/serial_code/uuidv7.rs
Normal file
@@ -0,0 +1,291 @@
|
||||
use std::{
|
||||
sync::{Mutex, OnceLock},
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use thiserror::Error;
|
||||
use time::UtcDateTime;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum UuidV7Error {
|
||||
#[error("UUIDv7 Generator not initialized")]
|
||||
GeneratorNotInitialized,
|
||||
#[error("UUIDv7 Node ID exceeded the maximum supports")]
|
||||
NodeIdExceeded,
|
||||
#[error("Invalid UUIDv7 string format")]
|
||||
InvalidStringFormat,
|
||||
#[error("Invalid Base64 format string")]
|
||||
InvalidBase64Format,
|
||||
}
|
||||
|
||||
const EPOCH: i64 = 1645566142222; // 自定义纪元:2022-02-22 22:22:22.222 UTC
|
||||
const NODE_BITS: u8 = 5; // 主机编号容量为0~32
|
||||
const SEQUENCE_BITS: u8 = 18; // 每毫秒生成序列号最大为2^18-1,即262144个
|
||||
const MAX_NODE_ID: u16 = (1 << NODE_BITS) - 1;
|
||||
const MAX_SEQUENCE: u32 = (1 << SEQUENCE_BITS) - 1;
|
||||
const TIMESTAMP_SHIFTS: u8 = NODE_BITS + SEQUENCE_BITS;
|
||||
const NODE_SHIFTS: u8 = SEQUENCE_BITS;
|
||||
|
||||
pub struct Uuidv7Generator {
|
||||
node_id: u16,
|
||||
last_timestamp: i64,
|
||||
sequence: u32,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub struct Uuidv7Components {
|
||||
timestamp: i64, // 毫秒时间戳(相对于自定义纪元)
|
||||
node_id: u16, // 5位节点ID
|
||||
sequence: u32, // 18位序列号
|
||||
version: u8, // 版本号(应为7)
|
||||
variant: u8, // 变体(应为2,表示10xx)
|
||||
raw_bytes: [u8; 16], // 原始字节
|
||||
}
|
||||
|
||||
static GENERATOR: OnceLock<Mutex<Uuidv7Generator>> = OnceLock::new();
|
||||
|
||||
/// 获取UUIDv7生成器实例,如果实例未初始化,则返回错误。
|
||||
pub fn generator<'a>() -> Result<&'a Mutex<Uuidv7Generator>, UuidV7Error> {
|
||||
GENERATOR.get().ok_or(UuidV7Error::GeneratorNotInitialized)
|
||||
}
|
||||
|
||||
/// 初始化UUIDv7生成器实例。
|
||||
///
|
||||
/// - `node_id`:节点ID,取值范围:0~32。
|
||||
pub fn init_generator(node_id: u16) -> Result<(), UuidV7Error> {
|
||||
if node_id > MAX_NODE_ID {
|
||||
return Err(UuidV7Error::NodeIdExceeded);
|
||||
}
|
||||
GENERATOR
|
||||
.set(Mutex::new(Uuidv7Generator::new(node_id)))
|
||||
.map_err(|_| UuidV7Error::GeneratorNotInitialized)
|
||||
}
|
||||
|
||||
impl Uuidv7Generator {
|
||||
pub fn new(node_id: u16) -> Self {
|
||||
Self {
|
||||
node_id,
|
||||
last_timestamp: EPOCH,
|
||||
sequence: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn now(&self) -> i64 {
|
||||
(UtcDateTime::now().unix_timestamp_nanos() / 1_000_000 - EPOCH as i128) as i64
|
||||
}
|
||||
|
||||
pub fn next(&mut self) -> Uuidv7Components {
|
||||
let mut now = self.now();
|
||||
if now < self.last_timestamp {
|
||||
now = self.last_timestamp;
|
||||
}
|
||||
if now == self.last_timestamp {
|
||||
self.sequence += 1;
|
||||
if self.sequence > MAX_SEQUENCE {
|
||||
thread::sleep(Duration::from_secs(1));
|
||||
now = self.now();
|
||||
self.sequence = 0;
|
||||
}
|
||||
} else {
|
||||
self.sequence = 0;
|
||||
}
|
||||
self.last_timestamp = now;
|
||||
Uuidv7Components {
|
||||
timestamp: now,
|
||||
node_id: self.node_id,
|
||||
sequence: self.sequence,
|
||||
version: 7,
|
||||
variant: 2,
|
||||
raw_bytes: [0; 16],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Uuidv7Components {
|
||||
pub fn bytes(&self) -> [u8; 16] {
|
||||
let mut uuid = [0u8; 16];
|
||||
|
||||
// 时间戳(48 位)
|
||||
let timestamp = (self.timestamp as u64) << TIMESTAMP_SHIFTS;
|
||||
let seq_and_node = ((self.sequence as u64) << NODE_SHIFTS) | (self.node_id as u64);
|
||||
|
||||
// 写入高位时间戳
|
||||
uuid[0] = (timestamp >> 56) as u8;
|
||||
uuid[1] = (timestamp >> 48) as u8;
|
||||
uuid[2] = (timestamp >> 40) as u8;
|
||||
uuid[3] = (timestamp >> 32) as u8;
|
||||
uuid[4] = (timestamp >> 24) as u8;
|
||||
uuid[5] = (timestamp >> 16) as u8;
|
||||
|
||||
// 写入低位时间戳 + 版本号(4 位)
|
||||
uuid[6] = ((timestamp >> 8) as u8) | 0x70; // version 7
|
||||
|
||||
// 写入 seq + node
|
||||
uuid[7] = timestamp as u8;
|
||||
uuid[8] = ((seq_and_node >> 16) as u8) | 0x80; // variant 10xx
|
||||
uuid[9] = (seq_and_node >> 8) as u8;
|
||||
uuid[10] = seq_and_node as u8;
|
||||
|
||||
// 剩余位使用随机数填充
|
||||
use rand::RngCore;
|
||||
let mut rng = rand::thread_rng();
|
||||
rng.fill_bytes(&mut uuid[11..16]);
|
||||
|
||||
uuid
|
||||
}
|
||||
|
||||
pub fn to_base64(&self) -> String {
|
||||
let uuid = self.bytes();
|
||||
crate::serialize::to_base64_str(uuid)
|
||||
}
|
||||
|
||||
pub fn try_from_base64<S: AsRef<str>>(uuid_str: S) -> Result<Self, UuidV7Error> {
|
||||
let bytes = crate::serialize::from_base64_str(uuid_str.as_ref())
|
||||
.map_err(|_| UuidV7Error::InvalidBase64Format)?;
|
||||
|
||||
if bytes.len() != 16 {
|
||||
return Err(UuidV7Error::InvalidStringFormat);
|
||||
}
|
||||
|
||||
let mut uuid_bytes = [0u8; 16];
|
||||
uuid_bytes.copy_from_slice(&bytes);
|
||||
|
||||
Uuidv7Components::try_from(uuid_bytes)
|
||||
}
|
||||
|
||||
pub fn to_base36(&self) -> String {
|
||||
let uuid = self.bytes();
|
||||
crate::serialize::base36::encode(&uuid)
|
||||
}
|
||||
|
||||
pub fn try_from_base36<S: AsRef<str>>(uuid_str: S) -> Result<Self, UuidV7Error> {
|
||||
let bytes = crate::serialize::base36::decode(uuid_str.as_ref())
|
||||
.map_err(|_| UuidV7Error::InvalidStringFormat)?;
|
||||
|
||||
if bytes.len() != 16 {
|
||||
return Err(UuidV7Error::InvalidStringFormat);
|
||||
}
|
||||
|
||||
let mut uuid_bytes = [0u8; 16];
|
||||
uuid_bytes.copy_from_slice(&bytes);
|
||||
|
||||
Uuidv7Components::try_from(uuid_bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl ToString for Uuidv7Components {
|
||||
fn to_string(&self) -> String {
|
||||
let uuid = self.bytes();
|
||||
format!(
|
||||
"{}-{}-{}-{}-{}",
|
||||
hex::encode(&uuid[0..4]),
|
||||
hex::encode(&uuid[4..6]),
|
||||
hex::encode(&uuid[6..8]),
|
||||
hex::encode(&uuid[8..10]),
|
||||
hex::encode(&uuid[10..16])
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Uuidv7Components {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.timestamp == other.timestamp
|
||||
&& self.node_id == other.node_id
|
||||
&& self.sequence == other.sequence
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Uuidv7Components {}
|
||||
|
||||
impl PartialOrd for Uuidv7Components {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
if self.timestamp != other.timestamp {
|
||||
return Some(self.timestamp.cmp(&other.timestamp));
|
||||
}
|
||||
|
||||
if self.sequence != other.sequence {
|
||||
return Some(self.sequence.cmp(&other.sequence));
|
||||
}
|
||||
|
||||
if self.node_id != other.node_id {
|
||||
// 注意:这里与时间戳和序列号不同,node_id的比较逻辑是反的
|
||||
// 这与Go代码中的Compare方法保持一致
|
||||
return Some(other.node_id.cmp(&self.node_id));
|
||||
}
|
||||
|
||||
Some(std::cmp::Ordering::Equal)
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Uuidv7Components {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.partial_cmp(other).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<[u8; 16]> for Uuidv7Components {
|
||||
type Error = UuidV7Error;
|
||||
|
||||
fn try_from(value: [u8; 16]) -> Result<Self, Self::Error> {
|
||||
// 提取时间戳(前48位)
|
||||
let timestamp = ((value[0] as i64) << 40)
|
||||
| ((value[1] as i64) << 32)
|
||||
| ((value[2] as i64) << 24)
|
||||
| ((value[3] as i64) << 16)
|
||||
| ((value[4] as i64) << 8)
|
||||
| (value[5] as i64);
|
||||
|
||||
// 提取版本号(第6字节的高4位)
|
||||
let version = (value[6] >> 4) as u8;
|
||||
|
||||
// 提取变体(第8字节的高2位)
|
||||
let variant = (value[8] >> 6) as u8;
|
||||
|
||||
// 提取序列号和节点ID
|
||||
// 第8字节的低6位 + 第9字节 + 第10字节组成23位
|
||||
let seq_and_node = (((value[8] & 0x3F) as i64) << 16) // 第8字节低6位
|
||||
| ((value[9] as i64) << 8) // 第9字节
|
||||
| (value[10] as i64); // 第10字节
|
||||
|
||||
// 分离序列号(高18位)和节点ID(低5位)
|
||||
let sequence = (seq_and_node >> 5) as u32;
|
||||
let node_id = (seq_and_node & 0x1F) as u16;
|
||||
|
||||
Ok(Uuidv7Components {
|
||||
timestamp,
|
||||
node_id,
|
||||
sequence,
|
||||
version,
|
||||
variant,
|
||||
raw_bytes: value,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<String> for Uuidv7Components {
|
||||
type Error = UuidV7Error;
|
||||
|
||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||
// 移除连字符
|
||||
let clean_str = value.replace("-", "");
|
||||
|
||||
// 验证长度
|
||||
if clean_str.len() != 32 {
|
||||
return Err(UuidV7Error::InvalidStringFormat);
|
||||
}
|
||||
|
||||
// 解码十六进制字符串
|
||||
let bytes = hex::decode(&clean_str).map_err(|_| UuidV7Error::InvalidStringFormat)?;
|
||||
|
||||
// 转换为数组
|
||||
if bytes.len() != 16 {
|
||||
return Err(UuidV7Error::InvalidStringFormat);
|
||||
}
|
||||
|
||||
let mut uuid_bytes = [0u8; 16];
|
||||
uuid_bytes.copy_from_slice(&bytes);
|
||||
|
||||
Uuidv7Components::try_from(uuid_bytes)
|
||||
}
|
||||
}
|
144
src/serialize/base36.rs
Normal file
144
src/serialize/base36.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
use thiserror::Error;
|
||||
|
||||
const BASE36_CHARS: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Base36Error {
|
||||
#[error("number too large for i64")]
|
||||
NumberTooLarge,
|
||||
#[error("invalid character '{0}'")]
|
||||
InvalidCharacter(char),
|
||||
}
|
||||
|
||||
/// 将字节数据编码为Base36字符串(大写),使用=作为padding字符
|
||||
pub fn encode(src: &[u8]) -> String {
|
||||
if src.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
// 将字节转换为大数表示,这里使用Vec<u8>模拟大整数运算
|
||||
let mut num = src.to_vec();
|
||||
|
||||
// 去除前导零但保留至少一个字节
|
||||
while num.len() > 1 && num[0] == 0 {
|
||||
num.remove(0);
|
||||
}
|
||||
|
||||
// 如果输入为全零字节,则直接返回"0"
|
||||
if num.iter().all(|&b| b == 0) {
|
||||
return "0".to_string();
|
||||
}
|
||||
|
||||
// 进行Base36编码
|
||||
let mut result = Vec::new();
|
||||
let base = 36u8;
|
||||
|
||||
// 重复除以36,获取余数作为字符
|
||||
while !num.is_empty() && !(num.len() == 1 && num[0] == 0) {
|
||||
let mut remainder: u16 = 0;
|
||||
let mut new_num = Vec::new();
|
||||
let mut first = true;
|
||||
|
||||
for &byte in &num {
|
||||
remainder = remainder * 256 + byte as u16;
|
||||
let quotient = remainder / base as u16;
|
||||
remainder %= base as u16;
|
||||
|
||||
if quotient > 0 || !first {
|
||||
new_num.push(quotient as u8);
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
|
||||
// 如果new_num为空,说明这是最后一次除法
|
||||
if !new_num.is_empty() || num.len() > 1 {
|
||||
num = new_num;
|
||||
} else {
|
||||
num.clear();
|
||||
}
|
||||
|
||||
result.push(BASE36_CHARS[remainder as usize]);
|
||||
}
|
||||
|
||||
// 反转字符串,因为我们是从低位开始计算的
|
||||
result.reverse();
|
||||
String::from_utf8(result).unwrap()
|
||||
}
|
||||
|
||||
/// 将Base36字符串(可为任意大小写)解码为字节数组
|
||||
pub fn decode(src: &str) -> Result<Vec<u8>, Base36Error> {
|
||||
if src.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
// 移除padding字符并转换为大写
|
||||
let cleaned: String = src.chars().filter(|&c| c != '=').collect();
|
||||
let cleaned = cleaned.to_uppercase();
|
||||
|
||||
// 使用Vec<u8>模拟大整数进行解码
|
||||
let mut num = Vec::new();
|
||||
let base = 36u16;
|
||||
|
||||
for c in cleaned.chars() {
|
||||
let digit = match c {
|
||||
'0'..='9' => c as u16 - '0' as u16,
|
||||
'A'..='Z' => c as u16 - 'A' as u16 + 10,
|
||||
_ => return Err(Base36Error::InvalidCharacter(c)),
|
||||
};
|
||||
|
||||
// num = num * 36 + digit
|
||||
let mut carry = digit as u32;
|
||||
for byte in num.iter_mut() {
|
||||
let product = *byte as u32 * base as u32 + carry;
|
||||
*byte = (product % 256) as u8;
|
||||
carry = product / 256;
|
||||
}
|
||||
|
||||
while carry > 0 {
|
||||
num.push((carry % 256) as u8);
|
||||
carry /= 256;
|
||||
}
|
||||
}
|
||||
|
||||
// 反转字节数组,因为我们的计算是从低位开始的
|
||||
num.reverse();
|
||||
|
||||
// 如果结果为空,返回单个零字节
|
||||
if num.is_empty() {
|
||||
num.push(0);
|
||||
}
|
||||
|
||||
Ok(num)
|
||||
}
|
||||
|
||||
/// Encode的别名,用于保持与标准库一致的命名
|
||||
pub fn encode_to_string(src: &[u8]) -> String {
|
||||
encode(src)
|
||||
}
|
||||
|
||||
/// Decode的别名,用于保持与标准库一致的命名
|
||||
pub fn decode_string(src: &str) -> Result<Vec<u8>, Base36Error> {
|
||||
decode(src)
|
||||
}
|
||||
|
||||
/// 将int64转换为Base36字符串
|
||||
pub fn encode_int64(num: i64) -> String {
|
||||
let bytes = num.to_be_bytes().to_vec();
|
||||
encode(&bytes)
|
||||
}
|
||||
|
||||
/// 将Base36字符串解码为int64
|
||||
pub fn decode_to_int64(src: &str) -> Result<i64, Base36Error> {
|
||||
let bytes = decode(src)?;
|
||||
if bytes.len() > 8 {
|
||||
return Err(Base36Error::NumberTooLarge);
|
||||
}
|
||||
|
||||
let mut array = [0u8; 8];
|
||||
let start = 8 - bytes.len();
|
||||
for (i, &byte) in bytes.iter().enumerate() {
|
||||
array[start + i] = byte;
|
||||
}
|
||||
|
||||
Ok(i64::from_be_bytes(array))
|
||||
}
|
@@ -1,6 +1,8 @@
|
||||
use base64::Engine;
|
||||
use thiserror::Error;
|
||||
|
||||
pub mod base36;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum HexSerializeError {
|
||||
#[error("Invalid hex char: {0}")]
|
||||
|
108
src/time/mod.rs
108
src/time/mod.rs
@@ -1,46 +1,36 @@
|
||||
use chrono::{DateTime, Datelike, Duration, FixedOffset, NaiveDate, NaiveDateTime, Utc};
|
||||
use std::i64;
|
||||
|
||||
use time::{macros::offset, Date, Month, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset};
|
||||
|
||||
/// 获取一个类型为`chrono::DateTime<chrono::FixedOffset>`类型的当前日期时间的实例。时间时区将自动被设置为东八区。
|
||||
pub fn now_asia_shanghai() -> DateTime<FixedOffset> {
|
||||
let utc_now = Utc::now();
|
||||
pub fn now_asia_shanghai() -> OffsetDateTime {
|
||||
let utc_now = OffsetDateTime::now_utc();
|
||||
shift_to_asia_shanghai(utc_now)
|
||||
}
|
||||
|
||||
/// 将一个类型为`chrono::DateTime<chrono::Utc>`类型的日期时间转换到指定时区的时间实例。
|
||||
pub fn shift_tz(datetime: DateTime<Utc>, zone: i64) -> DateTime<FixedOffset> {
|
||||
if zone.is_positive() {
|
||||
datetime.with_timezone(
|
||||
&FixedOffset::east_opt(Duration::hours(zone.abs()).num_seconds() as i32).unwrap(),
|
||||
)
|
||||
} else {
|
||||
datetime.with_timezone(
|
||||
&FixedOffset::west_opt(Duration::hours(zone.abs()).num_seconds() as i32).unwrap(),
|
||||
)
|
||||
}
|
||||
pub fn shift_tz(datetime: OffsetDateTime, zone: i8) -> OffsetDateTime {
|
||||
datetime.to_offset(UtcOffset::from_hms(zone.clamp(-25, 25), 0, 0).unwrap())
|
||||
}
|
||||
|
||||
/// 将一个类型为`chrono::DateTime<chrono::Utc>`类型的日期时间转换到东八区的时间实例。
|
||||
pub fn shift_to_asia_shanghai(datetime: DateTime<Utc>) -> DateTime<FixedOffset> {
|
||||
shift_tz(datetime, 8)
|
||||
pub fn shift_to_asia_shanghai(datetime: OffsetDateTime) -> OffsetDateTime {
|
||||
datetime.to_offset(offset!(+8))
|
||||
}
|
||||
|
||||
/// 直接给一个原生日期时间附加东八区的时区信息。
|
||||
pub fn attach_asia_shanghai(datetime: NaiveDateTime) -> DateTime<FixedOffset> {
|
||||
DateTime::<FixedOffset>::from_local(
|
||||
datetime,
|
||||
FixedOffset::east_opt(Duration::hours(8).num_seconds() as i32).unwrap(),
|
||||
)
|
||||
pub fn attach_asia_shanghai(datetime: PrimitiveDateTime) -> OffsetDateTime {
|
||||
let utc_date_time = datetime.as_utc();
|
||||
let offseted_date_time = OffsetDateTime::from(utc_date_time);
|
||||
offseted_date_time.replace_offset(offset!(+8))
|
||||
}
|
||||
|
||||
/// 从一个64位时间戳生成东八区的时间实例。这个函数主要用于处理使用`timestamp`方法直接返回的时间戳。
|
||||
///
|
||||
/// - `timestamp`:64位时间戳。
|
||||
pub fn from_utc_timestamp(timestamp: i64) -> DateTime<FixedOffset> {
|
||||
let request_time = NaiveDateTime::from_timestamp_micros(timestamp).unwrap();
|
||||
DateTime::<FixedOffset>::from_utc(
|
||||
request_time,
|
||||
FixedOffset::east_opt(Duration::hours(8).num_seconds() as i32).unwrap(),
|
||||
)
|
||||
pub fn from_utc_timestamp(timestamp: i64) -> OffsetDateTime {
|
||||
let request_time = OffsetDateTime::from_unix_timestamp(timestamp.clamp(0, i64::MAX)).unwrap();
|
||||
request_time.to_offset(offset!(+8))
|
||||
}
|
||||
|
||||
/// 根据指定的日期生成一个时间对象,如果给定的日期不合法将返回空白内容。
|
||||
@@ -48,8 +38,8 @@ pub fn from_utc_timestamp(timestamp: i64) -> DateTime<FixedOffset> {
|
||||
/// - `year`:日期的年份。
|
||||
/// - `month`:日期的月份,从`1`开始。
|
||||
/// - `day`:日期的天数。
|
||||
pub fn date(year: i32, month: u32, day: u32) -> Option<NaiveDate> {
|
||||
NaiveDate::from_ymd_opt(year, month, day)
|
||||
pub fn date(year: i32, month: u8, day: u8) -> Option<Date> {
|
||||
Date::from_calendar_date(year, Month::try_from(month.clamp(1, 12)).unwrap(), day).ok()
|
||||
}
|
||||
|
||||
/// 根据指定日期生成一个指定日期最开始时间的时间,精度为毫秒。
|
||||
@@ -57,29 +47,26 @@ pub fn date(year: i32, month: u32, day: u32) -> Option<NaiveDate> {
|
||||
/// - `year`:指定日期的年份。
|
||||
/// - `month`:指定日期的月份,从`1`开始。
|
||||
/// - `day`:指定日期的天数。
|
||||
pub fn date_beginning(year: i32, month: u32, day: u32) -> Option<DateTime<FixedOffset>> {
|
||||
let timezone = FixedOffset::east_opt(Duration::hours(8).num_seconds() as i32).unwrap();
|
||||
NaiveDate::from_ymd_opt(year, month, day)
|
||||
.map(|d| d.and_hms_micro_opt(0, 0, 0, 0).unwrap())
|
||||
.map(|dt| DateTime::<FixedOffset>::from_local(dt, timezone))
|
||||
pub fn date_beginning(year: i32, month: u8, day: u8) -> OffsetDateTime {
|
||||
OffsetDateTime::new_in_offset(
|
||||
Date::from_calendar_date(year, Month::try_from(month.clamp(1, 12)).unwrap(), day).unwrap(),
|
||||
Time::MIDNIGHT,
|
||||
offset!(+8),
|
||||
)
|
||||
}
|
||||
|
||||
/// 根据给定的日期,返回其当天最开始的时间,精度为毫秒。
|
||||
///
|
||||
/// - `date`:给定的原始日期,注意:原始日期将被消耗掉。
|
||||
pub fn begin_of_date(date: NaiveDate) -> Option<DateTime<FixedOffset>> {
|
||||
let timezone = FixedOffset::east_opt(Duration::hours(8).num_seconds() as i32).unwrap();
|
||||
date.and_hms_micro_opt(0, 0, 0, 0)
|
||||
.map(|dt| DateTime::<FixedOffset>::from_local(dt, timezone))
|
||||
pub fn begin_of_date(date: Date) -> OffsetDateTime {
|
||||
OffsetDateTime::new_in_offset(date, Time::MIDNIGHT, offset!(+8))
|
||||
}
|
||||
|
||||
/// 根据给定的日期,返回其当天即将结束的时间,精度为毫秒。
|
||||
///
|
||||
/// - `date`:给定的原始日期,注意:原始日期将被消耗掉。
|
||||
pub fn end_of_date(date: NaiveDate) -> Option<DateTime<FixedOffset>> {
|
||||
let timezone = FixedOffset::east_opt(Duration::hours(8).num_seconds() as i32).unwrap();
|
||||
date.and_hms_micro_opt(23, 59, 59, 999_999)
|
||||
.map(|dt| DateTime::<FixedOffset>::from_local(dt, timezone))
|
||||
pub fn end_of_date(date: Date) -> OffsetDateTime {
|
||||
OffsetDateTime::new_in_offset(date, Time::MAX, offset!(+8))
|
||||
}
|
||||
|
||||
/// 根据指定日期生成一个指定日期结束时间的时间,精度为毫秒。
|
||||
@@ -87,20 +74,19 @@ pub fn end_of_date(date: NaiveDate) -> Option<DateTime<FixedOffset>> {
|
||||
/// - `year`:指定日期的年份。
|
||||
/// - `month`:指定日期的月份,从`1`开始。
|
||||
/// - `day`:指定日期的天数。
|
||||
pub fn date_ending(year: i32, month: u32, day: u32) -> Option<DateTime<FixedOffset>> {
|
||||
let timezone = FixedOffset::east_opt(Duration::hours(8).num_seconds() as i32).unwrap();
|
||||
NaiveDate::from_ymd_opt(year, month, day)
|
||||
.map(|d| d.and_hms_micro_opt(23, 59, 59, 999_999).unwrap())
|
||||
.map(|dt| DateTime::<FixedOffset>::from_local(dt, timezone))
|
||||
pub fn date_ending(year: i32, month: u8, day: u8) -> Option<OffsetDateTime> {
|
||||
Date::from_calendar_date(year, Month::try_from(month.clamp(1, 12)).unwrap(), day)
|
||||
.ok()
|
||||
.map(end_of_date)
|
||||
}
|
||||
|
||||
/// 返回两个日期之间的月份差值。
|
||||
///
|
||||
/// - `control`:基准月份。
|
||||
/// - `test`:测试月份。
|
||||
pub fn difference_month(control: NaiveDate, test: NaiveDate) -> i32 {
|
||||
pub fn difference_month(control: Date, test: Date) -> i32 {
|
||||
let difference_year = test.year() - control.year();
|
||||
let difference_month = (test.month() - control.month()) as i32;
|
||||
let difference_month = u8::from(test.month()) as i32 - u8::from(control.month()) as i32;
|
||||
difference_year * 12 + difference_month
|
||||
}
|
||||
|
||||
@@ -108,40 +94,38 @@ pub fn difference_month(control: NaiveDate, test: NaiveDate) -> i32 {
|
||||
///
|
||||
/// - `control`:基准月份。
|
||||
/// - `test`:待测试的指定月份。
|
||||
pub fn is_previous_month(control: NaiveDate, test: NaiveDate) -> bool {
|
||||
difference_month(control, test) == 1
|
||||
pub fn is_previous_month(control: Date, test: Date) -> bool {
|
||||
control.month().previous() == test.month()
|
||||
}
|
||||
|
||||
/// 测试指定月份是否是基准月份的下一个月份。
|
||||
///
|
||||
/// - `control`:基准月份。
|
||||
/// - `test`:待测试的指定月份。
|
||||
pub fn is_next_month(control: NaiveDate, test: NaiveDate) -> bool {
|
||||
difference_month(control, test) == -1
|
||||
pub fn is_next_month(control: Date, test: Date) -> bool {
|
||||
control.month().next() == test.month()
|
||||
}
|
||||
|
||||
/// 生成符合Postgresql中日期类型最小值的日期。
|
||||
pub fn min_date() -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(1970, 1, 1).unwrap()
|
||||
pub fn min_date() -> Date {
|
||||
Date::from_calendar_date(1970, Month::January, 1).unwrap()
|
||||
}
|
||||
|
||||
/// 生成符合Postgresql中日期类型最小值的日期时间。
|
||||
pub fn min_datetime() -> DateTime<FixedOffset> {
|
||||
NaiveDate::from_ymd_opt(1970, 1, 1)
|
||||
pub fn min_datetime() -> OffsetDateTime {
|
||||
Date::from_calendar_date(1970, Month::January, 1)
|
||||
.map(begin_of_date)
|
||||
.flatten()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// 生成符合Postgresql中日期类型最大值的日期。
|
||||
pub fn max_date() -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(2099, 12, 31).unwrap()
|
||||
pub fn max_date() -> Date {
|
||||
Date::from_calendar_date(2099, Month::December, 31).unwrap()
|
||||
}
|
||||
|
||||
/// 生成符合Postgresql中日期类型最大值的日期时间。
|
||||
pub fn max_datetime() -> DateTime<FixedOffset> {
|
||||
NaiveDate::from_ymd_opt(2099, 12, 31)
|
||||
pub fn max_datetime() -> OffsetDateTime {
|
||||
Date::from_calendar_date(2099, Month::December, 31)
|
||||
.map(end_of_date)
|
||||
.flatten()
|
||||
.unwrap()
|
||||
}
|
||||
|
Reference in New Issue
Block a user