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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
#![cfg_attr(not(test),no_std)]
#![cfg_attr(feature = "nightly", feature(min_const_generics))]

//! Structures and traits to represent and safely manipulate any data as raw memory
//!
//!
//! # Examples
//! 
//! Any kind of data can be viewed as constant memory slice:
//! ```
//! use memory_slice::AsMemory;
//! let v: [u8;4] = [1,1,1,1];
//! //as_memory return a &memory_slice
//! assert_eq!(unsafe{v.as_memory().read::<i32>()},1 + (1<<8) + (1<<16) + (1<<24));
//! ```
//! 
//! But only types that does not preserve any invariants are accessible as mutable memory slice:
//!
//! This will compile:
//! ```
//! use memory_slice::AsMutMemory;
//! let mut v: [u8;4] = [1,1,1,1];
//! //as_memory return a &memory_slice
//! v.as_mut_memory().write(16 as u16);
//! ```
//!
//! This will not compile:
//! ```compile_fail
//! use memory_slice::AsMutMemory;
//! use std::string::String;
//! let mut v = String::new();
//! //as_memory return a &memory_slice
//! v.as_mut_memory().write(16 as u16);
//! ```
//!
//! Mutable memory slices can be used to write information of any type
//! while preserving borrow rules. The API provide also a smart pointer
//! that will drop value created on the memory slice:
//! ```
//! use memory_slice::{align,AsMutMemory,AsMemory};
//! // creates an array of 64 u8 aligned as 8: 
//! let mut buff = align!(8,[0 as u8;64]);
//!
//! //the create an int inside the buffer and get a reference to it
//! let (padding, v1, remaining_buffer) = buff.as_mut_memory().write(42 as i32);
//! assert!(padding.is_empty());
//! //unsafe{buff[0]}; //error => cannot borrow buff as immutable
//!
//! //use the remaining unitialized buffer to write an u64 in it:
//! let (padding, v2, remaining_buffer2) = remaining_buffer.write(42 as u64);
//! assert_eq!(padding.len(), 4);
//! //unsafe{remaing_buffer.read::<u8>()}; //error => cannot borrow remaining_buffer
//!
//! //v1 and v2 are reference to the i32 and u64 created inside buff
//! assert_eq!(*v1 as u64, *v2);
//!
//! {
//!     extern crate alloc;
//!     use alloc::borrow::ToOwned;
//!
//!     //In what remains of the buffer, let's create a value that needs to be dropped:
//!     let (_padding, v3, _remaining) = remaining_buffer2.emplace("42".to_owned());
//!
//!     //v3 is a smart pointer to the String created in the buffer that will drop
//!     //this string when it goes out of scope
//!     assert_eq!(*v1, v3.parse::<i32>().unwrap());
//! } //string refered by v3 is dropped
//!
//! //buff is not anymore borrowed, so it is accessible:
//! assert_eq!(unsafe { buff.as_memory().read::<i32>() }, 42);
//!
//! //memory slice can be indexed (!!less inoffensive than it looks)
//! unsafe{*buff.as_mut_memory()[2..4].as_mut_unchecked()=16 as u16};
//! assert_ne!(unsafe { buff.as_memory().read::<i32>() }, 42);
//! ```
//!
//! A macro named `buffer` is provided to create un initialized
//! buffer:
//! ```
//! use memory_slice::buffer;
//! // create an uninitialized buffer of 64 bytes aligned as 8.
//! let mut buff = buffer!(64,8);
//! // buffer are dereferencable as memory_slice
//!
//! //the create an int inside the buffer and get a reference to it
//! buff.write(42 as i32);
//! ```

extern crate contracts;
use contracts::*;

use core::alloc::Layout;
use core::marker::{PhantomData, Unpin};
use core::mem::{self, MaybeUninit};

use core::ops::{
    Deref, DerefMut, Drop, Index, IndexMut, Range, RangeBounds, RangeFrom, RangeFull,
    RangeInclusive, RangeTo, RangeToInclusive,
};
use core::slice;

type Underlying = MaybeUninit<u8>;
type MemLocation = u8;

/// Represents a raw memory range
///
/// References to this types are used to alias any kind
/// of objects that can be used as a memory buffer.
#[repr(transparent)]
pub struct Memory {
    inner: [Underlying],
}

/// Enable conversion of any type to a constant memory slice
///
/// This trait is implemented for every sized type and slices
pub trait AsMemory {
    fn as_memory(&self) -> &Memory {
        unsafe {
            Memory::from_raw_parts(
                self as *const _ as *const MemLocation,
                mem::size_of_val(self),
            )
        }
    }
}

/// Enable conversion to a mutable memory.
///
/// This trait should only be implemented for types that
/// does not maintain any internal invariants.
///
/// It is implemented for integer types and for all
/// slice \[T\] where T implements this trait.
pub trait AsMutMemory: AsMemory {
    fn as_mut_memory(&mut self) -> &mut Memory {
        unsafe {
            Memory::from_raw_parts_mut(self as *mut _ as *mut MemLocation, mem::size_of_val(self))
        }
    }
}

impl<T:?Sized> AsMemory for T {}

impl<T> AsMutMemory for [T] where T: AsMutMemory {}

#[cfg(feature = "nightly")]
impl <T, const N:usize> AsMutMemory for [T;N] where T: AsMutMemory {}

impl AsMutMemory for Memory {}

impl<T> AsMutMemory for MaybeUninit<T> {}

macro_rules! declare_trait {
    ($trait:ident ,$($type: ty),+) =>  ($(
        impl $trait for $type { }
        )*)
}

declare_trait! {AsMutMemory, u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, isize, usize, f32, f64}

impl Memory {
    #[test_ensures(loc == ret as *const _ as *const MemLocation)]
    /// Returns a constant memory slice of lenght `len` located at `loc`
    ///
    /// # Safety
    ///
    /// The referenced memory shall be a contiguous readable memory
    pub unsafe fn from_raw_parts<'a>(loc: *const MemLocation, len: usize) -> &'a Self {
        //mem::transmute(slice::from_raw_parts(loc as *const Underlying, len));
        &*(slice::from_raw_parts(loc as *const Underlying, len) as *const [Underlying]
            as *const Self)
    }

    #[test_ensures(loc == ret as *mut _ as *mut MemLocation)]
    /// Returns a mutable memory slice of lenght `len` located at `loc`
    ///
    /// # Safety
    ///
    /// The referenced memory shall be a contiguous readable and writable memory
    pub unsafe fn from_raw_parts_mut<'a>(loc: *mut MemLocation, len: usize) -> &'a mut Self {
        &mut *(slice::from_raw_parts_mut(loc as *mut Underlying, len) as *mut [Underlying]
            as *mut Self)
    }

    #[test_ensures(ret == self as *const _ as *const MemLocation)]
    /// Returns a pointer to the first byte of memory
    pub fn as_ptr(&self) -> *const MemLocation {
        self.inner.as_ptr() as *const MemLocation
    }

    #[test_ensures(ret == self as *mut _ as *mut MemLocation)]
    /// Returns a mutable pointer to the first byte of memory
    pub fn as_mut_ptr(&mut self) -> *mut MemLocation {
        self.inner.as_mut_ptr() as *mut MemLocation
    }

    #[test_ensures(ret == mem::size_of_val(self))]
    /// Returns the memory size.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    #[test_ensures(ret -> self.len()==0)]
    /// Returns true is length is null.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    #[test_ensures(self.as_ptr() as usize % ret == 0)]
    #[test_ensures(self.as_ptr() as usize % (2*ret) == ret)]
    /// Returns the alignment of the memory slice
    pub fn alignment(&self) -> usize {
        1 << (self.as_ptr() as usize).trailing_zeros()
    }

    #[test_ensures(self.len() == ret.0.len() + ret.1.len())]
    #[test_ensures(ret.0.len() == mid)]
    #[test_ensures(self.as_ptr() == ret.0.as_ptr())]
    #[test_ensures(unsafe{ret.0.as_ptr().add(mid)} == ret.1.as_ptr())]
    /// Split the memory slice at `mid`
    pub fn split_at(&self, mid: usize) -> (&Self, &Self) {
        let (l,r) = self.inner.split_at(mid);
        (l.as_memory(), r.as_memory())
    }

    #[test_ensures(self.len() == ret.0.len() + ret.1.len())]
    #[test_ensures(ret.0.len() == mid)]
    #[test_ensures(self.as_ptr() == ret.0.as_ptr())]
    #[test_ensures(unsafe{ret.0.as_ptr().add(mid)} == ret.1.as_ptr())]
    /// Mutably split the memory slice at `mid`
    pub fn split_at_mut<'a>(&mut self, mid: usize) -> (&mut Self, &mut Self) {
        let l = self.len();
        assert!(mid <= l);
        let ptr = self.as_mut_ptr();
        unsafe {(Memory::from_raw_parts_mut(ptr,mid), Memory::from_raw_parts_mut(ptr.add(mid),l-mid))}
    }

    #[test_ensures(unsafe{*(&self.inner as *const [Underlying] as *const[u8]) 
        == *(&other.inner as *const [Underlying] as *const[u8])})]
    /// Copy the content of a an other memory slice into self
    pub fn copy_from_memory(&mut self, other: &Self) {
        self.inner.copy_from_slice(unsafe {
            slice::from_raw_parts(other.as_ptr() as *const Underlying, other.len())
        });
    }

    /// Move data within this memory slice
    pub fn copy_within<R: RangeBounds<usize>>(&mut self, range: R, dest: usize) {
        self.inner.copy_within(range, dest);
    }

    #[debug_requires(self.alignment()>=mem::align_of::<T>())]
    #[debug_requires(self.len()>=mem::size_of::<T>())]
    #[test_ensures(self.as_ptr() == ret as *const _ as *const MemLocation)]
    /// Returns a reference of type &T that points to the first memory location
    ///
    /// # Safety
    ///
    /// The following pre-condition shall be filled:
    ///   - The memory is at least as aligned as T
    ///   - The memory size is at least as large as T
    ///   - The memory is a valid value representation of type T
    pub unsafe fn as_ref_unchecked<T>(&self) -> &T {
        &*(self.as_ptr() as *const T)
    }

    #[debug_requires(self.alignment()>=mem::align_of::<T>())]
    #[debug_requires(self.len()>=mem::size_of::<T>())]
    #[test_ensures(self.as_ptr() == ret as *mut _ as *const MemLocation)]
    /// Returns a mutable reference of type &mut T that points to the first memory location
    ///
    /// # Safety
    ///
    /// The following pre-condition shall be filled:
    ///   - The memory is at least as aligned as T
    ///   - The memory size is at least as large as T
    ///   - The memory is a valid value representation of type T
    pub unsafe fn as_mut_unchecked<T>(&mut self) -> &mut T {
        &mut *(self.as_mut_ptr() as *mut T)
    }

    #[debug_requires(self.alignment()>=mem::align_of::<T>())]
    #[debug_requires(self.len()>=len*mem::size_of::<T>())]
    #[test_ensures(self.as_ptr() == ret.as_ptr() as *const MemLocation)]
    /// Returns a slice of type &\[T\] that points to the first memory location
    ///
    /// # Safety
    ///
    /// The following pre-condition shall be filled:
    ///   - The memory is at least as aligned as T
    ///   - The memory size is at least as large as `len * size_of::<T>::()`
    ///   - The memory is a valid value representation of type T
    pub unsafe fn as_slice_unchecked<T>(&self, len: usize) -> &[T] {
        let ptr = self.as_ptr() as *const T;
        slice::from_raw_parts(ptr, len)
    }

    #[debug_requires(self.alignment()>=mem::align_of::<T>())]
    #[debug_requires(self.len()>=len*mem::size_of::<T>())]
    #[test_ensures(self.as_ptr() == ret.as_ptr() as *const MemLocation)]
    /// Returns a mutable slice of type &mut \[T\] that points to the first memory location
    ///
    /// # Safety
    ///
    /// The following pre-condition shall be filled:
    ///   - The memory is at least as aligned as T
    ///   - The memory size is at least as large as `len * size_of::<T>::()`
    ///   - The memory is a valid value representation of type T
    pub unsafe fn as_mut_slice_unchecked<T>(&mut self, len: usize) -> &mut [T] {
        let ptr = self.as_mut_ptr() as *mut T;
        slice::from_raw_parts_mut(ptr, len)
    }

    #[test_ensures(ret.0.len()<layout.align())]
    #[test_ensures(ret.1.len()==layout.size())]
    #[test_ensures(ret.1.alignment()>=layout.align())]
    #[test_ensures((self.alignment()<layout.align()) -> ret.1.alignment() == layout.align())]
    #[test_ensures((self.alignment()==layout.align()) -> (ret.0.len() == 0))]
    #[test_ensures(ret.0.len()+ret.1.len()+ret.2.len() == self.len())]
    #[test_ensures(ret.0.as_ptr() == self.as_ptr())]
    #[test_ensures(unsafe{ret.0.as_ptr().add(ret.0.len())} == ret.1.as_ptr())]
    #[test_ensures(unsafe{ret.1.as_ptr().add(ret.1.len())} == ret.2.as_ptr())]
    /// Create a split of the memory for the given layout
    ///
    /// Returns 3 memory slice:
    ///   - the first slice represent the alignment padding
    ///   - the second a memory slice sweatable for layout
    ///   - the third is the reaming memory
    ///
    pub fn align_for(&self, layout: Layout) -> (&Self, &Self, &Self) {
        let s0 = self.as_ptr().align_offset(layout.align());
        let (pad, rest) = self.split_at(s0);
        let (data, rem) = rest.split_at(layout.size());
        (pad, data, rem)
    }

    #[test_ensures(ret.1.len()<mem::size_of::<T>())]
    #[test_ensures(ret.1.alignment()>=mem::align_of::<T>())]
    /// Create a split of the memory for the given type
    ///
    /// Returns 3 memory slice:
    ///   - the first slice represent the alignment padding
    ///   - the second a memory slice sweatable for layout
    ///   - the third is the reaming memory
    ///
    pub fn align_for_type<T>(&self) -> (&Self, &Self, &Self) {
        self.align_for(unsafe {
            Layout::from_size_align_unchecked(mem::size_of::<T>(), mem::align_of::<T>())
        })
    }

    #[test_ensures(ret.1.len()<mem::size_of_val(v))]
    #[test_ensures(ret.1.alignment()>=mem::align_of_val(v))]
    /// Create a split of the memory for the given value
    ///
    /// Returns 3 memory slice:
    ///   - the first slice represent the alignment padding
    ///   - the second a memory slice sweatable for layout
    ///   - the third is the reaming memory
    ///
    pub fn align_for_val<T: ?Sized>(&self, v: &T) -> (&Self, &Self, &Self) {
        self.align_for(Layout::for_value(v))
    }

    #[test_ensures(ret.0.len()<layout.align())]
    #[test_ensures(ret.1.len()==layout.size())]
    #[test_ensures(ret.1.alignment()>=layout.align())]
    #[test_ensures((self.alignment()==layout.align()) -> (ret.0.len() == 0))]
    #[test_ensures(ret.0.len()+ret.1.len()+ret.2.len() == self.len())]
    #[test_ensures(ret.0.as_ptr() == self.as_ptr())]
    #[test_ensures(unsafe{ret.0.as_ptr().add(ret.0.len())} == ret.1.as_ptr())]
    #[test_ensures(unsafe{ret.1.as_ptr().add(ret.1.len())} == ret.2.as_ptr())]
    /// Create a split of the memory for the given layout
    ///
    /// Returns 3 memory slice:
    ///   - the first slice represent the alignment padding
    ///   - the second a memory slice sweatable for layout
    ///   - the third is the reaming memory
    ///
    pub fn align_for_mut(&mut self, layout: Layout) -> (&mut Self, &mut Self, &mut Self) {
        let l0 = self.as_ptr().align_offset(layout.align());
        let l1 = layout.size();
        let l = self.len();
        let l01 = l0+l1;
        assert!(l01 <= l);
        let ptr = self.as_mut_ptr();
        unsafe {(Memory::from_raw_parts_mut(ptr,l0)
               , Memory::from_raw_parts_mut(ptr.add(l0),l1)
               , Memory::from_raw_parts_mut(ptr.add(l01),l-l01))}
    }

    /// Create a split of the memory for the given type
    ///
    /// Returns 3 memory slice:
    ///   - the first slice represent the alignment padding
    ///   - the second a memory slice sweatable for layout
    ///   - the third is the reaming memory
    ///
    pub fn align_for_type_mut<T>(&mut self) -> (&mut Self, &mut Self, &mut Self) {
        self.align_for_mut(unsafe {
            Layout::from_size_align_unchecked(mem::size_of::<T>(), mem::align_of::<T>())
        })
    }

    /// Create a split of the memory for the given value
    ///
    /// Returns 3 memory slice:
    ///   - the first slice represent the alignment padding
    ///   - the second a memory slice sweatable for layout
    ///   - the third is the reaming memory
    ///
    pub fn align_for_val_mut<T: ?Sized>(&mut self, v: &T) -> (&mut Self, &mut Self, &mut Self) {
        self.align_for_mut(Layout::for_value(v))
    }

    /// Returns 2 memory slice and a reference to a value of type `T` as a tuple:
    ///   - the first element is a slice that represents the alignment padding
    ///   - the second element is reference to a `T`
    ///   - the third element is the reaming memory
    ///
    /// # Safety
    ///
    /// The following pre-condition shall be filled:
    ///   - The memory refered by the second element is a valid value representation of type T
    ///
    /// # Panics
    ///
    /// This function will panic if the memory slice is not large enough for T and needed alignment
    /// padding.
    ///
    pub unsafe fn get<T>(&self) -> (&Self, &T, &Self) {
        let (p, d, r) = self.align_for_type::<T>();
        (p, d.as_ref_unchecked(), r)
    }

    /// Returns 2 memory slice and a mutable reference to a value of type `T` as a tuple:
    ///   - the first element is a slice that represents the alignment padding
    ///   - the second element is reference to a `T`
    ///   - the third element is the reaming memory
    ///
    /// # Safety
    ///
    /// The following pre-condition shall be filled:
    ///   - The memory refered by the second element is a valid value representation of type T
    ///
    /// # Panics
    ///
    /// This function will panic if the memory slice is not large enough for T and needed alignment
    /// padding.
    ///
    pub unsafe fn get_mut<T>(&mut self) -> (&mut Self, &mut T, &mut Self) {
        let (p, d, r) = self.align_for_type_mut::<T>();
        (p, d.as_mut_unchecked(), r)
    }

    /// Returns 2 memory slice and a reference to a slice of type `[T]` and size `n` as a tuple:
    ///   - the first element is a slice that represents the alignment padding
    ///   - the second element is reference to `[T]`
    ///   - the third element is the reaming memory
    ///
    /// # Safety
    ///
    /// The following pre-condition shall be filled:
    ///   - The memory refered by the second element is a valid value representation for `n` `T`
    ///
    /// # Panics
    ///
    /// This function will panic if the memory slice is not large enough for `n` `T` and needed alignment
    /// padding.
    ///
    pub unsafe fn get_slice<T>(&self, n: usize) -> (&Self, &[T], &Self) {
        let (p, d, r) = self.align_for_type::<T>();
        (p, d.as_slice_unchecked(n), r)
    }

    /// Returns 2 memory slice and a mutable reference to a slice of type `[T]` and size `n` as a tuple:
    ///   - the first element is a slice that represents the alignment padding
    ///   - the second element is reference to `[T]`
    ///   - the third element is the reaming memory
    ///
    /// # Safety
    ///
    /// The following pre-condition shall be filled:
    ///   - The memory refered by the second element is a valid value representation for `n` `T`
    ///
    /// # Panics
    ///
    /// This function will panic if the memory slice is not large enough for `n` `T` and needed alignment
    /// padding.
    ///
    pub unsafe fn get_mut_slice<T>(&mut self, n: usize) -> (&mut Self, &mut [T], &mut Self) {
        let (p, d, r) = self.align_for_type_mut::<T>();
        (p, d.as_mut_slice_unchecked(n), r)
    }

    /// Returns an OwnedRef that refers to a &mut T that points to the first memory location
    ///
    /// # Safety
    ///
    /// The following pre-condition shall be filled:
    ///   - The memory is a valid value representation of type T
    ///
    /// # Panics
    ///
    /// This function will panic if the memory slice is not large enough for T and needed alignment
    /// padding.
    ///
    pub unsafe fn get_owned_ref<T>(&mut self) -> (&mut Self, OwnedRef<'_, T>, &mut Self) {
        let (p, v, r) = self.get_mut::<T>();
        (p, OwnedRef::new(v), r)
    }

    /// Returns an OwnedRef to a mutable slice of type &mut \[T\] that points to the first memory location
    ///
    /// # Safety
    ///
    /// The following pre-condition shall be filled:
    ///   - The memory is a valid value representation of type T
    ///
    /// # Panics
    ///
    /// This function will panic if the memory slice is not large enough for `n` `T` and needed alignment
    /// padding.
    pub unsafe fn get_owned_slice<T>(
        &mut self,
        n: usize,
    ) -> (&mut Self, OwnedSlice<'_, T>, &mut Self) {
        let (p, v, r) = self.get_mut_slice::<T>(n);
        (p, OwnedSlice::new(v), r)
    }

    /// Writes a value of type T by consuming it and
    /// returns a reference to it
    ///
    /// # Safety
    ///
    /// The following pre-condition shall be filled:
    ///   - The memory is at least as aligned as T
    ///   - The memory size is at least as large as T
    pub unsafe fn write_unchecked<T: Unpin>(&mut self, val: T) -> &mut T {
        core::ptr::copy_nonoverlapping(&val, self.as_mut_ptr() as *mut T, 1);
        core::mem::forget(val);
        self.as_mut_unchecked()
    }

    /// Writes a value of type T by consuming it and
    /// returns a reference to it
    ///
    /// # Panics
    ///
    /// This function will panic if the memory slice is not large enough for T and needed alignment
    /// padding.
    ///
    pub fn write<T: Unpin>(&mut self, val: T) -> (&mut Self, &mut T, &mut Self) {
        let (p, d, r) = self.align_for_type_mut::<T>();
        (p, unsafe { d.write_unchecked(val) }, r)
    }

    /// Writes a value of type T by consuming it and
    /// returns an [OwnedRef] that refers to it.
    ///
    /// # Panics
    ///
    /// The following pre-conditions will cause panics:
    ///   - The memory is not as aligned as T
    ///   - The memory size is not as large as T
    pub fn emplace<T: Unpin>(&mut self, val: T) -> (&mut Self, OwnedRef<'_, T>, &mut Self) {
        let (p, d, r) = self.write(val);
        (p, unsafe { OwnedRef::new(d) }, r)
    }

    /// Reads a value of type T
    ///
    /// # Safety
    ///
    /// The following pre-conditions shall be fullfilled:
    ///   - The memory size is as large as T
    ///   - The memory has a valid value representation of type T
    pub unsafe fn read<T: Unpin>(&self) -> T {
        let mut b = MaybeUninit::uninit();
        core::ptr::copy_nonoverlapping(self.as_ptr() as *const T, b.as_mut_ptr(), 1);
        b.assume_init()
    }

    /// Reads a value of type T
    ///
    /// # Safety
    ///
    /// The following pre-condition shall be fullfilled:
    ///   - The memory has a valid value representation of type T
    ///
    /// # Panics
    ///
    /// This function will panic if the memory slice is not large enough for T and needed alignment
    /// padding.
    ///
    pub unsafe fn aligned_read<T: Unpin>(&self) -> T {
        let (_, d, _) = self.align_for_type::<T>();
        d.read()
    }
}

macro_rules! impl_index {
    ($($range: ty),+) => ( $(
impl Index<$range> for Memory
{
    type Output = Self;
    fn index(&self, range: $range) -> &Self::Output {
        unsafe{&*(self.inner.index(range) as *const [Underlying] as *const Self)}
    }
}
impl IndexMut<$range> for Memory
{
    fn index_mut(&mut self, range: $range) -> &mut Self::Output {
        unsafe{&mut *(self.inner.index_mut(range) as *mut [Underlying] as *mut Self)}
    }
}
)*)
}

impl_index! {Range<usize>,RangeFrom<usize>, RangeFull,RangeInclusive<usize>,RangeTo<usize>,RangeToInclusive<usize>}

impl Index<usize> for Memory {
    type Output = MemLocation;
    fn index(&self, index: usize) -> &Self::Output {
        unsafe { &*(&self.inner[index] as *const Underlying as *const MemLocation) }
    }
}
impl IndexMut<usize> for Memory {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        unsafe { &mut *(&mut self.inner[index] as *mut Underlying as *mut MemLocation) }
    }
}

#[repr(transparent)]
#[derive(Debug, Copy)]
/// A buffer of uninitialized memory with same size and alignement as T.
///
/// Those buffer implement `Deref<Target=Memory>` and `DerefMut<Target=Memory>`
/// so they have the same interface as [Memory].
pub struct BufferAs<T>(MaybeUninit<T>);

impl<T> BufferAs<T> {
    /// Create an uninitialized buffer.
    pub fn new() -> Self {
        Self(MaybeUninit::uninit())
    }
    /// Create a zeroed buffer.
    pub fn zeroed() -> Self {
        Self(MaybeUninit::zeroed())
    }
}

impl<T> Deref for BufferAs<T> {
    type Target = Memory;
    fn deref(&self) -> &Self::Target {
        unsafe {
            Memory::from_raw_parts(
                self as *const _ as *const MemLocation,
                mem::size_of_val(self),
            )
        }
    }
}

impl<T> DerefMut for BufferAs<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe {
            Memory::from_raw_parts_mut(self as *mut _ as *mut MemLocation, mem::size_of_val(self))
        }
    }
}

impl<T> AsMutMemory for BufferAs<T> { }

impl<T> Clone for BufferAs<T> {
    fn clone(&self) -> Self {
        let mut r = MaybeUninit::<Self>::uninit();
        unsafe {
            core::ptr::copy_nonoverlapping(self, r.as_mut_ptr(), 1);
            r.assume_init()
        }
    }
}

#[repr(transparent)]
/// A reference that drops its pointee when it is dropped
///
/// Hold a reference to a value of type T that is
/// dropped when the OwnedRef is dropped
pub struct OwnedRef<'a, T>(&'a mut T);

impl<'a, T> OwnedRef<'a, T> {
    /// Returns an OwnedRef to v.
    ///
    /// # Safety
    ///
    /// v shall not be destroyed by other means
    pub unsafe fn new(v: &'a mut T) -> Self {
        Self(v)
    }
}

impl<'a, T> Drop for OwnedRef<'a, T> {
    fn drop(&mut self) {
        unsafe { core::ptr::drop_in_place(self.0) }
    }
}
impl<'a, T> Deref for OwnedRef<'a, T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl<'a, T> DerefMut for OwnedRef<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}
impl<'a, T> AsRef<T> for OwnedRef<'a, T> {
    fn as_ref(&self) -> &T {
        &self.0
    }
}
impl<'a, T> AsMut<T> for OwnedRef<'a, T> {
    fn as_mut(&mut self) -> &mut T {
        &mut self.0
    }
}

/// A reference to a slice that drops its pointee when it is dropped
///
/// Hold a reference to a slice of type T that is
/// dropped when the OwnedSlice is dropped
pub struct OwnedSlice<'a, T>(*mut T, usize, PhantomData<&'a mut T>);

impl<'a, T> OwnedSlice<'a, T> {
    /// Returns an OwnedSlice to s.
    ///
    /// # Safety
    ///
    /// s elements shall not be destroyed by other means
    pub unsafe fn new(s: &'a mut [T]) -> Self {
        Self(s.as_mut_ptr(), s.len(), PhantomData)
    }
}

impl<'a, T> Drop for OwnedSlice<'a, T> {
    fn drop(&mut self) {
        unsafe { core::ptr::drop_in_place(slice::from_raw_parts_mut(self.0, self.1)) }
    }
}
impl<'a, T> Deref for OwnedSlice<'a, T> {
    type Target = [T];
    fn deref(&self) -> &Self::Target {
        unsafe { slice::from_raw_parts(self.0, self.1) }
    }
}
impl<'a, T> DerefMut for OwnedSlice<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { slice::from_raw_parts_mut(self.0, self.1) }
    }
}
impl<'a, T> AsRef<[T]> for OwnedSlice<'a, T> {
    fn as_ref(&self) -> &[T] {
        self.deref()
    }
}
impl<'a, T> AsMut<[T]> for OwnedSlice<'a, T> {
    fn as_mut(&mut self) -> &mut [T] {
        self.deref_mut()
    }
}

#[macro_export]
/// Returns an overaligned value.
///
/// `align(alignment,expr)` returns the value of a structure declared with #[repr(align($alignment))]
/// attributes that dereferences the result of `expr`.
macro_rules! align {
    ($alignment:literal, $exp:expr) => {{
        #[repr(align($alignment))]
        struct Aligner<T>(T);
        impl<T> ::core::ops::Deref for Aligner<T> {
            type Target = T;
            fn deref(&self) -> &T {
                &self.0
            }
        }
        impl<T> ::core::ops::DerefMut for Aligner<T> {
            fn deref_mut(&mut self) -> &mut T {
                &mut self.0
            }
        }
        impl<T> ::core::convert::AsRef<T> for Aligner<T> {
            fn as_ref(&self) -> &T {
                &*self
            }
        }
        impl<T> ::core::convert::AsMut<T> for Aligner<T> {
            fn as_mut(&mut self) -> &mut T {
                &mut *self
            }
        }
        impl<T> $crate::AsMutMemory for Aligner<T> where T: $crate::AsMutMemory {}
        Aligner($exp)
    }};
}

#[macro_export]
/// Creates a statically sized buffer on the stack.
///
/// `buffer(size)` returns a buffer of size `size` aligned as `16`.
///
/// `buffer(size,alignment)` returns a buffer of size `size` aligned as `alignment`.
///
///  The argument `size` must be a constant expression and `alignement` a litteral integer.
macro_rules! buffer {
    ($size:expr,$alignment:literal) => {{
        use $crate::align;
        align!($alignment, $crate::BufferAs::<[u8; $size]>::new())
    }};
    ($size:expr) => {{
        $crate::buffer!($size, 16)
    }};
}

#[cfg(test)]
mod tests {
    use super::buffer;
    use rstest::*;
    use core::fmt::Debug;
    use core::mem;

    #[rstest(
        value => [42 as usize,42 as u32,42 as u16, 42 as u8],
        mis_alignment => [0,1,2,3,4,5,6,7,8,9]
        )]
    fn write<T:Eq+Copy+Unpin+Debug>(value: T,mis_alignment: usize) {
        let mut buff = buffer!(64, 64);
        {
            let (_,buff) = buff.split_at_mut(mis_alignment);
            let (_,v,_) = buff.write(value);
            assert_eq!(*v,value);
        }
        if mis_alignment==0 {
            assert_eq!(unsafe{buff.read::<T>()},value);
            assert_eq!(*unsafe{buff.as_ref_unchecked::<T>()},value);
        } else {
            let loc = ((mis_alignment-1)/mem::size_of::<T>() + 1) * mem::size_of::<T>();
            assert_eq!(unsafe{buff[loc..].read::<T>()},value);
            assert_eq!(*unsafe{buff[loc..].as_ref_unchecked::<T>()},value);
        }
    }

}