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
use crate::assert::StaticAssertions;
use crate::mem::Memory;
use crate::ptr::write_addr;
use crate::raw::FatPointer;

use core::any::Any;
use core::fmt;
use core::mem::{self, ManuallyDrop, MaybeUninit};
use core::ops;
use core::ptr;

#[cfg(feature = "coerce_unsized")]
use core::marker::Unsize;
#[cfg(feature = "coerce_unsized")]
use core::ops::CoerceUnsized;

/// A box that exists entirely on the stack.
pub struct BoxS<T, M>
where
    T: ?Sized,
    M: Memory,
{
    buf: ManuallyDrop<M>,
    ptr: *mut T,
}

/// Box a value on the stack.
///
/// This macro exists as DST coercion currently requires a nightly compiler.
/// It will be deprecated once this hits stable.
///
/// For more info, see [#27732].
///
/// Note that just like [`BoxS::new`] the space and alignment demands for the
/// box are evaluated at compile time. Attempting to use this macro to construct
/// a boxed value with invalid backing storage will result in a compilation
/// failure.
///
/// [#27732]: https://github.com/rust-lang/rust/issues/27732
/// [`BoxS::new`]: struct.BoxS.html#method.new
///
/// # Examples
///
/// Boxing a value on the stack, coercing to a DST:
///
/// ```
/// use core::any::Any;
/// use no_alloc::{boxed_s, BoxS};
///
/// let boxed: BoxS<dyn Any, [usize; 1]> = boxed_s!(0_isize);
/// ```
#[macro_export]
macro_rules! boxed_s {
    ($val:expr) => {{
        let mut val = $val;
        let ptr = &mut val as *mut _;
        let boxed = unsafe { $crate::BoxS::__new(&mut val, ptr) };
        ::core::mem::forget(val);
        boxed
    }};
}

/*
    impl BoxS
*/

#[cfg(feature = "coerce_unsized")]
impl<T, U, M> CoerceUnsized<BoxS<U, M>> for BoxS<T, M>
where
    T: ?Sized + Unsize<U>,
    U: ?Sized,
    M: Memory,
{
}

impl<T, M> ops::Deref for BoxS<T, M>
where
    T: ?Sized,
    M: Memory,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        unsafe { &*self.as_ptr() }
    }
}

impl<T, M> ops::DerefMut for BoxS<T, M>
where
    T: ?Sized,
    M: Memory,
{
    fn deref_mut(&mut self) -> &mut <Self as ops::Deref>::Target {
        unsafe { &mut *self.as_mut_ptr() }
    }
}

impl<T, M> Drop for BoxS<T, M>
where
    T: ?Sized,
    M: Memory,
{
    fn drop(&mut self) {
        unsafe {
            ptr::drop_in_place(self.as_mut_ptr());
        }
    }
}

impl<T, M> fmt::Debug for BoxS<T, M>
where
    T: ?Sized + fmt::Debug,
    M: Memory,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <T as fmt::Debug>::fmt(self, f)
    }
}

impl<T, M> fmt::Display for BoxS<T, M>
where
    T: ?Sized + fmt::Display,
    M: Memory,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <T as fmt::Display>::fmt(self, f)
    }
}

impl<T, M> fmt::Pointer for BoxS<T, M>
where
    T: ?Sized,
    M: Memory,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.as_ptr().fmt(f)
    }
}

impl<T, M> BoxS<T, M>
where
    M: Memory,
{
    /// Acquires memory on the stack and places `x` into it.
    ///
    /// The acquired memory is backed by `M`. If the size or alignment of `T`
    /// is greater than that of `M` the box cannot be constructed. This will
    /// reuslt in a compile fail.
    ///
    /// If `T` is zero-sized then no memory is required; `M` may also be zero
    /// sized in this case.
    ///
    /// # Examples
    ///
    /// Creating a boxed value:
    ///
    /// ```
    /// use no_alloc::BoxS;
    ///
    /// let boxed: BoxS<isize, [usize; 1]> = BoxS::new(0);
    /// ```
    ///
    /// Creating a boxed ZST (zero-sized type):
    ///
    /// ```
    /// use no_alloc::BoxS;
    ///
    /// let boxed: BoxS<(), [usize; 0]> = BoxS::new(());
    /// ```
    ///
    /// Failing to create a boxed value due to size error (this results in a
    /// _compile_ error):
    ///
    /// ```compile_fail
    /// use no_alloc::BoxS;
    ///
    /// let _impossible = BoxS::<isize, [u8; 0]>::new(0);
    /// ```
    ///
    /// Failing to create a boxed value due to alignment error (this results
    /// in a _compile_ error):
    ///
    /// ```compile_fail
    /// use core::mem::size_of;
    /// use no_alloc::BoxS;
    ///
    /// let _impossible = BoxS::<isize, [u8; size_of::<isize>()]>::new(0);
    /// ```
    ///
    /// Coercing to a boxed DST (dynamically-sized type) (requires the
    /// `coerce_unsized` feature):
    ///
    /// ```
    /// use core::any::Any;
    /// use no_alloc::BoxS;
    ///
    /// # #[cfg(feature = "coerce_unsized")]
    /// # {
    /// let boxed: BoxS<dyn Any, [usize; 1]> = BoxS::new(0_isize);
    /// # }
    /// ```
    pub fn new(x: T) -> Self {
        boxed_s!(x)
    }
}

impl<M> BoxS<dyn Any + 'static, M>
where
    M: Memory,
{
    /// Attempts to downcast the box to a concrete type.
    ///
    /// # Examples
    ///
    /// ```
    /// use core::any::Any;
    /// use core::fmt;
    ///
    /// use no_alloc::{BoxS, Memory};
    ///
    /// fn write_if_str<W: fmt::Write, M: Memory>(
    ///     mut wtr: W,
    ///     boxed: BoxS<dyn Any + 'static, M>
    /// ) -> fmt::Result {
    ///     if let Ok(s) = boxed.downcast::<&str>() {
    ///         wtr.write_str(&s)?;
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub fn downcast<T>(self) -> Result<BoxS<T, M>, Self>
    where
        T: Any,
    {
        if self.is::<T>() {
            Ok(unsafe { self.downcast_unchecked() })
        } else {
            Err(self)
        }
    }
}

impl<M> BoxS<dyn Any + Send + 'static, M>
where
    M: Memory,
{
    /// Attempts to downcast the box to a concrete type.
    ///
    /// # Examples
    ///
    /// ```
    /// use core::any::Any;
    /// use core::fmt;
    ///
    /// use no_alloc::{BoxS, Memory};
    ///
    /// fn write_if_str<W: fmt::Write, M: Memory>(
    ///     mut wtr: W,
    ///     boxed: BoxS<dyn Any + Send + 'static, M>
    /// ) -> fmt::Result {
    ///     if let Ok(s) = boxed.downcast::<&str>() {
    ///         wtr.write_str(&s)?;
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub fn downcast<T>(self) -> Result<BoxS<T, M>, Self>
    where
        T: Any,
    {
        if self.is::<T>() {
            Ok(unsafe { self.downcast_unchecked() })
        } else {
            Err(self)
        }
    }
}

impl<T, M> BoxS<T, M>
where
    T: ?Sized,
    M: Memory,
{
    #[doc(hidden)]
    pub unsafe fn __new<U>(val: &mut U, ptr: *mut T) -> Self {
        let _ = StaticAssertions::<T, U, M>::new();
        BoxS::<T, M>::from_ptr(val, FatPointer::from_raw(ptr).map(|fat| fat.meta))
    }
}

impl<T, M> BoxS<T, M>
where
    T: ?Sized,
    M: Memory,
{
    unsafe fn from_ptr<U>(ptr_u: &U, extra: Option<usize>) -> Self
    where
        U: ?Sized,
    {
        let mut buf: MaybeUninit<M> = MaybeUninit::uninit();
        let dst: *mut u8 = buf.as_mut_ptr() as *mut _;
        ptr::copy_nonoverlapping(
            ptr_u as *const _ as *const u8,
            dst,
            mem::size_of_val::<U>(&ptr_u),
        );

        let mut ptr = MaybeUninit::zeroed();
        let ptr_ptr: *mut usize = ptr.as_mut_ptr() as *mut _;
        if let Some(addr) = extra {
            ptr_ptr.add(1).write(addr);
        }

        Self {
            buf: ManuallyDrop::new(buf.assume_init()),
            ptr: ptr.assume_init(),
        }
    }

    fn as_ptr(&self) -> *const T {
        write_addr(self.ptr, &*self.buf as *const M as _)
    }

    fn as_mut_ptr(&mut self) -> *mut T {
        write_addr(self.ptr, &mut *self.buf as *mut M as _)
    }

    unsafe fn downcast_unchecked<U: Any>(mut self) -> BoxS<U, M> {
        let Self { ref mut buf, ptr } = self;
        let buf = ManuallyDrop::new(ManuallyDrop::take(buf));
        mem::forget(self);
        BoxS {
            buf,
            ptr: ptr as *mut _,
        }
    }
}

unsafe impl<T, M> Send for BoxS<T, M>
where
    T: ?Sized + Send,
    M: Memory,
{
}

unsafe impl<T, M> Sync for BoxS<T, M>
where
    T: ?Sized + Sync,
    M: Memory,
{
}

/*
    Unit tests
*/

#[cfg(test)]
mod tests {
    use super::*;

    use core::any::Any;
    use core::sync::atomic::{AtomicBool, Ordering};

    #[test]
    fn smoke() {
        let mut boxed = BoxS::<usize, [usize; 1]>::new(0);
        assert_eq!(*boxed, 0);
        *boxed = 1;
        assert_eq!(*boxed, 1);
    }

    #[test]
    fn boxed_s_macro() {
        let _boxed: BoxS<dyn Any, [usize; 1]> = boxed_s!(0_usize);
    }

    #[cfg(feature = "coerce_unsized")]
    #[test]
    fn coerce_unsized() {
        let _boxed: BoxS<dyn Any, [usize; 1]> = BoxS::new(0_usize);
    }

    #[test]
    fn zst() {
        let mut boxed = BoxS::<(), [usize; 0]>::new(());
        assert_eq!(*boxed, ());
        *boxed = ();
    }

    #[test]
    fn drop() {
        struct Foo<'a>(&'a AtomicBool);
        impl Drop for Foo<'_> {
            fn drop(&mut self) {
                self.0.store(true, Ordering::Relaxed);
            }
        }

        let dropped = AtomicBool::new(false);
        let foo = Foo(&dropped);
        let boxed = BoxS::<_, [usize; 1]>::new(foo);
        assert!(!dropped.load(Ordering::Relaxed));
        mem::drop(boxed);
        assert!(dropped.load(Ordering::Relaxed));
    }

    #[test]
    fn any() {
        let boxed: BoxS<dyn Any, [usize; 1]> = boxed_s!(0_usize);
        assert_eq!(*boxed.downcast::<usize>().ok().unwrap(), 0);
        let boxed: BoxS<dyn Any + Send, [usize; 1]> = boxed_s!(0_usize);
        assert_eq!(*boxed.downcast::<usize>().ok().unwrap(), 0);
    }

    #[test]
    fn slice() {
        let boxed: BoxS<[u8], [usize; 1]> = boxed_s!([0_u8; 4]);
        assert_eq!(&*boxed, &[0_u8; 4][..]);
    }
}