Skip to content

Commit

Permalink
Merge 931b64e into 13a423f
Browse files Browse the repository at this point in the history
  • Loading branch information
zbraniecki committed Jul 27, 2020
2 parents 13a423f + 931b64e commit 278ee4e
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 1 deletion.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
/target
**/target
**/*.rs.bk
Cargo.lock
11 changes: 11 additions & 0 deletions macros/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "tinystr-macros"
version = "0.1.0"
authors = ["Zibi Braniecki <zibi@braniecki.net>"]
edition = "2018"

[lib]
proc_macro = true

[dependencies]
tinystr = "0.3"
12 changes: 12 additions & 0 deletions macros/examples/ts_example.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use tinystr_macros::*;

fn main() {
let x = tinystr4!("Latn");
println!("{:#?}", x);

let y = tinystr8!("Valencia");
println!("{:#?}", y);

let z = tinystr16!("Very Long Word");
println!("{:#?}", z);
}
42 changes: 42 additions & 0 deletions macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
extern crate proc_macro;

use proc_macro::TokenStream;

fn get_value_from_token_stream(input: TokenStream) -> String {
let val = format!("{}", input);
if !val.starts_with('"') || !val.ends_with('"') {
panic!("Argument must be a string literal.");
}
let len = val.len();
(&val[1..len - 1]).to_string()
}

#[proc_macro]
pub fn tinystr4(input: TokenStream) -> TokenStream {
let val = get_value_from_token_stream(input);
let bytes: u32 = tinystr::TinyStr4::from_bytes(val.as_bytes())
.expect("Failed to construct TinyStr from input")
.into();
let formula = format!("unsafe {{ tinystr::TinyStr4::new_unchecked({}) }}", bytes);
formula.parse().unwrap()
}

#[proc_macro]
pub fn tinystr8(input: TokenStream) -> TokenStream {
let val = get_value_from_token_stream(input);
let bytes: u64 = tinystr::TinyStr8::from_bytes(val.as_bytes())
.expect("Failed to construct TinyStr from input")
.into();
let formula = format!("unsafe {{ tinystr::TinyStr8::new_unchecked({}) }}", bytes);
formula.parse().unwrap()
}

#[proc_macro]
pub fn tinystr16(input: TokenStream) -> TokenStream {
let val = get_value_from_token_stream(input);
let bytes: u128 = tinystr::TinyStr16::from_bytes(val.as_bytes())
.expect("Failed to construct TinyStr from input")
.into();
let formula = format!("unsafe {{ tinystr::TinyStr16::new_unchecked({}) }}", bytes);
formula.parse().unwrap()
}

0 comments on commit 278ee4e

Please sign in to comment.