T: 32 or 64 bit Unifying Generic Type

Just checking if this is the most reasonable way to go about this (or if there might be a crate available?):

pub struct B32 {}
pub struct B64 {}

pub trait AlignedTypes {
    type Float;
    type Int;
    type UInt;
}

impl AlignedTypes for B32 {
    type Float = f32;
    type Int = i32;
    type UInt = i32;
}

impl AlignedTypes for B64 {
    type Float = f64;
    type Int = i64;
    type UInt = i64;
}

Thus allowing a fully aligned struct of all the same size primitive types with one generic type:

pub struct Example<T: AlignedTypes> {
    a_float: T::Float,
    an_integer: T::Int,
    an_unsigned_int: T::UInt,
    or_whatever: T::Float,
    but_all_aligned: T::Float,
}

I would be curious to know if there is any other solution as well because I have almost the exact same code in a project of mine

Right? Kind of analogous to usize/isize... but fstruct/ustruct/istruct instead...

Also, only tangentially related, but has anyone made a crate explicitly naming the PhantomData variance / drop check / Sync + Send specific implementations? And are there others I've missed?

use ::std::marker::PhantomData;
use ::std::cell::Cell;

/// The standard covariant form of PhantomData for a type T. This will call drop check of T.
pub type DropCheckPhantom<T> = PhantomData<T>;

/// An alternate covariant form of PhantomData for a type T. Does not call the drop check of T.
pub type NonDropPhantom<T> = PhantomData<fn() -> T>;

/// PhantomData for a type T that is contravariant over T.
pub type ContravariantPhantom<T> = PhantomData<fn(T)>;

/// PhantomData for a type T that is invariant over T.
pub type InvariantPhantom<T> = PhantomData<fn(T) -> T>;

/// PhantomData which will enforce that a struct containing it is not Sync.
pub type PhantomNotSync = PhantomData<Cell<u8>>;

/// PhantomData which will enforce that a struct containing it is neither Sync nor Send.
pub type PhantomNoSyncNoSend = PhantomData<&'static Cell<u8>>;

I guess I'm wondering if there's a "not in std but would be nice" crate?

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.