Skip to content

Commit

Permalink
Re-adding ui_id
Browse files Browse the repository at this point in the history
  • Loading branch information
bwoods committed Nov 17, 2024
1 parent 8ca0720 commit 47e105e
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
4 changes: 4 additions & 0 deletions composable-views/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ lyon = "1.0.1"
usvg = "0.44.0"
svg = "0.18.0"

[dependencies.ui_id]
path = "src/ui_id"
optional = true


[dev-dependencies]
futures.workspace = true
Expand Down
18 changes: 18 additions & 0 deletions composable-views/src/ui_id/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "ui_id"
version = "0.4.1"
authors = ["Bryan Woods"]
edition = "2021"

[lib]
proc-macro = true


[dependencies]
syn = "2.0"
quote = "1.0"
fastrand = "2.2"


[dev-dependencies]
itertools = "0.13.0"
47 changes: 47 additions & 0 deletions composable-views/src/ui_id/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#![allow(clippy::unreadable_literal)]

use quote::quote;
use syn::parse::Parser;

#[proc_macro]
/// Produces a unique id (at compile-time) for every call-site in the source code
/// ```
/// let a = ui_id::ui_id!();
/// let b = ui_id::ui_id!();
/// assert_ne!(a, b);
/// ```
///
/// More complex cases are handled by passing in optional runtime values to distinguish ids that are logically different but produced by the same location in the source code. Loops, for example, can be handled by passing in the loop index.
/// ```
/// use itertools::Itertools;
/// (0..1000)
/// .map(|n| { return ui_id::ui_id!(n) })
/// .collect::<std::vec::Vec<_>>()
/// .into_iter()
/// .combinations(2)
/// .into_iter()
/// .for_each(|pair| assert_ne!(pair[0], pair[1]));
/// ```
pub fn ui_id(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
let bytes = fastrand::u128(..);

let exprs = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_terminated
.parse(tokens)
.expect("ui_id arguments could not be parsed.")
.into_iter();

let tokens = quote! {
{
let mut hash = #bytes;

// If runtime parameters where passed into the macro, perform a 128-bit FNV-1a
// mix-step to combine them with the current `ui_id` to generate a new one.
let prime = 0x0000000001000000000000000000013Bu128;
#( hash = (hash ^ ((#exprs) as u128)).wrapping_mul(prime); )*

unsafe { std::num::NonZeroU128::new_unchecked(hash ^ 0x1u128) }
}
};

tokens.into()
}

0 comments on commit 47e105e

Please sign in to comment.