data_tracker 0.1.0

tracks changes to data and notifies listeners

Crate data_tracker [] [src]

Track changes to data and notify listeners.

The main API feature is the DataTracker struct, which takes ownership of a value.

The principle of operation is that DataTracker::as_tracked_mut() returns a mutable Modifier. Modifier has two key properties:

  • It implements the DerefMut trait and allows ergonomic access to the underlying data.
  • It implements the Drop trait which checks if the underlying data was changed and, if so, notifies the listeners.

Futhermore, DataTracker::as_ref() returns a (non-mutable) reference to the data for cases when only read-only access to the data is needed.

To implement tracking, when Modifier is created, a copy of the original data is made and when Modifier is dropped, an equality check is performed. If the original and the new data are not equal, the callbacks are called with references to the old and the new values.

use data_tracker::DataTracker;

// Create a new type to be tracked. Must implement Clone and PartialEq.
#[derive(Debug, Clone, PartialEq)]
struct MyData {
    a: u8,

// Create some data.
let data = MyData {a: 1};

// Transfer ownership of data to the tracker.
let mut tracked_data = DataTracker::new(data);

// Register a listener which is called when a data change is noticed.
let key = 0; // Keep the key to remove the callback later.

// At the time or writing, the rust compiler could not infer the type
// of the closure and therefore I needed to annotate the argument types.
tracked_data.add_listener(key, Box::new(|old_value: &MyData, new_value: &MyData| {
    println!("changed {:?} -> {:?}", old_value, new_value);

    // Create x, a (non-mutable) reference to original data.
    let x = tracked_data.as_ref();
    println!("x.a: {}",x.a);

    // Create x, which allows modifying the original data and checks for changes when
    // it goes out of scope.
    let mut x = tracked_data.as_tracked_mut();
    x.a = 10;
    println!("x.a: {}",x.a);
    // When we leave this scope, changes are detected and sent to the listeners.

// Remove our callback.



Tracks changes to data and notifies listeners.


Allow viewing and modifying data owned by DataTracker.



Trait defining change notification callback function.