Skip to main content

TStr

Struct TStr 

Source
pub struct TStr<S>(/* private fields */);
Expand description

A type-level string type, emulates a &'static str const parameter.

This type is zero-sized and has an alignment of 1.

§Examples

§Emulating named parameters

This example demonstrates how you can use TStr to emulate functions with named parameters overloaded by the name of the parameters.

use tstr::{IsTStr, TS, TStr, ts};

use std::{collections::HashMap, hash::RandomState};

{
    // equivalent to HashMap::new
    let mut map = HashMap::make(args!());
    assert!(map.capacity() == 0);
    map.insert(0, "");;
}
{
    // equivalent to HashMap::with_capacity
    let mut map = HashMap::make(args!(capacity: 10));
    assert!(map.capacity() >= 10);
    map.insert(0, "");;
}
{
    // equivalent to HashMap::with_hasher
    let mut map = HashMap::make(args!(hasher: RandomState::new()));
    assert!(map.capacity() == 0);
    map.insert(0, "");;
}
{
    // equivalent to HashMap::with_capacity_and_hasher
    let mut map = HashMap::make(args!(capacity: 10, hasher: RandomState::new()));
    assert!(map.capacity() >= 10);
    map.insert(0, "");;
}

/// The struct that encodes a named parameter by taking two arguments:
//  - a `TStr` that encodes the name at the type level
/// - the type of the argument.
///
/// The parameter list as a whole is a tuple of this struct.
#[repr(transparent)]
pub struct NamedParameter<N: IsTStr, T> {
    // since TStr is zero-sized, it can be put alongside the non-zero-sized
    // wrapped value in a `#[repr(transparent)]` type.
    name: TStr<N::Arg>,
    pub value: T,
}

impl<N, T> NamedParameter<N, T>
where
    N: IsTStr
{
    pub const fn new(name: N, value: T) -> Self {
        Self {
            // `TStr::from_gen` is needed for constructing a `TStr` from a
            // generic `IsTStr` type
            name: TStr::from_gen(name),
            value,
        }
    }
}

/// Custom trait for constructors.
trait Make<Args>: Sized {
    fn make(args: Args) -> Self;
}

// make constructor with no parameters
impl<K, V> Make<args_ty!()> for HashMap<K, V> {
    fn make(args_pat!{}: args_ty!()) -> Self {
        HashMap::new()
    }
}

// make constructor with a capacity parameter
impl<K, V> Make<args_ty!(capacity: usize)> for HashMap<K, V> {
    fn make(args_pat!{capacity}: args_ty!(capacity: usize)) -> Self {
        HashMap::with_capacity(capacity)
    }
}

// make constructor with a hasher parameter
impl<K, V, S> Make<args_ty!(hasher: S)> for HashMap<K, V, S> {
    fn make(args_pat!{hasher}: args_ty!(hasher: S)) -> Self {
        HashMap::with_hasher(hasher)
    }
}

// make constructor with capacity and hasher parameters
impl<K, V, S> Make<args_ty!(capacity: usize, hasher: S)> for HashMap<K, V, S> {
    fn make(args_pat!{capacity, hasher}: args_ty!(capacity: usize, hasher: S)) -> Self {
        HashMap::with_capacity_and_hasher(capacity, hasher)
    }
}

macro_rules! args {
    ($($name:ident: $val:expr),* $(,)?) => (
        ($(NamedParameter::new(ts!($name), $val),)*)
    )
} use args;

macro_rules! args_ty {
    ($($name:ident: $field_ty:ty),* $(,)?) => (
        ($(NamedParameter<TS!($name), $field_ty>,)*)
    )
} use args_ty;

macro_rules! args_pat {
    ($($name:ident),* $(,)?) => (
        ($( NamedParameter::<TS!($name), _> { value: $name, .. }, )*)
    )
} use args_pat;

§Parsing integers

Parsing integers from TStrs, since the primitive integers all have const fn from_str_radix functions, parsing them doesn’t require direct support from TStr itself.

(this example requires the "const_panic" feature because it uses tstr::unwrap)

use tstr::ts;

// parses the number at compile-time!
const NUMBER: u32 = tstr::unwrap!(u32::from_str_radix(tstr::to_str(ts!(1234)), 10));

assert_eq!(NUMBER, 1234u32);

§Serde

TStr implements serde::{Serialize, Deserialize} when the "serde" feature is enabled.

use tstr::{TS, ts};

assert_eq!(serde_json::from_str::<TS!(foo)>(r#""foo""#).unwrap(), ts!(foo));

// trying to deserialize a `TS!(foo)` from any value other than `"foo"` produces an error
assert!(serde_json::from_str::<TS!(foo)>(r#""bar""#).is_err());


assert_eq!(serde_json::to_string(&ts!(wtf)).unwrap(), r#""wtf""#);

assert_eq!(serde_json::to_string(&ts!("hello")).unwrap(), r#""hello""#);

assert_eq!(serde_json::to_string(&ts!(12345)).unwrap(), r#""12345""#);

Implementations§

Source§

impl<S> TStr<S>

Source

pub const fn new() -> Self

Constructs the TStr.

Source§

impl<S: TStrArg> TStr<S>

Source

pub const fn from_gen<G>(tstr: G) -> Self
where G: IsTStr<Arg = S>,

Coerces an impl IsTStr into a TStr, only necessary in generic contexts

The trait method equivalent of this const function is IsTStr::to_tstr.

While it’s always possible to construct a TStr through its new constructor, this method ensures that it’s the same string as the argument.

§Example
use tstr::{IsTStr, TStr};

#[repr(transparent)]
struct Foo<T, N: IsTStr> {
    val: T,
    // since TStr is zero-sized, it can be put in `#[repr(transparent)]` types
    // next to the wrapped non-Zero-Sized-Type.
    name: TStr<N::Arg>,
}

impl<T, N: IsTStr> Foo<T, N> {
    pub fn new(val: T, tstr: N) -> Self {
        Self{ val, name: TStr::from_gen(tstr) }
    }
}
Source

pub const fn to_gen<G>(self) -> G
where G: IsTStr<Arg = S>,

Coerces a TStr into an impl IsTStr, only necessary in generic contexts

While it’s always possible to construct an IsTStr through its VAL associated constant, this method ensures that it’s the same string as Self.

§Example
use tstr::{IsTStr, TStr};

#[repr(transparent)]
struct Foo<T, N: IsTStr> {
    val: T,
    // since TStr is zero-sized, it can be put in `#[repr(transparent)]` types
    // next to the wrapped non-Zero-Sized-Type.
    name: TStr<N::Arg>,
}

impl<T, N: IsTStr> Foo<T, N> {
    const fn name(&self) -> N {
        self.name.to_gen()
    }
}
Source§

impl<S> TStr<S>

Source

pub const fn to_panicval(&self, fmtarg: FmtArg) -> PanicVal<'static>
where S: TStrArg,

Available on crate feature const_panic only.

const_panic-based-formatting of TStr

Source

pub const fn to_panicvals(&self, fmtarg: FmtArg) -> [PanicVal<'static>; 1]
where S: TStrArg,

Available on crate feature const_panic only.

const_panic-based-formatting of TStr

Trait Implementations§

Source§

impl<S> Clone for TStr<S>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<S> Debug for TStr<S>
where S: TStrArg,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<S> Default for TStr<S>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de, SA: TStrArg> Deserialize<'de> for TStr<SA>

Available on crate feature serde only.
Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<S> Display for TStr<S>
where S: TStrArg,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<S> Hash for TStr<S>
where S: TStrArg,

Source§

fn hash<H>(&self, _state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<S> IsTStr for TStr<S>
where S: TStrArg,

Source§

const VAL: Self

Constructs this IsTStr
Source§

const LENGTH: usize = S::__LENGTH

The length of this string when encoded to utf8
Source§

const BYTES: &[u8] = S::__BYTES

This string converted to a uf8-encoded byte slice
Source§

const STR: &str = S::__STR

This type-level string converted to a string
Source§

type Arg = S

The type parameter of TStr
Source§

fn to_tstr(self) -> TStr<Self::Arg>

Coerces Self to TStr<Self::Arg>, only necessary in generic contexts Read more
Source§

fn from_tstr(tstr: TStr<Self::Arg>) -> Self

Coerces a TStr into Self, only necessary in generic contexts. Read more
Source§

fn len(self) -> usize

Gets the length of the string in utf8 Read more
Source§

fn to_str(self) -> &'static str

Gets the &'static str equivalent of this TStr Read more
Source§

fn to_bytes(self) -> &'static [u8]

Gets the &'static [u8] equivalent of this TStr Read more
Source§

fn tstr_eq<Rhs: IsTStr>(self, rhs: Rhs) -> bool

Compares two TStrs for equality Read more
Source§

fn tstr_ne<Rhs: IsTStr>(self, rhs: Rhs) -> bool

Compares two TStrs for inequality Read more
Source§

fn tstr_cmp<Rhs: IsTStr>(self, rhs: Rhs) -> Ordering

Compares two TStrs for ordering Read more
Source§

fn type_eq<Rhs: IsTStr>(self, rhs: Rhs) -> TypeCmp<Self, Rhs>

Compares two TStrs for equality, returning a proof of (in)equality of Self and Rhs Read more
Source§

impl<S> Ord for TStr<S>
where S: TStrArg,

Source§

fn cmp(&self, _other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<S> PanicFmt for TStr<S>
where S: TStrArg,

Available on crate feature const_panic only.
Source§

const PV_COUNT: usize = 1

The length of the array returned in Self::to_panicvals (an inherent method that formats the type for panic messages).
Source§

type This = TStr<S>

The type after dereferencing all references. Read more
Source§

type Kind = IsCustomType

Whether this is a user-defined type or standard library type. Read more
Source§

const PROOF: IsPanicFmt<Self, Self::This, Self::Kind> = IsPanicFmt::NEW

A marker type that proves that Self implements PanicFmt. Read more
Source§

impl<S> PartialEq<&&str> for TStr<S>
where S: TStrArg,

Source§

fn eq(&self, other: &&&str) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<S> PartialEq<&str> for TStr<S>
where S: TStrArg,

Source§

fn eq(&self, other: &&str) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<S, S2> PartialEq<S2> for TStr<S>
where S: TStrArg, S2: ?Sized + StrLike,

Source§

fn eq(&self, other: &S2) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<S2> PartialEq<TStr<S2>> for &&str
where S2: TStrArg,

Source§

fn eq(&self, other: &TStr<S2>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<S2> PartialEq<TStr<S2>> for &str
where S2: TStrArg,

Source§

fn eq(&self, other: &TStr<S2>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<S2> PartialEq<TStr<S2>> for str
where S2: TStrArg,

Source§

fn eq(&self, other: &TStr<S2>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<S> PartialOrd<&&str> for TStr<S>
where S: TStrArg,

Source§

fn partial_cmp(&self, other: &&&str) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<S> PartialOrd<&str> for TStr<S>
where S: TStrArg,

Source§

fn partial_cmp(&self, other: &&str) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<S, S2> PartialOrd<S2> for TStr<S>
where S: TStrArg, S2: ?Sized + StrLike,

Source§

fn partial_cmp(&self, other: &S2) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<S2> PartialOrd<TStr<S2>> for &&str
where S2: TStrArg,

Source§

fn partial_cmp(&self, other: &TStr<S2>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<S2> PartialOrd<TStr<S2>> for &str
where S2: TStrArg,

Source§

fn partial_cmp(&self, other: &TStr<S2>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<S2> PartialOrd<TStr<S2>> for str
where S2: TStrArg,

Source§

fn partial_cmp(&self, other: &TStr<S2>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<SA: TStrArg> Serialize for TStr<SA>

Available on crate feature serde only.
Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<S> Copy for TStr<S>

Source§

impl<S> Eq for TStr<S>
where S: TStrArg,

Auto Trait Implementations§

§

impl<S> Freeze for TStr<S>

§

impl<S> RefUnwindSafe for TStr<S>

§

impl<S> Send for TStr<S>

§

impl<S> Sync for TStr<S>

§

impl<S> Unpin for TStr<S>

§

impl<S> UnsafeUnpin for TStr<S>

§

impl<S> UnwindSafe for TStr<S>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<S> StrLike for S
where S: IsTStr,

Source§

fn as_str(&self) -> &str

Converts self into a &str Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,