Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better TypeId #209

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion macros/src/type/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ pub fn derive(input: proc_macro::TokenStream) -> syn::Result<proc_macro::TokenSt
unraw_raw_ident(&format_ident!("{}", raw_ident.to_string())).to_token_stream()
});

let sid = quote!(#crate_ref::internal::construct::sid(#name, concat!("::", module_path!(), ":", line!(), ":", column!())));
let sid = quote!(#crate_ref::SpectaID::from::<Self>());
let (inlines, reference, can_flatten) = match data {
Data::Struct(data) => {
parse_struct(&name, &container_attrs, generics, &crate_ref, &sid, data)
Expand Down
58 changes: 31 additions & 27 deletions src/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,33 +154,6 @@
pub const fn impl_location(loc: &'static str) -> ImplLocation {
ImplLocation(loc)
}

/// Compute an SID hash for a given type.
/// This will produce a type hash from the arguments.
/// This hashing function was derived from https://stackoverflow.com/a/71464396
pub const fn sid(type_name: &'static str, type_identifier: &'static str) -> SpectaID {
let mut hash = 0xcbf29ce484222325;
let prime = 0x00000100000001B3;

let mut bytes = type_name.as_bytes();
let mut i = 0;

while i < bytes.len() {
hash ^= bytes[i] as u64;
hash = hash.wrapping_mul(prime);
i += 1;
}

bytes = type_identifier.as_bytes();
i = 0;
while i < bytes.len() {
hash ^= bytes[i] as u64;
hash = hash.wrapping_mul(prime);
i += 1;
}

SpectaID { type_name, hash }
}
}

pub type NonSkipField<'a> = (&'a Field, &'a DataType);
Expand Down Expand Up @@ -226,16 +199,16 @@
#[doc(hidden)]
/// A helper for exporting a command to a [`CommandDataType`].
/// You shouldn't use this directly and instead should use [`fn_datatype!`](crate::fn_datatype).
pub fn get_fn_datatype<TMarker, T: SpectaFunction<TMarker>>(
_: T,
asyncness: bool,
name: Cow<'static, str>,
type_map: &mut TypeMap,
fields: &[Cow<'static, str>],
docs: Cow<'static, str>,
deprecated: Option<DeprecatedType>,
no_return_type: bool,
) -> FunctionDataType {

Check warning on line 211 in src/internal.rs

View workflow job for this annotation

GitHub Actions / clippy

this function has too many arguments (8/7)

warning: this function has too many arguments (8/7) --> src/internal.rs:202:5 | 202 | / pub fn get_fn_datatype<TMarker, T: SpectaFunction<TMarker>>( 203 | | _: T, 204 | | asyncness: bool, 205 | | name: Cow<'static, str>, ... | 210 | | no_return_type: bool, 211 | | ) -> FunctionDataType { | |_________________________^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#too_many_arguments note: the lint level is defined here --> src/lib.rs:3:9 | 3 | #![warn(clippy::all, clippy::unwrap_used, clippy::panic)] // TODO: missing_docs | ^^^^^^^^^^^ = note: `#[warn(clippy::too_many_arguments)]` implied by `#[warn(clippy::all)]`
T::to_datatype(
asyncness,
name,
Expand All @@ -249,3 +222,34 @@
}
#[cfg(feature = "functions")]
pub use functions::*;

// This code is taken from `erased-serde` - https://github.com/dtolnay/erased-serde/blob/master/src/any.rs
#[allow(unsafe_code)]
pub(crate) mod type_id {
use std::{any::TypeId, marker::PhantomData};

trait NonStaticAny {
fn get_type_id(&self) -> TypeId
where
Self: 'static;
}

impl<T: ?Sized> NonStaticAny for PhantomData<T> {
fn get_type_id(&self) -> TypeId
where
Self: 'static,
{
TypeId::of::<T>()
}
}

pub fn non_static_type_id<T: ?Sized>() -> TypeId {
let non_static_thing = PhantomData::<T>;
let thing = unsafe {
std::mem::transmute::<&dyn NonStaticAny, &(dyn NonStaticAny + 'static)>(
&non_static_thing,
)
};
NonStaticAny::get_type_id(thing)
}
}
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![doc = include_str!("./docs.md")]
#![forbid(unsafe_code)]
#![deny(unsafe_code)]
#![warn(clippy::all, clippy::unwrap_used, clippy::panic)] // TODO: missing_docs
#![allow(clippy::module_inception)]
#![cfg_attr(docsrs, feature(doc_cfg))]
Expand Down
34 changes: 30 additions & 4 deletions src/type/specta_id.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use std::cmp::Ordering;
use std::{any::TypeId, cmp::Ordering};

use crate::internal::type_id::non_static_type_id;

/// The unique Specta ID for the type.
///
Expand All @@ -10,19 +12,43 @@
/// - `&'a T::SID == &'b T::SID` (unlike std::any::TypeId which forces a static lifetime)
/// - `Box<T> == Arc<T> == Rc<T>` (unlike std::any::TypeId)
///
// TODO: Encode the properties above into unit tests.
#[allow(clippy::derived_hash_with_manual_eq)]
#[derive(Debug, Clone, Copy, Hash)]
pub struct SpectaID {
pub(crate) type_name: &'static str,
pub(crate) hash: u64,
pub(crate) tid: TypeId,
}

impl SpectaID {
// TODO: Unit test this (including with non-static types)
pub fn from<T>() -> Self {
// I am aware `std::any::type_name`'s format is not guaranteed but plz just let me order my types by name without a macro in peace.
let type_name = std::any::type_name::<T>(); // Current output is in the form `some::Type<some::Generic>`

// Strip from `<` to the end of the string
let end_offset = type_name.rfind("<").unwrap_or(type_name.len());

Check warning on line 30 in src/type/specta_id.rs

View workflow job for this annotation

GitHub Actions / clippy

single-character string constant used as pattern

warning: single-character string constant used as pattern --> src/type/specta_id.rs:30:42 | 30 | let end_offset = type_name.rfind("<").unwrap_or(type_name.len()); | ^^^ help: try using a `char` instead: `'<'` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_char_pattern = note: `#[warn(clippy::single_char_pattern)]` implied by `#[warn(clippy::all)]`

// Strip everything before the last `::`
let start_offset = type_name[0..end_offset]
.rfind("::")
// +2 to skip the ::
.map(|v| v + 2)
.unwrap_or(0);

SpectaID {
type_name: &type_name[start_offset..end_offset],
tid: non_static_type_id::<T>(),
}
}
}

// We do custom impls so the order prefers type_name over hash.
impl Ord for SpectaID {
fn cmp(&self, other: &Self) -> Ordering {
self.type_name
.cmp(other.type_name)
.then(self.hash.cmp(&other.hash))
.then(self.tid.cmp(&other.tid))
}
}

Expand All @@ -39,7 +65,7 @@
// We do custom impls so equals is by SID exclusively.
impl PartialEq<Self> for SpectaID {
fn eq(&self, other: &Self) -> bool {
self.hash.eq(&other.hash)
self.tid.eq(&other.tid)
}
}

Expand Down
4 changes: 2 additions & 2 deletions tests/duplicate_ty_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ fn test_duplicate_ty_name() {
#[cfg(not(target_os = "windows"))]
let err = Err(ExportError::DuplicateTypeName(
"One".into(),
impl_location("tests/duplicate_ty_name.rs:19:14"),
impl_location("tests/duplicate_ty_name.rs:9:14"),
impl_location("tests/duplicate_ty_name.rs:19:14"),
));
#[cfg(target_os = "windows")]
let err = Err(ExportError::DuplicateTypeName(
"One".into(),
impl_location("tests\\duplicate_ty_name.rs:19:14"),
impl_location("tests\\duplicate_ty_name.rs:9:14"),
impl_location("tests\\duplicate_ty_name.rs:19:14"),
));

assert_eq!(export::<Demo>(&Default::default()), err);
Expand Down
Loading