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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! # GSRS or Generic Self Referencing Struct
//!
//! This crate helps to create custom movable self referencing structs.
//! Nothing magical. It just wraps Owner and references to it in single package
//! with simple but unsafe lifetime tricks.
//!
//! Self referencing structs are generally considered an anti-pattern in Rust, so if you can easily
//! go without it you should do it. But sometimes you actually need to have a self referential struct.
//! So here are some examples when you actually need `SRS`:
//! - If you have structure that is built on references
//! (graph with Arena, or any structure built with slices on top of the string)
//! and you want to be able move it to another thread, or put it into Vec.
//! - If your api would be much better if you will be able to return self contained values.
//!
//! Does not support dependent lifetimes (yet?, is it actully needed/possible?)
//!
//! Should work on any stable rust starting from 1.31(2018 edition)
//!
//! # Usage
//! Simple example:
//! ```
//! use gsrs::*;
//! struct Test{field:usize}
//! #[derive(Default)]
//! struct TestRef<'a>(Option<&'a Test>);
//! deref_with_lifetime!(TestRef);
//! // create owned part
//! let mut srs = SRS::<Test, TestRef>::new( Test{ field: 5 } );
//! // create self-referencing part
//! srs.with(|user, owner|*user = TestRef(Some(owner)));
//! // get self referencing part back
//! let r = srs.get_ref(|user, _| user.0.unwrap());
//! println!("{}", r.field);
//! ```
//! or you can do creation in one go.
//! Although you anyway have to specify type of the referencing part
//! because type inference is getting confused by changed lifetime.
//! This can be fixed, but only when GATs will be stabilized.
//! ```
//! use gsrs::*;
//! struct Test{field:usize}
//! struct TestRef<'a>(&'a Test);
//! deref_with_lifetime!(TestRef);
//! // create owned part and self-referencing part
//! let mut srs = SRS::<_, TestRef>::create_with(
//! Test{ field: 5 },
//! |owner|TestRef(owner)
//! );
//! // get self referencing part back
//! let r = srs.get_ref(|user, _| user.0);
//! println!("{}", r.field);
//! ```
//! Referencing part can be arbitrary complex:
//! ```
//! use gsrs::*;
//! struct TestRef<'a>(Vec<&'a str>);
//! deref_with_lifetime!(TestRef);
//! // create owned part and self-referencing part
//! let mut srs = SRS::<_, TestRef>::create_with(
//! "long unicode string".to_owned(),
//! |owner|TestRef(owner.split(' ').collect())
//! );
//! // get self referencing part back
//! let r = srs.get_ref(|user, _| user.0[1]);
//! assert_eq!("unicode", r);
//! ```
//!
//! and this won't compile because `get_ref` is able to supply return value with proper lifetime:
//! ```compile_fail
//! # use gsrs::*;
//! # struct Test{field:usize}
//! # #[derive(Default)]
//! # struct TestRef<'a>(Option<&'a Test>);
//! # deref_with_lifetime!(TestRef);
//! # let mut srs = SRS::<Test,TestRef<'static>>::new(Test{field:5});
//! srs.with(|user, owner|*user = TestRef(Some(owner)));
//! let r = srs.get_ref(|user, _| user.0.unwrap());
//! drop(srs);
//! println!("{}",r.field);
//! ```
//! This also will fail because it is possible to return only static types or references to static types.
//! It is done to prevent changing some inner reference with interior mutability.
//! ```compile_fail
//! # use gsrs::*;
//! # struct Test{field:usize}
//! # struct TestRef<'a>(&'a Test);
//! # deref_with_lifetime!(TestRef);
//! let mut srs = SRS::<Test,TestRef<'static>>::create_with(
//! Test{field:5},
//! |owner|TestRef(owner),
//! );
//! // here closure returns TestRef<'a> not a reference
//! let r = srs.with(|user,_|user);
//! let mut ow = Box::new(Test{field:0});
//! let r = srs.split(&mut ow);
//! println!("{}",r.0.field);
//! ```
// use std::intrinsics::transmute;
// pub unsafe trait ExtendedWhileBorrowed:Movable {}
use Deref;
use mem;
use transmute;
use NonNull;
use ;
// use std::marker::PhantomPinned;
// use std::pin::Pin;
// pub unsafe trait Movable:Unpin{}
// unsafe impl<T:Unpin> Movable for Box<T>{}
// unsafe impl<T:Unpin> Movable for Arena<T>{}
// unsafe impl<T:Unpin> Movable for Vec<T>{}
/// ## Self Referencing Struct
/// Allows owner and references to it to be saved in a same movable struct
///
/// In general you create `SRS` with `create_with`, modify it with `with`, use it with `get_ref`
/// and in the end it will be dropped automatically or you can use `split` to keep some parts if necessary.f
///
/// If you want to add additional owned values you will need arena-like structure like Arena from `typed_arena`
///
/// If `Owner` type can be extended while there are references to existing data, like Arena,
/// you can use `default` otherwise `new` is the only way to create it
///
/// It is recommended to annotate lifetime used for `DerefWithLifetime` impl as `'static` when creating `SRS`
/// otherwise it might be impossible to move it.
// uncomment if U is UnsafeCell
// unsafe impl<Owner,U> Sync for SRS<Owner,U>
// where
// U: for<'b> DerefWithLifetime<'b>+Sync,
// Owner: Sync
// {}
// pub trait TypeEquals {
// type Other;
// fn into_self(self) -> Self::Other;
// }
//
// impl<'b, T: DerefWithLifetime<'b>> TypeEquals for T {
// type Other = Self;
//
// fn into_self(self) -> Self::Other {
// self
// }
// }
// technically default drop is safe for current rust version
// but manually implementing drop is more future proof
// in case rust will allow to run particular code only if lifetime is static
// because in that case malicious drop impls will be able to save inner references in outer static variables
// impl<'a, Owner: 'a, U> Drop for SRS<Owner, U>
// where
// U: for<'b> DerefWithLifetime<'b>,
// {
// fn drop<'a>(&'a mut self) {
// unsafe {
// drop_in_place(<U as DerefWithLifetime<'a>>::deref_with_lifetime_mut(&mut self.user));
// drop_in_place(&mut self.owner)
// }
// }
// }
// impl<U: ?Sized> AliasedBox<U>{
// fn into(self) -> Box<U> {
// unsafe {
// let ptr = self.ptr.as_ptr();
// mem::forget(self);
// Box::from_raw(ptr)
// }
// }
// }
// /// This one is the most efficient but most restrictive.
// ///
// ///
// #[derive(Debug)]
// pub struct SRSThin<U1, U2>
// where
// U1: for<'b> DerefWithLifetime<'b>,
// U2: for<'b> DerefWithLifetime<'b>,
// {
// user1: U1,
// user2: U2,
// pinned: PhantomPinned,
// }
//
// impl<U1, U2> SRSThin<U1, U2>
// where
// U1: for<'b> DerefWithLifetime<'b>,
// U2: for<'b> DerefWithLifetime<'b>,
// {
//
// pub fn new(part1: U1, part2: U2) -> Self {
// Self{
// user1: part1,
// user2: part2,
// pinned: PhantomPinned
// }
// }
// }
/// This trait should be implemented for any struct that will contain references to data inside `SRS`
/// and it should be implemented for any lifetime.
/// Basically it just allows to apply custom lifetime to struct
///
/// It is already implemented for pure references.
/// In general `deref_with_lifetime' macro should be used to implement this trait safely.
///
/// It is unsafe because SRS expects implementations of this trait to only change lifetime.
///
/// TODO this will only be implemented with macro in future
pub unsafe
unsafe
/// Macro to implement `DerefWithLifetime`
///
/// Currently only works for simple cases with one lifetime and no generic,
/// but in future this will be the only way to implement trait