2023-06-21 23:30:13 +00:00
|
|
|
use std::{
|
|
|
|
borrow::Cow,
|
|
|
|
fmt::{Debug, Display},
|
|
|
|
};
|
|
|
|
|
2023-06-29 23:27:21 +00:00
|
|
|
use chrono::Utc;
|
2023-06-21 23:30:13 +00:00
|
|
|
use serde::{de::Visitor, Deserialize, Serialize};
|
|
|
|
use sqlx::{
|
|
|
|
encode::IsNull,
|
|
|
|
sqlite::{SqliteArgumentValue, SqliteValueRef},
|
|
|
|
Decode, Encode, Sqlite,
|
|
|
|
};
|
|
|
|
use ulid::Ulid;
|
|
|
|
|
|
|
|
#[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
|
|
pub struct DbId(pub Ulid);
|
|
|
|
|
|
|
|
impl DbId {
|
|
|
|
pub fn bytes(&self) -> [u8; 16] {
|
2023-06-22 21:10:18 +00:00
|
|
|
self.to_be_bytes()
|
2023-06-21 23:30:13 +00:00
|
|
|
}
|
|
|
|
|
2023-06-22 21:10:18 +00:00
|
|
|
pub fn to_be_bytes(self) -> [u8; 16] {
|
2023-06-21 23:30:13 +00:00
|
|
|
self.0 .0.to_be_bytes()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn is_nil(&self) -> bool {
|
|
|
|
self.0.is_nil()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn new() -> Self {
|
2023-06-22 17:01:04 +00:00
|
|
|
Self(Ulid::new())
|
2023-06-21 23:30:13 +00:00
|
|
|
}
|
|
|
|
|
2023-07-01 22:42:01 +00:00
|
|
|
pub fn from_string(s: &str) -> Result<Self, ulid::DecodeError> {
|
2023-06-21 23:30:13 +00:00
|
|
|
let id = Ulid::from_string(s)?;
|
|
|
|
Ok(id.into())
|
|
|
|
}
|
2023-06-28 16:51:15 +00:00
|
|
|
|
|
|
|
pub fn as_string(&self) -> String {
|
|
|
|
self.0.to_string()
|
|
|
|
}
|
2023-06-29 23:27:21 +00:00
|
|
|
|
|
|
|
pub fn created_at(&self) -> chrono::DateTime<Utc> {
|
|
|
|
self.0.datetime().into()
|
|
|
|
}
|
2023-06-21 23:30:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
//-************************************************************************
|
|
|
|
// standard trait impls
|
|
|
|
//-************************************************************************
|
|
|
|
|
|
|
|
impl Display for DbId {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
write!(f, "{}", self.0.to_string())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Debug for DbId {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
2023-07-01 22:42:01 +00:00
|
|
|
f.debug_tuple("DbId").field(&self.as_string()).finish()
|
2023-06-21 23:30:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<Ulid> for DbId {
|
|
|
|
fn from(value: Ulid) -> Self {
|
|
|
|
DbId(value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<u128> for DbId {
|
|
|
|
fn from(value: u128) -> Self {
|
|
|
|
DbId(value.into())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//-************************************************************************
|
|
|
|
// sqlx traits for going in and out of the db
|
|
|
|
//-************************************************************************
|
|
|
|
|
|
|
|
impl sqlx::Type<sqlx::Sqlite> for DbId {
|
|
|
|
fn type_info() -> <sqlx::Sqlite as sqlx::Database>::TypeInfo {
|
|
|
|
<&[u8] as sqlx::Type<sqlx::Sqlite>>::type_info()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'q> Encode<'q, Sqlite> for DbId {
|
|
|
|
fn encode_by_ref(&self, args: &mut Vec<SqliteArgumentValue<'q>>) -> IsNull {
|
|
|
|
args.push(SqliteArgumentValue::Blob(Cow::Owned(self.bytes().to_vec())));
|
|
|
|
IsNull::No
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-28 16:51:15 +00:00
|
|
|
impl Decode<'_, Sqlite> for DbId {
|
|
|
|
fn decode(value: SqliteValueRef<'_>) -> Result<Self, sqlx::error::BoxDynError> {
|
2023-06-21 23:30:13 +00:00
|
|
|
let bytes = <&[u8] as Decode<Sqlite>>::decode(value)?;
|
|
|
|
let bytes: [u8; 16] = bytes.try_into().unwrap_or_default();
|
2023-06-22 21:10:18 +00:00
|
|
|
Ok(u128::from_be_bytes(bytes).into())
|
2023-06-21 23:30:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//-************************************************************************
|
|
|
|
// serde traits
|
|
|
|
//-************************************************************************
|
|
|
|
impl Serialize for DbId {
|
|
|
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
|
|
|
where
|
|
|
|
S: serde::Serializer,
|
|
|
|
{
|
|
|
|
serializer.serialize_bytes(&self.bytes())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct DbIdVisitor;
|
|
|
|
|
|
|
|
impl<'de> Visitor<'de> for DbIdVisitor {
|
|
|
|
type Value = DbId;
|
|
|
|
|
|
|
|
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
2023-06-28 16:51:15 +00:00
|
|
|
formatter.write_str("16 bytes")
|
2023-06-21 23:30:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
|
|
|
|
where
|
|
|
|
E: serde::de::Error,
|
|
|
|
{
|
|
|
|
match std::convert::TryInto::<[u8; 16]>::try_into(v) {
|
2023-06-22 17:01:04 +00:00
|
|
|
Ok(v) => Ok(u128::from_be_bytes(v).into()),
|
2023-06-21 23:30:13 +00:00
|
|
|
Err(_) => Err(serde::de::Error::invalid_length(v.len(), &self)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
|
|
|
|
where
|
|
|
|
E: serde::de::Error,
|
|
|
|
{
|
|
|
|
let len = v.len();
|
|
|
|
match std::convert::TryInto::<[u8; 16]>::try_into(v) {
|
2023-06-22 17:01:04 +00:00
|
|
|
Ok(v) => Ok(u128::from_be_bytes(v).into()),
|
2023-06-21 23:30:13 +00:00
|
|
|
Err(_) => Err(serde::de::Error::invalid_length(len, &self)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
|
|
|
|
where
|
|
|
|
A: serde::de::SeqAccess<'de>,
|
|
|
|
{
|
2023-06-22 21:10:18 +00:00
|
|
|
let mut raw_bytes_from_db = [0u8; 16];
|
2023-06-21 23:30:13 +00:00
|
|
|
let size = seq.size_hint().unwrap_or(0);
|
|
|
|
let mut count = 0;
|
|
|
|
while let Some(val) = seq.next_element()? {
|
2023-06-22 17:01:04 +00:00
|
|
|
if count > 15 {
|
2023-06-21 23:30:13 +00:00
|
|
|
break;
|
|
|
|
}
|
2023-06-22 21:10:18 +00:00
|
|
|
raw_bytes_from_db[count] = val;
|
2023-06-21 23:30:13 +00:00
|
|
|
count += 1;
|
|
|
|
}
|
|
|
|
if count != 16 || size > 16 {
|
|
|
|
let sz = if count < 16 { count } else { size };
|
|
|
|
Err(serde::de::Error::invalid_length(sz, &self))
|
|
|
|
} else {
|
2023-06-22 21:10:18 +00:00
|
|
|
Ok(u128::from_be_bytes(raw_bytes_from_db).into())
|
2023-06-21 23:30:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'de> Deserialize<'de> for DbId {
|
|
|
|
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
|
|
|
where
|
|
|
|
D: serde::Deserializer<'de>,
|
|
|
|
{
|
|
|
|
deserializer.deserialize_bytes(DbIdVisitor)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//-************************************************************************
|
|
|
|
// serialization tests
|
|
|
|
//-************************************************************************
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use serde_test::{assert_tokens, Token};
|
|
|
|
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_ser_de() {
|
|
|
|
let bytes: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
|
2023-06-22 17:01:04 +00:00
|
|
|
let id: DbId = u128::from_be_bytes(bytes).into();
|
2023-06-21 23:30:13 +00:00
|
|
|
|
|
|
|
assert_tokens(
|
2023-06-22 17:01:04 +00:00
|
|
|
&id,
|
2023-06-21 23:30:13 +00:00
|
|
|
&[Token::Bytes(&[
|
|
|
|
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
|
|
|
])],
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|