From 4211ead59edc008e65aca2ed69e9f87de26e37b2 Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Thu, 22 Jun 2023 10:01:04 -0700 Subject: [PATCH] tidy the db_ids a bit --- src/db_id.rs | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/src/db_id.rs b/src/db_id.rs index 5b7e2f6..404ff49 100644 --- a/src/db_id.rs +++ b/src/db_id.rs @@ -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 { @@ -76,7 +75,6 @@ impl sqlx::Type for DbId { } } -// sqlx traits for marshalling in and out impl<'q> Encode<'q, Sqlite> for DbId { fn encode(self, args: &mut Vec>) -> 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 { let bytes = <&[u8] as Decode>::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(self, v: u128) -> Result where E: serde::de::Error, { - Ok(DbId(Ulid(v))) + Ok(v.into()) } fn visit_bytes(self, v: &[u8]) -> Result @@ -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, ])],