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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
//! A module containing a self referencing struct with a generic `parent` and a mutable [`Holder<T>`] `child` which can reference the `parent`.
//!
//! For examples and further explanation, visit [`SelfRefHolder<T,U>`].
//! [`Holder<T>`]: ../../crow_util/holder/struct.Holder.html
//! [`SelfRefHolder<T,U>`]: ../../crow_util/self_ref/struct.SelfRefHolder.html

use holder::*;
use std::cell::UnsafeCell;

/// A struct consisting of both a [`Holder<T>`] and a `parent` which can be referenced by the holder.
///
/// There are still **many problems** with the struct, those will be fixed in case they end up being relevant
/// during the development of the [`crow_engine`].
///
/// To prevent undefined behavior the `parent` **must not** be mutated during the lifetime of this struct!
///
/// [`insert()`] uses a raw pointer to `parent` to circumvent problems with lifetimes. Do not cast this pointer into a mutable reference
/// or create a reference which is both lasting longer than the closure and is not the return value of said closure, this is causing undefined behavior!
///
/// ```
/// struct Foo {
///     field: String
/// }
///
/// impl Foo {
///     fn boo(&self,start: usize) -> Boo {
///         Boo {
///             field: &self.field[start..],
///         }
///     }
/// }
///
/// struct Boo<'a> {
///     field: &'a str,
/// }
/// ```
///
/// # Examples
///
/// ```
/// use crow_util::self_ref;
///
/// # struct Foo {
/// #     field: String
/// # }
/// #
/// # impl Foo {
/// #     fn boo(&self,start: usize) -> Boo {
/// #         Boo {
/// #             field: &self.field[start..],
/// #         }
/// #     }
/// # }
/// #
/// # struct Boo<'a> {
/// #     field: &'a str,
/// # }
/// let self_ref_holder = self_ref::SelfRefHolder::new(Foo { field: "Hi, I am Foo!".to_string()});
///
/// self_ref_holder.insert("a", |foo| unsafe { &*foo }.boo(4));
///
/// assert_eq!(self_ref_holder.get("a").unwrap().field,"I am Foo!");
/// ```
///
/// [`Holder<T>`]: ../../crow_util/holder/struct.Holder.html
/// [`SelfRefHolder<T,U>`]: ../../crow_util/self_ref/struct.SelfRefHolder.html
/// [`insert()`]:../../crow_util/self_ref/struct.SelfRefHolder.html#method.insert
/// [`crow_engine`]:https://crates.io/crates/crow_engine
pub struct SelfRefHolder<T,U> {
    parent: UnsafeCell<T>,
    child: Holder<U>,
}

impl<T,U> SelfRefHolder<T,U> {
    /// Constructs a new `SelfRefHolder<T,U>` with an empty `Holder<T>` `child`.
    ///
    /// After this calling this method it is not possible to mutate `parent`!
    ///
    /// # Examples
    ///
    /// ```
    /// use crow_util::self_ref;
    ///
    /// # struct Foo {
    /// #     field: String
    /// # }
    /// #
    /// # impl Foo {
    /// #     fn boo(&self,start: usize) -> Boo {
    /// #         Boo {
    /// #             field: &self.field[start..],
    /// #         }
    /// #     }
    /// # }
    /// #
    /// # struct Boo<'a> {
    /// #     field: &'a str,
    /// # }
    /// let foo = Foo { field: "Hi, I am Foo!".to_string()};
    ///
    /// let self_ref_holder = self_ref::SelfRefHolder::new(foo);
    /// # self_ref_holder.insert("a", |foo| unsafe { &*foo }.boo(4));
    /// ```
    pub fn new(parent: T) -> Self
    {
        let parent = UnsafeCell::new(parent);
        let child = Holder::new();
        SelfRefHolder {
            parent,
            child,
        }
    }

    /// Returns a reference to the element of `child` corresponding to the key.
    ///
    /// # Examples
    ///
    /// ```
    /// use crow_util::self_ref;
    ///
    /// # struct Foo {
    /// #     field: String
    /// # }
    /// #
    /// # impl Foo {
    /// #     fn boo(&self,start: usize) -> Boo {
    /// #         Boo {
    /// #             field: &self.field[start..],
    /// #         }
    /// #     }
    /// # }
    /// #
    /// # struct Boo<'a> {
    /// #     field: &'a str,
    /// # }
    /// let foo = Foo { field: "Hi, I am Foo!".to_string()};
    ///
    /// let self_ref_holder = self_ref::SelfRefHolder::new(foo);
    /// self_ref_holder.insert("a", |foo| unsafe { &*foo }.boo(4));
    ///
    /// let val = self_ref_holder.get("a").unwrap().field;
    /// assert_eq!(val, "I am Foo!");
    /// ```
    pub fn get(&self,key: &str) -> Option<&U> {
        self.child.get(key)
    }

    /// Inserts an `element` accessible by `key`, returning a usable reference `element` corresponding to this `key`.
    /// In case the `key` was already present, the old `element` is returned and the new one is ignored.
    /// This method does not need `SelfRefHolder` to be mutable.
    ///
    /// There are 2 limitations to guarantee that this function is safe:
    ///
    /// * **Never** cast `*const T` to `&mut T`, **always** use `|p| unsafe {&*p}`!
    /// * **Never** create a reference to `parent` which outlives this closure, when using this function!  ( Use [`parent()`] instead)
    ///
    /// # Examples
    ///
    /// ```
    /// use crow_util::self_ref;
    ///
    /// # struct Foo {
    /// #     field: String
    /// # }
    /// #
    /// # impl Foo {
    /// #     fn boo(&self,start: usize) -> Boo {
    /// #         Boo {
    /// #             field: &self.field[start..],
    /// #         }
    /// #     }
    /// # }
    /// #
    /// # struct Boo<'a> {
    /// #     field: &'a str,
    /// # }
    /// let foo = Foo { field: "Hi, I am Foo!".to_string()};
    ///
    /// let self_ref_holder = self_ref::SelfRefHolder::new(foo);
    ///
    /// let a = self_ref_holder.insert("a", |foo| unsafe { &*foo }.boo(4)).unwrap();
    ///
    /// assert_eq!(a.field, self_ref_holder.insert("a", |foo| unsafe { &*foo }.boo(7)).unwrap().field);
    /// ```
    /// [`parent()`]:../../crow_util/self_ref/struct.SelfRefHolder.html#method.parent
    pub fn insert<F>(&self,key: &str, element: F) -> Option<&U>
    where F: Fn(*const T) -> U,{
        let element = || element(self.parent.get());
        self.child.insert_fn(key, element)
    }

    /// Returns a immutable reference to the `parent` field.
    ///
    /// # Examples
    ///
    /// ```
    /// use crow_util::self_ref;
    ///
    /// # struct Foo {
    /// #     field: String
    /// # }
    /// #
    /// # impl Foo {
    /// #     fn boo(&self,start: usize) -> Boo {
    /// #         Boo {
    /// #             field: &self.field[start..],
    /// #         }
    /// #     }
    /// # }
    /// #
    /// # struct Boo<'a> {
    /// #     field: &'a str,
    /// # }
    /// let foo = Foo { field: "Hi, I am Foo!".to_string()};
    ///
    /// let self_ref_holder = self_ref::SelfRefHolder::new(foo);
    ///
    /// assert_eq!(self_ref_holder.parent().field,"Hi, I am Foo!");
    /// # self_ref_holder.insert("a", |foo| unsafe { &*foo }.boo(4)).unwrap();
    /// ```
    pub fn parent(&self) -> &T {
        unsafe { &*self.parent.get() }
    }

    /// Consumes `self` and returns the `parent`.
    ///
    /// # Examples
    ///
    /// ```
    /// use crow_util::self_ref;
    ///
    /// # struct Foo {
    /// #     field: String
    /// # }
    /// #
    /// # impl Foo {
    /// #     fn boo(&self,start: usize) -> Boo {
    /// #         Boo {
    /// #             field: &self.field[start..],
    /// #         }
    /// #     }
    /// # }
    /// #
    /// # struct Boo<'a> {
    /// #     field: &'a str,
    /// # }
    /// let foo = Foo { field: "Hi, I am Foo!".to_string()};
    /// let self_ref_holder = self_ref::SelfRefHolder::new(foo);
    ///
    /// self_ref_holder.insert("a", |foo| unsafe { &*foo }.boo(4)).unwrap();
    /// self_ref_holder.insert("b", |foo| unsafe { &*foo }.boo(7)).unwrap();
    ///
    /// let foo = self_ref_holder.free();
    /// assert_eq!(foo.field, "Hi, I am Foo!")
    /// ```
    pub fn free(self) -> T {
        unsafe { self.parent.into_inner() }
    }
}