ai generated
This commit is contained in:
98
examples/basic_usage.rs
Normal file
98
examples/basic_usage.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
use hash2::Hash2;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::Hasher;
|
||||
|
||||
// Basic struct with derive
|
||||
#[derive(Hash2)]
|
||||
pub struct User {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub age: u8,
|
||||
}
|
||||
|
||||
// Struct with generics
|
||||
#[derive(Hash2)]
|
||||
pub struct Container<T> {
|
||||
pub value: T,
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
// Struct with lifetimes
|
||||
#[derive(Hash2)]
|
||||
pub struct Borrowed<'a> {
|
||||
pub data: &'a str,
|
||||
pub id: u64,
|
||||
}
|
||||
|
||||
// Struct with both generics and lifetimes
|
||||
#[derive(Hash2)]
|
||||
pub struct Complex<'a, T> {
|
||||
pub owned: T,
|
||||
pub borrowed: &'a str,
|
||||
}
|
||||
|
||||
// Example with PhantomData (like the original Test struct)
|
||||
#[derive(Hash2)]
|
||||
pub struct Test<'a> {
|
||||
pub test: f32,
|
||||
pub test2: u64,
|
||||
pub _ignored: std::marker::PhantomData<&'a ()>,
|
||||
}
|
||||
|
||||
// Enum example
|
||||
#[derive(Hash2)]
|
||||
pub enum Status {
|
||||
Active,
|
||||
Inactive,
|
||||
Pending { since: u64 },
|
||||
}
|
||||
|
||||
fn compute_hash<T: Hash2>(value: &T) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
value.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Basic struct
|
||||
let user = User {
|
||||
id: 42,
|
||||
name: "Alice".to_string(),
|
||||
age: 30,
|
||||
};
|
||||
println!("User hash: {}", compute_hash(&user));
|
||||
|
||||
// Generic struct
|
||||
let container = Container {
|
||||
value: 100u32,
|
||||
count: 5,
|
||||
};
|
||||
println!("Container hash: {}", compute_hash(&container));
|
||||
|
||||
// Borrowed struct
|
||||
let text = String::from("Hello");
|
||||
let borrowed = Borrowed {
|
||||
data: &text,
|
||||
id: 1,
|
||||
};
|
||||
println!("Borrowed hash: {}", compute_hash(&borrowed));
|
||||
|
||||
// Complex struct
|
||||
let complex = Complex {
|
||||
owned: vec![1, 2, 3],
|
||||
borrowed: &text,
|
||||
};
|
||||
println!("Complex hash: {}", compute_hash(&complex));
|
||||
|
||||
// Test struct (original example)
|
||||
let test = Test {
|
||||
test: 3.14,
|
||||
test2: 999,
|
||||
_ignored: std::marker::PhantomData,
|
||||
};
|
||||
println!("Test hash: {}", compute_hash(&test));
|
||||
|
||||
// Enum
|
||||
let status = Status::Pending { since: 12345 };
|
||||
println!("Status hash: {}", compute_hash(&status));
|
||||
}
|
||||
Reference in New Issue
Block a user