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
//! A library for rust to provide ways to emplace dynamic sized type
//! ```rust
//! #![feature(alloc_layout_extra)]
//! #![feature(ptr_metadata)]
//!
//! use dst_init_macros::dst;
//! use dst_init::{BoxExt, Slice, SliceExt};
//! #[dst]
//! #[derive(Debug)]
//! struct Test<A, B, C, D> {
//!     a: A,
//!     b: B,
//!     c: C,
//!     dst: [(C, D)],
//! }
//!
//! #[dst]
//! #[derive(Debug)]
//! struct Test1<A, B, C, D> {
//!     a: usize,
//!     t: Test<A, B, C, D>,
//! }
//!
//! let t = TestInit {
//!     a: 1usize,
//!     b: 1u8,
//!     c: 1u8,
//!     dst: Slice::iter_init(3, (0..).map(|i| (i as u8, i as usize))),
//! };
//! let u = Test1Init { a: 1usize, t };
//! let a = Box::emplace(u);
//! assert_eq!(a.a,1usize);
//! assert_eq!(a.t.a,1);
//! assert_eq!(a.t.b,1);
//! assert_eq!(a.t.c,1);
//! assert_eq!(a.t.dst,[(0,0),(1,1),(2,2)]);
//!
//! ```
#![feature(ptr_metadata)]
#![feature(unsize)]
#![feature(alloc_layout_extra)]
#![feature(allocator_api)]
#![feature(return_position_impl_trait_in_trait)]

pub mod alloc;

pub use dst_init_macros as macros;
pub use macros::dst;
use std::alloc::Layout;
use std::marker::{PhantomData, Unsize};
use std::ptr::{null, NonNull, Pointee};
use std::{mem, ptr};
use std::rc::Rc;
use std::sync::Arc;

type Metadata<T> = <T as Pointee>::Metadata;

#[inline(always)]
const fn metadata_of<T: Unsize<Dyn>, Dyn: ?Sized>() -> Metadata<Dyn> {
    let null: *const T = null();
    let dyn_null = null as *const Dyn;
    ptr::metadata(dyn_null)
}

pub trait Initializer<DstInit: EmplaceInitializer> {
    type Init;
}

pub type Init<T, DstInit> = <T as Initializer<DstInit>>::Init;

/// An abstract interface for all emplace initializer
pub trait EmplaceInitializer {
    type Output: ?Sized;
    /// Layout of the type
    fn layout(&mut self) -> Layout;
    /// Emplace the type in given memory
    fn emplace(self, ptr: NonNull<u8>) -> NonNull<Self::Output>;
}

/// An Emplace Initializer for Slice, created by iterator and member number.
pub struct SliceIterInitializer<Iter: Iterator> {
    size: usize,
    iter: Iter,
}

impl<Iter: Iterator> SliceIterInitializer<Iter> {
    /// Create a SliceIterInitializer by iterator and member number. iterator::next will be called
    /// for given member number times
    ///
    /// # Panics
    /// would panic if iterator has less item than given member number
    #[inline(always)]
    pub fn new(size: usize, iter: Iter) -> Self {
        Self { size, iter }
    }
}

impl<Iter: Iterator> EmplaceInitializer for SliceIterInitializer<Iter> {
    type Output = [Iter::Item];

    #[inline(always)]
    fn layout(&mut self) -> Layout {
        Layout::array::<Iter::Item>(self.size).unwrap()
    }

    #[inline(always)]
    fn emplace(mut self, ptr: NonNull<u8>) -> NonNull<Self::Output> {
        unsafe {
            let mut p: *mut Iter::Item = ptr.as_ptr().cast();
            for _ in 0..self.size {
                let item = self.iter.next().unwrap();
                p.write(item);
                p = p.add(1);
            }
            mem::transmute(NonNull::slice_from_raw_parts(
                ptr.cast::<Iter::Item>(),
                self.size,
            ))
        }
    }
}

/// An Emplace Initializer for Slice, created by closure and member number.
pub struct SliceFnInitializer<Item, F: FnMut() -> Item> {
    size: usize,
    f: F,
}

impl<Item, F: FnMut() -> Item> SliceFnInitializer<Item, F> {
    /// Create a SliceIterInitializer by closure and member number. Given closure will be called
    /// for given member number times
    #[inline(always)]
    pub fn new(size: usize, f: F) -> Self {
        Self { size, f }
    }
}

impl<Item, F: FnMut() -> Item> EmplaceInitializer for SliceFnInitializer<Item, F> {
    type Output = [Item];

    #[inline(always)]
    fn layout(&mut self) -> Layout {
        Layout::array::<Item>(self.size).unwrap()
    }

    #[inline(always)]
    fn emplace(mut self, ptr: NonNull<u8>) -> NonNull<Self::Output> {
        unsafe {
            let mut p: *mut Item = ptr.as_ptr().cast();
            for _ in 0..self.size {
                let item = (self.f)();
                p.write(item);
                p = p.add(1);
            }
            NonNull::slice_from_raw_parts(ptr.cast::<Item>(), self.size)
        }
    }
}

/// An Emplace Initializer for `dyn` or `[T]` types, created by concrete type `T` or `[T;N]`.
/// For example `usize` is sized type and implemented `Debug`:
///```rust
/// use std::fmt::Debug;
/// use dst_init::{BoxExt, CoercionInitializer};
///
/// let init:CoercionInitializer<usize,dyn Debug> = CoercionInitializer::new(1usize);
/// let boxed:Box<dyn Debug> = Box::emplace(init);
/// assert_eq!(format!("{:?}",boxed),"1")
///```
pub struct CoercionInitializer<T: Unsize<U>, U: ?Sized> {
    t: T,
    phan: PhantomData<U>,
}

impl<T: Unsize<U>, U: ?Sized> CoercionInitializer<T, U> {
    #[inline(always)]
    pub fn new(t: T) -> Self {
        Self {
            t,
            phan: Default::default(),
        }
    }
    #[inline(always)]
    pub fn fallback(self) -> T {
        self.t
    }
}

impl<T: Unsize<U>, U: ?Sized> EmplaceInitializer for CoercionInitializer<T, U> {
    type Output = U;

    #[inline(always)]
    fn layout(&mut self) -> Layout {
        Layout::new::<T>()
    }

    #[inline(always)]
    fn emplace(self, ptr: NonNull<u8>) -> NonNull<Self::Output> {
        unsafe {
            let meta = metadata_of::<T, U>();
            ptr.as_ptr().cast::<T>().write(self.t);
            NonNull::from_raw_parts(ptr.cast(), meta)
        }
    }
}

/// An Emplace Initializer for sized type, created by itself.
pub struct DirectInitializer<T> {
    t: T,
}

impl<T> DirectInitializer<T> {
    #[inline(always)]
    pub fn new(t: T) -> Self {
        Self { t }
    }

    #[inline(always)]
    pub fn fallback(self) -> T {
        self.t
    }
}

impl<T> EmplaceInitializer for DirectInitializer<T> {
    type Output = T;

    #[inline(always)]
    fn layout(&mut self) -> Layout {
        Layout::new::<T>()
    }

    #[inline(always)]
    fn emplace(self, ptr: NonNull<u8>) -> NonNull<Self::Output> {
        unsafe {
            ptr.as_ptr().cast::<T>().write(self.t);
            ptr.cast()
        }
    }
}

/// Abstract for type `Box`,`Rc` and etc to allocate value by EmplaceInitializer types.
pub trait BoxExt: Sized {

    type Output: ?Sized;

    /// Allocate memory by `std::alloc::alloc()` and emplace value in it
    /// Then use Self wrap it.
    fn emplace<Init: EmplaceInitializer<Output = Self::Output>>(init: Init) -> Self;
}

impl<T: ?Sized> BoxExt for Box<T> {

    type Output = T;

    /// Allocate memory by `std::alloc::alloc()` and emplace value in it
    /// Then use `Box` wrap it.
    fn emplace<Init: EmplaceInitializer<Output = Self::Output>>(
        mut init: Init,
    ) -> Box<Self::Output> {
        unsafe {
            let layout = init.layout();
            let mem = std::alloc::alloc(layout);
            let obj = init.emplace(NonNull::new(mem).unwrap());
            Box::from_raw(obj.as_ptr())
        }
    }
}

impl<T: ?Sized> BoxExt for Rc<T> {
    type Output = T;

    /// Allocate memory by `std::alloc::alloc()` and emplace value in it
    /// Then use `Rc` wrap it.
    fn emplace<Init: EmplaceInitializer<Output = Self::Output>>(
        mut init: Init,
    ) -> Rc<Self::Output> {
        unsafe {
            let layout = init.layout();
            let mem = std::alloc::alloc(layout);
            let obj = init.emplace(NonNull::new(mem).unwrap());
            Rc::from_raw(obj.as_ptr())
        }
    }
}

impl<T: ?Sized> BoxExt for Arc<T> {
    type Output = T;

    /// Allocate memory by `std::alloc::alloc()` and emplace value in it
    /// Then use `Arc` wrap it.
    fn emplace<Init: EmplaceInitializer<Output = Self::Output>>(
        mut init: Init,
    ) -> Arc<Self::Output> {
        unsafe {
            let layout = init.layout();
            let mem = std::alloc::alloc(layout);
            let obj = init.emplace(NonNull::new(mem).unwrap());
            Arc::from_raw(obj.as_ptr())
        }
    }
}

/// pub type Slice\<T\> = \[T\];
pub type Slice<T> = [T];

/// Extension for type `[T]` to create EmplaceInitializer.
pub trait SliceExt {
    type Item;

    /// create SliceFnInitializer
    fn fn_init<F>(size: usize, f: F) -> impl EmplaceInitializer<Output = [Self::Item]>
    where
        F: FnMut() -> Self::Item;

    /// create SliceIterInitializer
    fn iter_init<Iter>(size: usize, iter: Iter) -> impl EmplaceInitializer<Output = [Self::Item]>
    where
        Iter: Iterator<Item = Self::Item>;
}

impl<T> SliceExt for Slice<T> {
    type Item = T;

    /// create SliceFnInitializer
    #[inline(always)]
    fn fn_init<F>(size: usize, f: F) -> impl EmplaceInitializer<Output = [Self::Item]>
    where
        F: FnMut() -> Self::Item,
    {
        SliceFnInitializer::new(size, f)
    }

    /// create SliceIterInitializer
    fn iter_init<Iter>(size: usize, iter: Iter) -> impl EmplaceInitializer<Output = [Self::Item]>
    where
        Iter: Iterator<Item = Self::Item>,
    {
        SliceIterInitializer::new(size, iter)
    }
}

#[cfg(test)]
pub mod test {
    use crate::{
        CoercionInitializer, DirectInitializer, EmplaceInitializer, Initializer,
        SliceFnInitializer, SliceIterInitializer,
    };
    use crate::macros::dst;
    use std::alloc;
    use std::alloc::Layout;
    use std::fmt::{Debug, Formatter};
    use std::ptr::NonNull;

    #[dst]
    #[derive(Debug)]
    struct Test<A, B, C, D> {
        a: A,
        b: B,
        c: C,
        dst: [(C, D)],
    }

    #[dst]
    #[derive(Debug)]
    struct Test1<A, B, C, D> {
        a: usize,
        t: Test<A, B, C, D>,
    }

    #[test]
    fn test() {
        let t = TestInit {
            a: 1usize,
            b: 1u8,
            c: 1u8,
            dst: SliceIterInitializer::new(3, (0..).map(|i| (i as u8, i as usize))),
        };
        let u = Test1Init { a: 1usize, t };
        let a = alloc(u);
        println!("{:?}", a)
    }

    fn alloc<O: ?Sized, Init: EmplaceInitializer<Output = O>>(mut init: Init) -> Box<O> {
        unsafe {
            let layout = init.layout();
            let ptr = alloc::alloc(layout);
            if ptr.is_null() {
                panic!("no memory");
            }
            let ptr = init.emplace(NonNull::new(ptr).unwrap());
            Box::from_raw(ptr.as_ptr())
        }
    }

    #[derive(PartialEq, Copy, Clone)]
    pub struct FstStruct {
        a: u8,
        b: usize,
        c: f64,
    }
    impl Debug for FstStruct {
        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
            write!(f, "{},{},{}", self.a, self.b, self.c)
        }
    }

    #[derive(Debug)]
    pub struct DstStruct<Data: Debug + ?Sized> {
        a: u8,
        b: usize,
        c: u8,
        d: Data,
    }

    #[test]
    fn test_direct_initializer() {
        #[inline(never)]
        fn test<T: PartialEq + Debug>(a: T, b: T) {
            let mut init = DirectInitializer::new(a);
            let layout = init.layout();
            assert_eq!(layout, Layout::new::<T>());
            let obj = alloc(init);
            assert_eq!(*obj, b);
        }

        test(12345usize, 12345usize);
        test(127u8, 127u8);
        test(456131248u32, 456131248u32);
        test(4123456789u64, 4123456789u64);
        test(1.0f64, 1.0f64);

        let a = FstStruct {
            a: 159,
            b: 47521,
            c: 12345.12345,
        };
        test(a, a);
    }

    #[test]
    fn test_coercion_initializer() {
        let a = FstStruct {
            a: 159,
            b: 47521,
            c: 12345.12345,
        };
        let init = CoercionInitializer::new(a);
        let data: Box<dyn Debug> = alloc(init);
        assert_eq!(format!("{:?}", &*data), "159,47521,12345.12345");

        let create = || DstStruct {
            a: 156,
            b: 157,
            c: 175,
            d: [1usize, 13123usize, 13123usize],
        };
        let init = CoercionInitializer::new(create());
        let data: Box<DstStruct<[usize]>> = alloc(init);
        assert_eq!(format!("{:?}", data), format!("{:?}", create()));
    }

    #[test]
    fn test_slice_fn_initializer() {
        let mut i = 0;
        let init = SliceFnInitializer::new(10065, || {
            i += 1;
            i
        });
        let data = alloc(init);
        i = 1;
        for x in data.iter() {
            assert_eq!(i, *x);
            i += 1;
        }
    }

    #[test]
    fn test_slice_iter_initializer() {
        let init = SliceIterInitializer::new(100, 0..100);
        let data = alloc(init);
        for x in 0..100 {
            assert_eq!(data[x], x)
        }
    }
}