localloc 0.0.1

A collection of local (non-global) rust allocation traits
Documentation
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use core::any::Any;
//use core::array::LengthAtMost32;
use core::borrow;
use core::cmp::Ordering;
//use core::convert::{From, TryFrom};
use core::fmt;
use core::future::Future;
use core::hash::{Hash, Hasher};
//use core::iter::{FromIterator, FusedIterator, Iterator};
use core::marker::{Unpin};
use core::mem;
use core::ops::{
    Deref, DerefMut,
};
use core::pin::Pin;
use core::ptr::{NonNull};
use core::task::{Context, Poll};

//use core::alloc::{self, AllocInit, AllocRef, Global};
//use core::raw_vec::RawVec;
//use alloc::str::from_boxed_utf8_unchecked;
//use alloc::vec::Vec;

use core::marker;
use core::alloc::Layout;

use crate::alloc::LocalAlloc;

pub struct LocalBox<T: ?Sized, A: LocalAlloc> {
    data: NonNull<T>,
    _allocator: marker::PhantomData<A>,
}

impl<T, A: LocalAlloc> LocalBox<T, A> {
    unsafe fn layout() -> Layout {
        Layout::from_size_align_unchecked(mem::size_of::<T>(), mem::align_of::<T>())
    }
    /// Allocates memory on the heap and then places `x` into it.
    ///
    /// This doesn't actually allocate if `T` is zero-sized.
    ///
    /// # Examples
    ///
    /// ```
    /// let five = Box::new(5);
    /// ```
    #[inline(always)]
    pub fn new(x: T) -> LocalBox<T, A> {
        unsafe {
            let l = Self::layout();
            let mut s = Self::from_raw(A::alloc(l) as *mut T);
            *s.data.as_mut() = x;
            s
        }
    }

    //#[inline(always)]
    //pub fn pin(x: T) -> Pin<LocalBox<T, A>> {
    //    Self::new(x).into()
    //}
}

impl<T: ?Sized, A: LocalAlloc> LocalBox<T, A> {
    fn layout_of(val: &T) -> Layout {
        unsafe {
            Layout::from_size_align_unchecked(mem::size_of_val(val), mem::align_of_val(val))
        }
    }

    #[inline]
    pub unsafe fn from_raw(raw: *mut T) -> Self {
        LocalBox{ 
            data: NonNull::new_unchecked(raw),
            _allocator: marker::PhantomData,
        }
    }
    #[inline]
    pub fn into_raw(b: LocalBox<T, A>) -> *mut T {
        LocalBox::into_raw_non_null(b).as_ptr()
    }

    // Currently unstable
    #[inline]
    #[doc(hidden)]
    pub fn into_raw_non_null(b: LocalBox<T, A>) -> NonNull<T> {
        unsafe {
            NonNull::new_unchecked(LocalBox::leak(b) as *mut T)
        }
    }

    #[inline]
    pub fn leak<'a>(b: LocalBox<T, A>) -> &'a mut T
    where
        T: 'a, // Technically not needed, but kept to be explicit.
    {
        unsafe { &mut *LocalBox::into_raw(b) }
    }
}

impl<T: ?Sized, A: LocalAlloc> Drop for LocalBox<T, A> {
    fn drop(&mut self) {
        unsafe {
            A::dealloc(self.data.as_ptr() as *mut u8, Self::layout_of(self.data.as_ref()))
        }
    }
}

impl<T: Default, A: LocalAlloc> Default for LocalBox<T, A> {
    /// Creates a `Box<T>`, with the `Default` value for T.
    fn default() -> LocalBox<T, A> {
        Self::new(Default::default())
    }
}

//impl<T, A: LocalAlloc> Default for LocalBox<[T], A> {
//    fn default() -> LocalBox<[T], A> {
//        LocalBox::<[T; 0], A>::new([])
//    }
//}

//impl Default for LocalBox<str> {
//    fn default() -> LocalBox<str> {
//        unsafe { from_boxed_utf8_unchecked(Default::default()) }
//    }
//}

impl<T: Clone, A: LocalAlloc> Clone for LocalBox<T, A> {
    fn clone(&self) -> LocalBox<T, A> {
        Self::new((**self).clone())
    }

    #[inline]
    fn clone_from(&mut self, source: &LocalBox<T, A>) {
        (**self).clone_from(&(**source));
    }
}

impl<T: ?Sized + PartialEq, A: LocalAlloc> PartialEq for LocalBox<T, A> {
    #[inline]
    fn eq(&self, other: &LocalBox<T, A>) -> bool {
        PartialEq::eq(&**self, &**other)
    }
    #[inline]
    fn ne(&self, other: &LocalBox<T, A>) -> bool {
        PartialEq::ne(&**self, &**other)
    }
}
impl<T: ?Sized + PartialOrd, A: LocalAlloc> PartialOrd for LocalBox<T, A> {
    #[inline]
    fn partial_cmp(&self, other: &LocalBox<T, A>) -> Option<Ordering> {
        PartialOrd::partial_cmp(&**self, &**other)
    }
    #[inline]
    fn lt(&self, other: &LocalBox<T, A>) -> bool {
        PartialOrd::lt(&**self, &**other)
    }
    #[inline]
    fn le(&self, other: &LocalBox<T, A>) -> bool {
        PartialOrd::le(&**self, &**other)
    }
    #[inline]
    fn ge(&self, other: &LocalBox<T, A>) -> bool {
        PartialOrd::ge(&**self, &**other)
    }
    #[inline]
    fn gt(&self, other: &LocalBox<T, A>) -> bool {
        PartialOrd::gt(&**self, &**other)
    }
}
impl<T: ?Sized + Ord, A: LocalAlloc> Ord for LocalBox<T, A> {
    #[inline]
    fn cmp(&self, other: &LocalBox<T, A>) -> Ordering {
        Ord::cmp(&**self, &**other)
    }
}
impl<T: ?Sized + Eq, A: LocalAlloc> Eq for LocalBox<T, A> {}

impl<T: ?Sized + Hash, A: LocalAlloc> Hash for LocalBox<T, A> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        (**self).hash(state);
    }
}

impl<T: ?Sized + Hasher, A: LocalAlloc> Hasher for LocalBox<T, A> {
    fn finish(&self) -> u64 {
        (**self).finish()
    }
    fn write(&mut self, bytes: &[u8]) {
        (**self).write(bytes)
    }
    fn write_u8(&mut self, i: u8) {
        (**self).write_u8(i)
    }
    fn write_u16(&mut self, i: u16) {
        (**self).write_u16(i)
    }
    fn write_u32(&mut self, i: u32) {
        (**self).write_u32(i)
    }
    fn write_u64(&mut self, i: u64) {
        (**self).write_u64(i)
    }
    fn write_u128(&mut self, i: u128) {
        (**self).write_u128(i)
    }
    fn write_usize(&mut self, i: usize) {
        (**self).write_usize(i)
    }
    fn write_i8(&mut self, i: i8) {
        (**self).write_i8(i)
    }
    fn write_i16(&mut self, i: i16) {
        (**self).write_i16(i)
    }
    fn write_i32(&mut self, i: i32) {
        (**self).write_i32(i)
    }
    fn write_i64(&mut self, i: i64) {
        (**self).write_i64(i)
    }
    fn write_i128(&mut self, i: i128) {
        (**self).write_i128(i)
    }
    fn write_isize(&mut self, i: isize) {
        (**self).write_isize(i)
    }
}

impl<T, A:LocalAlloc> From<T> for LocalBox<T, A> {
    fn from(t: T) -> Self {
        LocalBox::new(t)
    }
}

//impl<T: ?Sized, A: LocalAlloc> From<LocalBox<T, A>> for Pin<LocalBox<T, A>> {
//    /// Converts a `Box<T>` into a `Pin<Box<T>>`
//    ///
//    /// This conversion does not allocate on the heap and happens in place.
//    fn from(boxed: LocalBox<T, A>) -> Self {
//        LocalBox::into_pin(boxed)
//    }
//}

//impl<T: Copy> From<&[T]> for LocalBox<[T]> {
//    /// Converts a `&[T]` into a `Box<[T]>`
//    ///
//    /// This conversion allocates on the heap
//    /// and performs a copy of `slice`.
//    ///
//    /// # Examples
//    /// ```rust
//    /// // create a &[u8] which will be used to create a LocalBox<[u8]>
//    /// let slice: &[u8] = &[104, 101, 108, 108, 111];
//    /// let boxed_slice: LocalBox<[u8]> = Box::from(slice);
//    ///
//    /// println!("{:?}", boxed_slice);
//    /// ```
//    fn from(slice: &[T]) -> LocalBox<[T]> {
//        let len = slice.len();
//        let buf = RawVec::with_capacity(len);
//        unsafe {
//            ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
//            buf.into_box(slice.len()).assume_init()
//        }
//    }
//}
//
//impl From<&str> for LocalBox<str> {
//    /// Converts a `&str` into a `Box<str>`
//    ///
//    /// This conversion allocates on the heap
//    /// and performs a copy of `s`.
//    ///
//    /// # Examples
//    /// ```rust
//    /// let boxed: LocalBox<str> = Box::from("hello");
//    /// println!("{}", boxed);
//    /// ```
//    #[inline]
//    fn from(s: &str) -> LocalBox<str> {
//        unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
//    }
//}
//
//impl From<LocalBox<str>> for LocalBox<[u8]> {
//    /// Converts a `Box<str>>` into a `Box<[u8]>`
//    ///
//    /// This conversion does not allocate on the heap and happens in place.
//    ///
//    /// # Examples
//    /// ```rust
//    /// // create a LocalBox<str> which will be used to create a LocalBox<[u8]>
//    /// let boxed: LocalBox<str> = Box::from("hello");
//    /// let boxed_str: LocalBox<[u8]> = Box::from(boxed);
//    ///
//    /// // create a &[u8] which will be used to create a LocalBox<[u8]>
//    /// let slice: &[u8] = &[104, 101, 108, 108, 111];
//    /// let boxed_slice = Box::from(slice);
//    ///
//    /// assert_eq!(boxed_slice, boxed_str);
//    /// ```
//    #[inline]
//    fn from(s: LocalBox<str>) -> Self {
//        unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
//    }
//}

//impl<T, const N: usize> TryFrom<LocalBox<[T]>> for LocalBox<[T; N]>
//where
//    [T; N]: LengthAtMost32,
//{
//    type Error = LocalBox<[T]>;
//
//    fn try_from(boxed_slice: LocalBox<[T]>) -> Result<Self, Self::Error> {
//        if boxed_slice.len() == N {
//            Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
//        } else {
//            Err(boxed_slice)
//        }
//    }
//}

impl<A: LocalAlloc> LocalBox<dyn Any, A> {
    #[inline]
    /// Attempt to downcast the box to a concrete type.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::any::Any;
    ///
    /// fn print_if_string(value: LocalBox<dyn Any>) {
    ///     if let Ok(string) = value.downcast::<String>() {
    ///         println!("String ({}): {}", string.len(), string);
    ///     }
    /// }
    ///
    /// let my_string = "Hello World".to_string();
    /// print_if_string(Box::new(my_string));
    /// print_if_string(Box::new(0i8));
    /// ```
    pub fn downcast<T: Any>(self) -> Result<LocalBox<T, A>, LocalBox<dyn Any, A>> {
        if self.is::<T>() {
            unsafe {
                let raw: *mut dyn Any = LocalBox::into_raw(self);
                Ok(LocalBox::from_raw(raw as *mut T))
            }
        } else {
            Err(self)
        }
    }
}

impl<A: LocalAlloc> LocalBox<dyn Any + Send, A> {
    #[inline]
    /// Attempt to downcast the box to a concrete type.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::any::Any;
    ///
    /// fn print_if_string(value: LocalBox<dyn Any + Send>) {
    ///     if let Ok(string) = value.downcast::<String>() {
    ///         println!("String ({}): {}", string.len(), string);
    ///     }
    /// }
    ///
    /// let my_string = "Hello World".to_string();
    /// print_if_string(Box::new(my_string));
    /// print_if_string(Box::new(0i8));
    /// ```
    pub fn downcast<T: Any>(self) -> Result<LocalBox<T, A>, LocalBox<dyn Any + Send, A>> {
        if self.is::<T>() {
            unsafe {
                let raw: *mut (dyn Any + Send) = LocalBox::into_raw(self);
                Ok(LocalBox::from_raw(raw as *mut T))
            }
        } else {
            Err(self)
        }
    }
}

impl<T: fmt::Display + ?Sized, A: LocalAlloc> fmt::Display for LocalBox<T, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

impl<T: fmt::Debug + ?Sized, A: LocalAlloc> fmt::Debug for LocalBox<T, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<T: ?Sized, A: LocalAlloc> fmt::Pointer for LocalBox<T, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // It's not possible to extract the inner Uniq directly from the Box,
        // instead we cast it to a *const which aliases the Unique
        let ptr: *const T = &**self;
        fmt::Pointer::fmt(&ptr, f)
    }
}

impl<T: ?Sized, A: LocalAlloc> Deref for LocalBox<T, A> {
    type Target = T;

    #[allow(unconditional_recursion)]
    fn deref(&self) -> &T {
        &**self
    }
}

impl<T: ?Sized, A: LocalAlloc> DerefMut for LocalBox<T, A> {
    #[allow(unconditional_recursion)]
    fn deref_mut(&mut self) -> &mut T {
        &mut **self
    }
}

//impl<I: Iterator + ?Sized, A: LocalAlloc> Iterator for LocalBox<I> {
//    type Item = I::Item;
//    fn next(&mut self) -> Option<I::Item> {
//        (**self).next()
//    }
//    fn size_hint(&self) -> (usize, Option<usize>) {
//        (**self).size_hint()
//    }
//    fn nth(&mut self, n: usize) -> Option<I::Item> {
//        (**self).nth(n)
//    }
//    fn last(self) -> Option<I::Item> {
//        BoxIter::last(self)
//    }
//}

//trait BoxIter {
//    type Item;
//    fn last(self) -> Option<Self::Item>;
//}

//impl<I: Iterator + ?Sized, A: LocalAlloc> BoxIter for LocalBox<I> {
//    type Item = I::Item;
//    default fn last(self) -> Option<I::Item> {
//        #[inline]
//        fn some<T>(_: Option<T>, x: T) -> Option<T> {
//            Some(x)
//        }
//
//        self.fold(None, some)
//    }
//}
//
///// Specialization for sized `I`s that uses `I`s implementation of `last()`
///// instead of the default.
//impl<I: Iterator> BoxIter for LocalBox<I> {
//    fn last(self) -> Option<I::Item> {
//        (*self).last()
//    }
//}
//
//impl<I: DoubleEndedIterator + ?Sized, A: LocalAlloc> DoubleEndedIterator for LocalBox<I> {
//    fn next_back(&mut self) -> Option<I::Item> {
//        (**self).next_back()
//    }
//    fn nth_back(&mut self, n: usize) -> Option<I::Item> {
//        (**self).nth_back(n)
//    }
//}
//impl<I: ExactSizeIterator + ?Sized, A: LocalAlloc> ExactSizeIterator for LocalBox<I> {
//    fn len(&self) -> usize {
//        (**self).len()
//    }
//    fn is_empty(&self) -> bool {
//        (**self).is_empty()
//    }
//}

//impl<I: FusedIterator + ?Sized, A: LocalAlloc> FusedIterator for LocalBox<I> {}
//
//impl<A, F: FnOnce<A> + ?Sized, L: LocalAlloc> FnOnce<A> for LocalBox<F> {
//    type Output = <F as FnOnce<A>>::Output;
//
//    extern "rust-call" fn call_once(self, args: A) -> Self::Output {
//        <F as FnOnce<A>>::call_once(*self, args)
//    }
//}
//
//impl<A, F: FnMut<A> + ?Sized, A: LocalAlloc> FnMut<A> for LocalBox<F> {
//    extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
//        <F as FnMut<A>>::call_mut(self, args)
//    }
//}
//
//impl<A, F: Fn<A> + ?Sized, A: LocalAlloc> Fn<A> for LocalBox<F> {
//    extern "rust-call" fn call(&self, args: A) -> Self::Output {
//        <F as Fn<A>>::call(self, args)
//    }
//}

//impl<A> FromIterator<A> for LocalBox<[A]> {
//    fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
//        iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
//    }
//}

//impl<T: Clone, A: LocalAlloc> Clone for LocalBox<[T], A> {
//    fn clone(&self) -> Self {
//        self.to_vec().into_boxed_slice()
//    }
//}

impl<T: ?Sized, A: LocalAlloc> borrow::Borrow<T> for LocalBox<T, A> {
    fn borrow(&self) -> &T {
        &**self
    }
}

impl<T: ?Sized, A: LocalAlloc> borrow::BorrowMut<T> for LocalBox<T, A> {
    fn borrow_mut(&mut self) -> &mut T {
        &mut **self
    }
}

impl<T: ?Sized, A: LocalAlloc> AsRef<T> for LocalBox<T, A> {
    fn as_ref(&self) -> &T {
        &**self
    }
}

impl<T: ?Sized, A: LocalAlloc> AsMut<T> for LocalBox<T, A> {
    fn as_mut(&mut self) -> &mut T {
        &mut **self
    }
}

/* Nota bene
 *
 *  We could have chosen not to add this impl, and instead have written a
 *  function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
 *  because LocalBox<T, A> implements Unpin even when T does not, as a result of
 *  this impl.
 *
 *  We chose this API instead of the alternative for a few reasons:
 *      - Logically, it is helpful to understand pinning in regard to the
 *        memory region being pointed to. For this reason none of the
 *        standard library pointer types support projecting through a pin
 *        (Box<T> is the only pointer type in std for which this would be
 *        safe.)
 *      - It is in practice very useful to have LocalBox<T, A> be unconditionally
 *        Unpin because of trait objects, for which the structural auto
 *        trait functionality does not apply (e.g., LocalBox<dyn Foo> would
 *        otherwise not be Unpin).
 *
 *  Another type with the same semantics as Box but only a conditional
 *  implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
 *  could have a method to project a Pin<T> from it.
 */
impl<T: ?Sized, A: LocalAlloc> Unpin for LocalBox<T, A> {}

impl<F: ?Sized + Future + Unpin, A: LocalAlloc> Future for LocalBox<F, A> {
    type Output = F::Output;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        F::poll(Pin::new(&mut *self), cx)
    }
}