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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// Copyright 2016 schroedinger_box developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate rand;

use std::cell::UnsafeCell;
use std::mem::{replace, transmute};
use rand::{thread_rng, Rng};
use std::fmt;
use std::default::Default;
use std::hash::{Hash, Hasher};
use std::ops::{Deref, DerefMut};
use std::cmp::Ordering;

/// A box that contains many values, but collapses into one when opened (read from) for the first
/// time.
///
/// # Example
///
/// ```rust
/// # use schroedinger_box::SchroedingerBox;
/// let cat_is_alive = SchroedingerBox::new(vec![true, false]);
/// // Here the cat is both dead and alive, but when we observe it...
/// let state = *cat_is_alive;
/// // ...it collapses into one of the possible states with equal probability.
/// assert_eq!(state, *cat_is_alive);
/// ```
// This should be called `SchrödingerBox`, but until type aliases can have static methods called on
// them (rust-lang/rust#11047) I’ll take pity on those barbarians who can’t type umlauts easily.
pub struct SchroedingerBox<Cat> {
    _inner: UnsafeCell<Vec<(u64, Cat)>>,
}

impl<Cat> SchroedingerBox<Cat> {
    /// Creates a new `SchroedingerBox` from a set of states.
    ///
    /// When the box is first opened, the contents’ superposition will collapse into one of the
    /// given states with equal probability.
    ///
    /// # Panic
    ///
    /// Panics if `states.len() == 0`.
    pub fn new(states: Vec<Cat>) -> SchroedingerBox<Cat> {
        SchroedingerBox::from_probabilities(states.into_iter().map(|x| (1, x)).collect())
    }

    /// Creates a new `SchroedingerBox` from a set of states, each with a probability.
    ///
    /// When the box is first opened, the contents’ superposition will collapse into one of the
    /// given states with each state’s probability determined by the probabilities given.
    ///
    /// The probablity for a state is represented by a ratio of an integer to the total sum of the
    /// probabilities; e.g., a set of states and probabilities `[(1, true), (5, false)]` would be
    /// `false` five sixths of the time and `true` one sixth of the time.
    ///
    /// # Panic
    ///
    /// Panics if `states.len() == 0`.
    // Here we *could* choose the `Collapsed` state instantly, avoiding all the trouble with
    // `UnsafeCell` and so on. But that would be boring and against the point, so we make sure that
    // the state collapses only on the first observation.
    pub fn from_probabilities(states: Vec<(u64, Cat)>) -> SchroedingerBox<Cat> {
        assert!(states.len() > 0);
        SchroedingerBox {
            _inner: UnsafeCell::new(states),
        }
    }

    /// This function is unsafe because it does lots of unsafe stuff that’s probably able to cause
    /// bad things to happen.
    unsafe fn collapse(&self) {
        // Using `UnsafeCell` is quite messy, so I hope I’ve got this bit right.
        let vec = &mut *self._inner.get();
        if vec.len() == 1 {
            return
        }
        let mut idx = {
            let len = vec.iter().map(|&(f, _)| f).fold(0, |a, b| a + b);
            thread_rng().gen_range(0, len)
        } + 1; // For some reason, we need to add 1 to idx

        let v = replace(vec, vec![]);
        let (_, val) =
            v.into_iter().skip_while(|&(f, _)| {
                idx = idx.saturating_sub(f);
                idx != 0
            }).next().unwrap();
        *vec = vec![(1, val)];
    }

    /// Moves the value inside a `SchroedingerBox` out, consuming the box and collapsing any
    /// superposition into a definite state if needed.
    pub fn into_inner(self) -> Cat {
        unsafe { self.collapse(); }
        let vec = unsafe { &mut *self._inner.get() };
        let v = replace(&mut *vec, vec![]);
        debug_assert_eq!(v.len(), 1);
        v.into_iter().next().unwrap().1
    }
}

impl<Cat> Deref for SchroedingerBox<Cat> {
    type Target = Cat;

    /// Obtains a reference to the value inside a `SchroedingerBox`, collapsing any superposition
    /// into a definite state if needed.
    fn deref(&self) -> &Cat {
        unsafe {
            self.collapse();
            transmute::<&Cat, &Cat>(&(*self._inner.get())[0].1)
        }
    }
}

impl<Cat> DerefMut for SchroedingerBox<Cat> {
    /// Obtains a mutable reference to the value inside a `SchroedingerBox`, collapsing any
    /// superposition into a definite state if needed.
    fn deref_mut(&mut self) -> &mut Cat {
        unsafe {
            self.collapse();
            transmute::<&mut Cat, &mut Cat>(&mut (*self._inner.get())[0].1)
        }
    }
}

impl<Cat> fmt::Debug for SchroedingerBox<Cat>
        where Cat: fmt::Debug {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        (**self).fmt(f)
    }
}

impl<Cat> fmt::Display for SchroedingerBox<Cat>
        where Cat: fmt::Display {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        (**self).fmt(f)
    }
}

impl<Cat> PartialEq for SchroedingerBox<Cat>
        where Cat: PartialEq {
    fn eq(&self, other: &SchroedingerBox<Cat>) -> bool {
        **self == **other
    }
}

impl<Cat> Eq for SchroedingerBox<Cat> where Cat: Eq {}

impl<Cat> PartialOrd for SchroedingerBox<Cat>
        where Cat: PartialOrd {
    fn partial_cmp(&self, other: &SchroedingerBox<Cat>) -> Option<Ordering> {
        (**self).partial_cmp(&**other)
    }
}

impl<Cat> Ord for SchroedingerBox<Cat> where Cat: Ord {
    fn cmp(&self, other: &SchroedingerBox<Cat>) -> Ordering {
        (**self).cmp(&**other)
    }
}

impl<Cat> Default for SchroedingerBox<Cat>
        where Cat: Default {
    fn default() -> SchroedingerBox<Cat> {
        SchroedingerBox::new(vec![Default::default()])
    }
}

impl<Cat> Clone for SchroedingerBox<Cat>
        where Cat: Clone {
    /// Clones a `SchroedingerBox`.
    ///
    /// This collapses any superposition into a single state.
    fn clone(&self) -> SchroedingerBox<Cat> {
        SchroedingerBox::new(vec![(**self).clone()])
    }
}

impl<Cat> Hash for SchroedingerBox<Cat>
        where Cat: Hash {
    fn hash<H>(&self, hasher: &mut H) where H: Hasher {
        (**self).hash(hasher)
    }
}

#[cfg(test)]
mod tests {
    use super::SchroedingerBox;

    #[test]
    fn whats_in_the_box() {
        // This is basically imposible to test, but we try anyway.
        // I think I’m beginning to understand how quantum physicists feel. :(

        // Set up a `SchroedingerBox` with one very unlikely value
        let foo = SchroedingerBox::from_probabilities(
            vec![(100000, 1), (500000, 2), (500000, 3), (1, 4)]);
        let val = *foo;
        match val {
            1 | 2 | 3 => {},
            // There’s a million to one chance, but it might not work
            4 => {
                panic!("an unlikely event occurred; this is probably a bug, \
                        but there’s a chance it isn’t");
            },
            // If this happens, our code is really broken
            _ => panic!(),
        }
    }

    #[test]
    fn collapsing_state_does_not_change() {
        let foo = SchroedingerBox::new(vec![1, 2, 3]);
        let val = *foo;
        for _ in 0u8..100 {
            assert_eq!(*foo, val);
        }
    }

    #[test]
    fn test_into_inner() {
        let foo = SchroedingerBox::new(vec![1, 2, 3]);
        let val = *foo;
        let own = foo.into_inner();
        assert_eq!(own, val);
    }
}