1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
//! This crate provide type for counting mutable borrow of a value. The `Bc<T>`
//! type is a small wrapper on top of a value of type `T` which count the number
//! of time the value has been mutably borrowed since it's creation.
//!
//! # Why?
//!
//! If you want to cache an expensive computation result, you need to have
//! information about wether the parameters of the computation have changed or
//! not. You can use a hash for that, but this have two shortcomings:
//!
//!  * You need to have values which implement the `Hash` trait. Some useful
//!    types like `f64` do not;
//!  * You need to have a cheap way to compute the hash.
//!
//! If computing the hash is harder or more expensive than doing the
//! computation, you are doomed. Or you can use `Bc<T>` which will give you
//! information about the number of borrow since the last computation. If this
//! number have changed, then it is very likely that the value have changed,
//! and that you need to redo your computation.
//!
//! # Limitations
//!
//! This can not be used a real hash algorithm, because the number of borrow can
//! change even if the value do not.
//!
//! If more than `usize::MAX` borrow occurs, the borrow counter will be wrapped
//! around to 0, and will not `panic` because of the overflow.
//!
//! # Performances
//!
//! The `Bc` type do not introduce notable overhead when borrowing. Here are the
//! benchmark results comparing a raw value and a borrow counted value:
//!
//! ```text
//! running 2 tests
//!    test counted ... bench:       1,061 ns/iter (+/- 12)
//!    test raw     ... bench:       1,059 ns/iter (+/- 16)
//! ```
//!
//! Using the number of borrow as hash value is way faster than doing the real
//! hash. Here is a benchmark for `[usize; 10000]` values:
//!
//! ```text
//! running 2 tests
//!    test counted ... bench:          22 ns/iter (+/- 1)
//!    test raw     ... bench:      49,011 ns/iter (+/- 755)
//! ```
//!
//! You can see the code for these benchmarks on [Github](https://github.com/Luthaf/bcount/tree/master/benches).
//!
//! # Example
//!
//! ```rust
//! extern crate bcount;
//! use bcount::Bc;
//!
//! fn main() {
//!     let mut a = Bc::new(vec![63, 67, 42]);
//!     assert_eq!(a.count(), 0);
//!
//!     do_work(&mut a);
//!     do_work(&mut a);
//!     do_work(&mut a);
//!     do_work(&mut a);
//!
//!     assert_eq!(a.count(), 4);
//!
//!     *a = vec![3, 4, 5];
//!     assert_eq!(a.count(), 5);
//! }
//!
//! fn do_work(_: &mut [usize]) {
//!     // Whatever, nobody cares
//! }
//!
//! ```

// TODO? Mbc (Mutable Borrow counter) & Cbc (*const* borrow counter) & Bc (*all* borrow counter)

#![deny(missing_docs)]
use std::ops::{Deref, DerefMut};

/// The borrow counter struct for type `T`.
pub struct Bc<T> {
    counter: usize,
    val: T
}

impl<T> Bc<T> {
    /// Create a new `Bc<T>` containing the value `val`.
    pub fn new(val: T) -> Bc<T> {
        Bc {
            val: val,
            counter: 0,
        }
    }

    /// Reset the borrow counter
    pub fn reset(&mut self) {
        self.counter = 0;
    }

    /// Get the number of time this structure has been mutably borrowed.
    pub fn count(&self) -> usize {
        self.counter
    }
}

impl<T> Deref for Bc<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.val
    }
}

impl<T> DerefMut for Bc<T> {
     fn deref_mut(&mut self) -> &mut T {
         self.counter = self.counter.wrapping_add(1);
         &mut self.val
     }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::usize;

    fn do_nothing(_: &mut f64) {}

    #[test]
    fn count() {
        let mut a = Bc::new(5.0);
        assert_eq!(a.count(), 0);

        *a = 89.0;
        assert_eq!(a.count(), 1);

        do_nothing(&mut a);
        assert_eq!(a.count(), 2);
    }

    #[test]
    fn reset() {
        let mut a = Bc::new(3);

        assert_eq!(a.count(), 0);

        *a = 18;
        *a = 42;
        assert_eq!(a.count(), 2);

        a.reset();
        assert_eq!(a.count(), 0);
    }

    #[test]
    fn overflow() {
        let mut a = Bc::new(3);
        a.counter = usize::MAX - 1;

        *a = 18;
        *a = 18;
        assert_eq!(a.count(), 0);
    }

    #[test]
    fn non_mutable() {
        fn observe(_: &f64) {/* Do nothing */}

        let a = Bc::new(3.0);
        assert_eq!(a.count(), 0);

        observe(&a);
        observe(&a);
        observe(&a);
        assert_eq!(a.count(), 0);
    }
}