tinystr_macros/
lib.rs

1//! `tinystr-macros` exports proc macros to convert byte strings to raw TinyStr data.
2//!
3//! Not intended for public consumption; use `tinystr` instead.
4
5extern crate proc_macro;
6
7// use proc_macro::bridge::client::Literal as BridgeLiteral;
8use proc_macro::{Literal, TokenStream, TokenTree};
9
10fn get_value_from_token_stream(input: TokenStream) -> String {
11    let val = input.to_string();
12    if !val.starts_with('"') && !val.ends_with('"') {
13        panic!("Expected a string literal; found {:?}", input);
14    }
15    (&val[1..val.len() - 1]).to_string()
16}
17
18#[proc_macro]
19pub fn u32_from_bytes(input: TokenStream) -> TokenStream {
20    let s = get_value_from_token_stream(input);
21    let u = tinystr_raw::try_u32_from_bytes(s.as_bytes())
22        .expect(&s);
23    TokenTree::from(Literal::u32_suffixed(u.into())).into()
24}
25
26#[proc_macro]
27pub fn u64_from_bytes(input: TokenStream) -> TokenStream {
28    let s = get_value_from_token_stream(input);
29    let u = tinystr_raw::try_u64_from_bytes(s.as_bytes())
30        .expect("Failed to construct TinyStr from input");
31    TokenTree::from(Literal::u64_suffixed(u.into())).into()
32}
33
34#[proc_macro]
35pub fn u128_from_bytes(input: TokenStream) -> TokenStream {
36    let s = get_value_from_token_stream(input);
37    let u = tinystr_raw::try_u128_from_bytes(s.as_bytes())
38        .expect("Failed to construct TinyStr from input");
39    TokenTree::from(Literal::u128_suffixed(u.into())).into()
40}