use lfrlock::LfrLock;
#[derive(Debug, Clone, PartialEq)]
struct Data {
value: i32,
}
#[test]
fn test_write_guard() {
let lock = LfrLock::new(Data { value: 0 });
for i in 1..=10 {
{
let mut write_guard = lock.write();
write_guard.value += 1; }
let data = lock.read();
assert_eq!(data.value, i);
}
let data = lock.read();
assert_eq!(data.value, 10);
}
#[test]
fn test_try_write() {
let lock = LfrLock::new(Data { value: 0 });
{
let guard = lock.try_write();
assert!(guard.is_some());
let mut guard = guard.unwrap();
guard.value = 42;
}
assert_eq!(lock.read().value, 42);
}
#[test]
fn test_update_and_fetch() {
let lock = LfrLock::new(Data { value: 0 });
let new_guard = lock.update_and_fetch(|old| Data {
value: old.value + 10,
});
assert_eq!(new_guard.value, 10);
let new_guard = lock.update_and_fetch(|old| Data {
value: old.value * 2,
});
assert_eq!(new_guard.value, 20);
}
#[test]
fn test_fetch_and_update() {
let lock = LfrLock::new(Data { value: 100 });
let old_guard = lock.fetch_and_update(|old| Data {
value: old.value + 50,
});
assert_eq!(old_guard.value, 100); assert_eq!(lock.read().value, 150);
let old_guard = lock.fetch_and_update(|old| Data {
value: old.value * 2,
});
assert_eq!(old_guard.value, 150); assert_eq!(lock.read().value, 300); }
#[test]
fn test_chained_operations() {
let lock = LfrLock::new(Data { value: 1 });
lock.update(|d| Data { value: d.value + 1 }); lock.update(|d| Data { value: d.value * 3 }); lock.update(|d| Data { value: d.value - 1 });
assert_eq!(lock.get().value, 5);
let squared = lock.map(|d| d.value * d.value);
assert_eq!(squared, 25);
assert_eq!(lock.get().value, 5); }