Skip to content

Commit

Permalink
Address feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
coolreader18 committed Oct 16, 2023
1 parent 1648f70 commit 4d1a143
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 19 deletions.
11 changes: 0 additions & 11 deletions crates/core/src/hash.rs

This file was deleted.

2 changes: 1 addition & 1 deletion crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub mod db;
pub mod messages;
pub use spacetimedb_lib::Identity;
pub mod error;
pub mod hash;
pub use spacetimedb_lib::hash;
pub use spacetimedb_lib::identity;
pub mod protobuf {
pub use spacetimedb_client_api_messages::*;
Expand Down
18 changes: 11 additions & 7 deletions crates/lib/src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use core::fmt;
use sha3::{Digest, Keccak256};
use spacetimedb_sats::{impl_deserialize, impl_serialize, impl_st, AlgebraicType};

use crate::hex::HexString;

pub const HASH_SIZE: usize = 32;

#[derive(Eq, PartialEq, PartialOrd, Ord, Clone, Copy, Hash)]
Expand All @@ -14,8 +16,6 @@ impl_serialize!([] Hash, (self, ser) => self.data.serialize(ser));
impl_deserialize!([] Hash, de => Ok(Self { data: <_>::deserialize(de)? }));

impl Hash {
const ABBREVIATION_LEN: usize = 16;

pub const ZERO: Self = Self { data: [0; HASH_SIZE] };

pub fn from_arr(arr: &[u8; HASH_SIZE]) -> Self {
Expand All @@ -31,12 +31,16 @@ impl Hash {
self.data.to_vec()
}

pub fn to_hex(&self) -> String {
hex::encode(self.data)
pub fn to_hex(&self) -> HexString<32> {
crate::hex::encode(&self.data)
}

pub fn abbreviate(&self) -> &[u8; 16] {
self.data[..16].try_into().unwrap()
}

pub fn to_abbreviated_hex(&self) -> String {
self.to_hex()[0..Hash::ABBREVIATION_LEN].to_owned()
pub fn to_abbreviated_hex(&self) -> HexString<16> {
crate::hex::encode(self.abbreviate())
}

pub fn as_slice(&self) -> &[u8] {
Expand All @@ -56,7 +60,7 @@ pub fn hash_bytes(bytes: impl AsRef<[u8]>) -> Hash {

impl fmt::Display for Hash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&hex::encode(self.data))
f.pad(&self.to_hex())
}
}

Expand Down
6 changes: 6 additions & 0 deletions crates/lib/src/hex.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
//! Allocation-free hex formatting.
//!
//! Given that most, if not all, of the types that we hex-format are of constant byte size (Hash,
//! Address, Identity), this hex implementation lets you format to hex without needing to allocate
//! a `String` on the heap.
use core::{fmt, ops, str};

#[derive(Copy, Clone)]
Expand Down

0 comments on commit 4d1a143

Please sign in to comment.