tidy the db_ids a bit

This commit is contained in:
Joe Ardent 2023-06-22 10:01:04 -07:00
parent 656e6dceed
commit 4211ead59e

View file

@ -28,8 +28,7 @@ impl DbId {
}
pub fn new() -> Self {
let id = Ulid::new();
Self(id)
Self(Ulid::new())
}
pub fn from_str(s: &str) -> Result<Self, ulid::DecodeError> {
@ -76,7 +75,6 @@ impl sqlx::Type<sqlx::Sqlite> for DbId {
}
}
// sqlx traits for marshalling in and out
impl<'q> Encode<'q, Sqlite> for DbId {
fn encode(self, args: &mut Vec<SqliteArgumentValue<'q>>) -> IsNull {
args.push(SqliteArgumentValue::Blob(Cow::Owned(self.bytes().to_vec())));
@ -104,8 +102,7 @@ impl<'r> Decode<'r, Sqlite> for DbId {
fn decode(value: SqliteValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> {
let bytes = <&[u8] as Decode<Sqlite>>::decode(value)?;
let bytes: [u8; 16] = bytes.try_into().unwrap_or_default();
let id: Ulid = u128::from_ne_bytes(bytes).into();
Ok(id.into())
Ok(u128::from_ne_bytes(bytes).into())
}
}
@ -134,14 +131,14 @@ impl<'de> Visitor<'de> for DbIdVisitor {
where
E: serde::de::Error,
{
Ok(DbId(Ulid(v as u128)))
Ok((v as u128).into())
}
fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(DbId(Ulid(v)))
Ok(v.into())
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
@ -149,7 +146,7 @@ impl<'de> Visitor<'de> for DbIdVisitor {
E: serde::de::Error,
{
match std::convert::TryInto::<[u8; 16]>::try_into(v) {
Ok(v) => Ok(DbId(Ulid(u128::from_be_bytes(v)))),
Ok(v) => Ok(u128::from_be_bytes(v).into()),
Err(_) => Err(serde::de::Error::invalid_length(v.len(), &self)),
}
}
@ -160,7 +157,7 @@ impl<'de> Visitor<'de> for DbIdVisitor {
{
let len = v.len();
match std::convert::TryInto::<[u8; 16]>::try_into(v) {
Ok(v) => Ok(DbId(Ulid(u128::from_be_bytes(v)))),
Ok(v) => Ok(u128::from_be_bytes(v).into()),
Err(_) => Err(serde::de::Error::invalid_length(len, &self)),
}
}
@ -199,7 +196,7 @@ impl<'de> Visitor<'de> for DbIdVisitor {
let size = seq.size_hint().unwrap_or(0);
let mut count = 0;
while let Some(val) = seq.next_element()? {
if count >= 16 {
if count > 15 {
break;
}
bytes[count] = val;
@ -209,8 +206,7 @@ impl<'de> Visitor<'de> for DbIdVisitor {
let sz = if count < 16 { count } else { size };
Err(serde::de::Error::invalid_length(sz, &self))
} else {
let id = u128::from_ne_bytes(bytes);
Ok(id.into())
Ok(u128::from_ne_bytes(bytes).into())
}
}
}
@ -237,12 +233,10 @@ mod test {
#[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];
let be_num = u128::from_be_bytes(bytes);
let le_ulid = Ulid(be_num);
let le_id = DbId(le_ulid);
let id: DbId = u128::from_be_bytes(bytes).into();
assert_tokens(
&le_id,
&id,
&[Token::Bytes(&[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
])],