my_box 0.2.2

An educational, zero-dependency Rust implementation of a heap-allocated smart pointer (MyBox<T>), mirroring std::boxed::Box<T> for learning purposes.
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
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
//! # MyBox
//!
//! A zero-dependency, educational Rust library that reimplements `Box<T>` from
//! first principles.
//!
//! `MyBox<T>` is a heap-allocated smart pointer with single ownership. It
//! provides automatic deallocation via `Drop`, transparent access via `Deref`,
//! deep cloning via `Clone`, and full forwarding of comparison, ordering,
//! hashing, and formatting to `T`.
//!
//! ## Quick Start
//!
//! ```
//! use my_box::MyBox;
//!
//! let num = MyBox::new(42);
//! assert_eq!(*num, 42);
//!
//! let player = MyBox::new(String::from("Ryu"));
//! println!("{}", *player);
//! ```
//!
//! ## Examples
//!
//! ### Recursive type via `Box`
//!
//! ```rust
//! use my_box::MyBox;
//!
//! #[derive(Debug, PartialEq)]
//! enum List<T> {
//!     Cons(T, Box<List<T>>),
//!     Nil,
//! }
//!
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! ```
//!
//! ## Features
//!
//! - **Zero-sized type (ZST) safe**: `MyBox::new(())` uses `NonNull::dangling()`.
//! - **Recursive data structures**: Use `Box<List<T>>` to break infinite size cycles.
//! - **Trait objects**: Combine with `Box<dyn Trait>` for runtime polymorphism.
//! - **Thread safe**: Implements `Send`/`Sync` when `T` does.
//! - **Fallible allocation**: `try_new` returns `Result` instead of panicking on OOM.
//! - **Consume to inner value**: `into_inner` extracts `T` from `MyBox<T>`.

use std::alloc::{alloc, dealloc, Layout};
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::{Deref, DerefMut};
use std::ptr::{self, NonNull};

/// Error type for heap allocation failures.
///
/// Returned by [`MyBox::try_new`] when the global allocator cannot satisfy
/// the allocation request. Currently `MyBox::new` panics on OOM, but
/// `try_new` lets callers handle the failure gracefully.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct AllocError;

impl fmt::Display for AllocError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "heap allocation failed (out of memory)")
    }
}

impl std::error::Error for AllocError {}

/// A heap-allocated smart pointer with single ownership.
///
/// `MyBox<T>` is the educational equivalent of `Box<T>` from the standard
/// library. It owns its heap allocation exclusively and frees it automatically
/// when dropped.
///
/// # Zero-Sized Types (ZSTs)
///
/// `MyBox::new(())` is handled safely by storing a `NonNull::dangling()` pointer,
/// which is valid because ZSTs have no data to read or write.
///
/// # Thread Safety
///
/// `MyBox<T>` implements `Send` when `T: Send` and `Sync` when `T: Sync`,
/// matching the behavior of `Box<T>`.
///
/// # Memory Layout
///
/// `MyBox<T>` is `#[repr(transparent)]`, guaranteeing the same ABI as `*mut T`.
/// This allows safe transmutation and correct FFI interop.
#[doc(alias = "heap")]
#[doc(alias = "box")]
#[doc(alias = "pointer")]
#[repr(transparent)]
#[must_use = "MyBox allocates on the heap and must be stored or explicitly dropped to avoid a leak"]
pub struct MyBox<T> {
    ptr: NonNull<T>,
}

unsafe impl<T: Send> Send for MyBox<T> {}
unsafe impl<T: Sync> Sync for MyBox<T> {}

impl<T> MyBox<T> {
    /// Heap-allocate a value of type `T` and return an owning smart pointer.
    ///
    /// # Panics
    ///
    /// Panics if the global allocator returns a null pointer (out-of-memory).
    ///
    /// # Examples
    ///
    /// ```
    /// use my_box::MyBox;
    ///
    /// let num = MyBox::new(42);
    /// assert_eq!(*num, 42);
    ///
    /// let s = MyBox::new(String::from("hello"));
    /// assert_eq!(s.len(), 5);
    /// ```
    #[must_use]
    pub fn new(value: T) -> Self {
        let layout = Layout::new::<T>();
        if layout.size() == 0 {
            return Self {
                ptr: NonNull::dangling(),
            };
        }
        unsafe {
            let raw_ptr = alloc(layout) as *mut T;
            let non_null_ptr = NonNull::new(raw_ptr)
                .expect("Fatal: out of memory on the heap");
            ptr::write(non_null_ptr.as_ptr(), value);
            Self { ptr: non_null_ptr }
        }
    }

    /// Attempt to heap-allocate a value of type `T`, returning `Err(AllocError)`
    /// instead of panicking if the allocator returns a null pointer.
    ///
    /// # Examples
    ///
    /// ```
    /// use my_box::MyBox;
    ///
    /// let num = MyBox::try_new(42).expect("allocation should succeed");
    /// assert_eq!(*num, 42);
    /// ```
    #[must_use = "ignoring the returned Result leaks the allocation"]
    pub fn try_new(value: T) -> Result<Self, AllocError> {
        let layout = Layout::new::<T>();
        if layout.size() == 0 {
            return Ok(Self {
                ptr: NonNull::dangling(),
            });
        }
        unsafe {
            let raw_ptr = alloc(layout) as *mut T;
            let non_null_ptr = NonNull::new(raw_ptr).ok_or(AllocError)?;
            ptr::write(non_null_ptr.as_ptr(), value);
            Ok(Self { ptr: non_null_ptr })
        }
    }

    /// Returns a raw pointer to the heap allocation without taking ownership.
    ///
    /// # Examples
    ///
    /// ```
    /// use my_box::MyBox;
    ///
    /// let b = MyBox::new(10);
    /// let ptr = b.as_ptr();
    /// assert_eq!(unsafe { *ptr }, 10);
    /// ```
    pub fn as_ptr(&self) -> *mut T {
        self.ptr.as_ptr()
    }

    /// Consumes the `MyBox<T>` and returns a raw pointer to the heap allocation.
    ///
    /// After calling this function, the caller is responsible for the memory
    /// previously managed by the `MyBox<T>`. The only way to restore the
    /// `MyBox<T>` is via [`MyBox::from_raw`].
    ///
    /// # Examples
    ///
    /// ```
    /// use my_box::MyBox;
    ///
    /// let b = MyBox::new(42);
    /// let ptr = b.into_raw();
    /// let recovered = unsafe { MyBox::from_raw(ptr) };
    /// assert_eq!(*recovered, 42);
    /// ```
    pub fn into_raw(self) -> *mut T {
        let raw = self.ptr.as_ptr();
        std::mem::forget(self);
        raw
    }

    /// Reconstructs a `MyBox<T>` from a raw pointer previously returned by
    /// [`MyBox::into_raw`].
    ///
    /// # Safety
    ///
    /// - `raw` must be non-null and correctly aligned for `T`.
    /// - `raw` must have been allocated by `MyBox::into_raw` (or equivalent).
    /// - [`MyBox::from_raw`] must be called exactly once per raw pointer.
    ///   Failing to uphold these invariants will cause undefined behavior.
    ///
    /// # Examples
    ///
    /// ```
    /// use my_box::MyBox;
    ///
    /// let b = MyBox::new(42);
    /// let ptr = b.into_raw();
    /// let recovered = unsafe { MyBox::from_raw(ptr) };
    /// assert_eq!(*recovered, 42);
    /// ```
    pub unsafe fn from_raw(raw: *mut T) -> Self {
        Self {
            ptr: NonNull::new_unchecked(raw),
        }
    }

    /// Consumes the `MyBox<T>` and returns the inner value `T`.
    ///
    /// The heap allocation is deallocated after the inner value is moved out.
    ///
    /// # Examples
    ///
    /// ```
    /// use my_box::MyBox;
    ///
    /// let b = MyBox::new(String::from("hello"));
    /// let inner: String = b.into_inner();
    /// assert_eq!(inner, "hello");
    /// ```
    pub fn into_inner(self) -> T
    where
        T: Sized,
    {
        let layout = Layout::new::<T>();
        unsafe {
            let value = ptr::read(self.ptr.as_ptr());
            if layout.size() > 0 {
                dealloc(self.ptr.as_ptr() as *mut u8, layout);
            }
            std::mem::forget(self);
            value
        }
    }
}

impl<T> Drop for MyBox<T> {
    fn drop(&mut self) {
        let layout = Layout::new::<T>();
        unsafe {
            ptr::drop_in_place(self.ptr.as_ptr());
            if layout.size() > 0 {
                dealloc(self.ptr.as_ptr() as *mut u8, layout);
            }
        }
    }
}

impl<T> Deref for MyBox<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        unsafe { self.ptr.as_ref() }
    }
}

impl<T> DerefMut for MyBox<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { self.ptr.as_mut() }
    }
}

impl<T: Clone> Clone for MyBox<T> {
    fn clone(&self) -> Self {
        let layout = Layout::new::<T>();
        if layout.size() == 0 {
            return Self {
                ptr: NonNull::dangling(),
            };
        }
        unsafe {
            let new_raw = alloc(layout) as *mut u8;
            let new_non_null = NonNull::new(new_raw)
                .expect("Fatal: out of memory on the heap (clone)");
            let dest = new_non_null.as_ptr() as *mut T;
            ptr::write(dest, (**self).clone());
            Self { ptr: NonNull::new_unchecked(dest) }
        }
    }
}

impl<T: Default> Default for MyBox<T> {
    fn default() -> Self {
        MyBox::new(T::default())
    }
}

impl<T> From<T> for MyBox<T> {
    fn from(t: T) -> Self {
        MyBox::new(t)
    }
}

impl<T: PartialEq> PartialEq for MyBox<T> {
    fn eq(&self, other: &Self) -> bool {
        PartialEq::eq(&**self, &**other)
    }
    fn ne(&self, other: &Self) -> bool {
        PartialEq::ne(&**self, &**other)
    }
}

impl<T: Eq> Eq for MyBox<T> {}

impl<T: PartialOrd> PartialOrd for MyBox<T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        PartialOrd::partial_cmp(&**self, &**other)
    }
    fn lt(&self, other: &Self) -> bool {
        PartialOrd::lt(&**self, &**other)
    }
    fn le(&self, other: &Self) -> bool {
        PartialOrd::le(&**self, &**other)
    }
    fn gt(&self, other: &Self) -> bool {
        PartialOrd::gt(&**self, &**other)
    }
    fn ge(&self, other: &Self) -> bool {
        PartialOrd::ge(&**self, &**other)
    }
}

impl<T: Ord> Ord for MyBox<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        Ord::cmp(&**self, &**other)
    }
}

impl<T: Hash> Hash for MyBox<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        (**self).hash(state);
    }
}

impl<T: fmt::Debug> fmt::Debug for MyBox<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<T: fmt::Display> fmt::Display for MyBox<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

impl<T> AsRef<T> for MyBox<T> {
    fn as_ref(&self) -> &T {
        &**self
    }
}

impl<T> AsMut<T> for MyBox<T> {
    fn as_mut(&mut self) -> &mut T {
        &mut **self
    }
}

impl<T> std::borrow::Borrow<T> for MyBox<T> {
    fn borrow(&self) -> &T {
        &**self
    }
}

impl<T> std::borrow::BorrowMut<T> for MyBox<T> {
    fn borrow_mut(&mut self) -> &mut T {
        &mut **self
    }
}

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

    #[test]
    fn basic_allocation_and_deref() {
        let num = MyBox::new(42);
        assert_eq!(*num, 42);
    }

    #[test]
    fn mutation_through_deref() {
        let mut num = MyBox::new(10);
        *num += 20;
        assert_eq!(*num, 30);
    }

    #[test]
    fn zero_sized_type_allocation() {
        let zst = MyBox::new(());
        assert_eq!(*zst, ());
    }

    #[test]
    fn struct_field_access_via_autoderef() {
        #[derive(Debug, Clone, PartialEq)]
        struct Character {
            name: String,
            hp: u32,
        }
        let hero = MyBox::new(Character {
            name: String::from("Aldric"),
            hp: 100,
        });
        assert_eq!(hero.name, "Aldric");
        assert_eq!(hero.hp, 100);
    }

    #[test]
    fn method_call_via_autoderef() {
        #[derive(Debug, PartialEq)]
        struct TaskList(Vec<i32>);
        impl TaskList {
            fn sort(&mut self) {
                self.0.sort();
            }
        }
        let mut tasks = MyBox::new(TaskList(vec![3, 1, 4, 1, 5]));
        tasks.sort();
        assert_eq!(tasks.0, vec![1, 1, 3, 4, 5]);
    }

    #[test]
    fn deep_clone_produces_independent_copy() {
        let original = MyBox::new(vec![1, 2, 3]);
        let mut cloned = original.clone();
        assert_eq!(*original, *cloned);
        cloned.push(4);
        assert_eq!(*original, vec![1, 2, 3]);
        assert_eq!(*cloned, vec![1, 2, 3, 4]);
    }

    #[test]
    fn drop_frees_memory() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;
        let drop_count = Arc::new(AtomicUsize::new(0));
        struct DropCounter(Arc<AtomicUsize>);
        impl Drop for DropCounter {
            fn drop(&mut self) {
                self.0.fetch_add(1, Ordering::SeqCst);
            }
        }
        {
            let counter = MyBox::new(DropCounter(drop_count.clone()));
            assert_eq!(drop_count.load(Ordering::SeqCst), 0);
            drop(counter);
        }
        assert_eq!(drop_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn partial_eq_and_ord() {
        let a = MyBox::new(5);
        let b = MyBox::new(10);
        let c = MyBox::new(5);
        assert_eq!(a, c);
        assert_ne!(a, b);
        assert!(a < b);
        assert!(b > a);
        assert!(a <= c);
        assert!(a >= c);
    }

    #[test]
    fn display_formatting() {
        let s = MyBox::new(String::from("hello"));
        assert_eq!(format!("{}", s), "hello");
    }

    #[test]
    fn debug_formatting() {
        let n = MyBox::new(42);
        assert_eq!(format!("{:?}", n), "42");
    }

    #[test]
    fn as_ref_and_as_mut() {
        let mut boxed = MyBox::new(vec![10, 20, 30]);
        let slice: &[i32] = boxed.as_ref();
        assert_eq!(slice, &[10, 20, 30]);
        boxed.as_mut().push(40);
        assert_eq!(boxed.as_ref(), &[10, 20, 30, 40]);
    }

    #[test]
    fn into_raw_and_from_raw_roundtrip() {
        let original = MyBox::new(128);
        let raw = original.into_raw();
        let reconstructed = unsafe { MyBox::from_raw(raw) };
        assert_eq!(*reconstructed, 128);
    }

    #[test]
    fn box_in_vec_moves_without_copying_data() {
        let v1 = MyBox::new(String::from("alpha"));
        let v2 = MyBox::new(String::from("beta"));
        let mut vec = vec![v1, v2];
        vec.sort_by(|a, b| b.as_str().cmp(a.as_str()));
        assert_eq!(vec[0].as_str(), "beta");
        assert_eq!(vec[1].as_str(), "alpha");
    }

    #[test]
    fn recursive_structure_with_box() {
        #[derive(Debug, PartialEq)]
        enum List<T> {
            Cons(T, Box<List<T>>),
            Nil,
        }
        let list: List<i32> =
            List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
        assert_eq!(
            list,
            List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))))
        );
    }

    #[test]
    fn hash_trait_works() {
        use std::collections::hash_map::DefaultHasher;
        let a = MyBox::new(7);
        let b = MyBox::new(7);
        let c = MyBox::new(9);
        let mut hasher_a = DefaultHasher::new();
        a.hash(&mut hasher_a);
        let mut hasher_b = DefaultHasher::new();
        b.hash(&mut hasher_b);
        let mut hasher_c = DefaultHasher::new();
        c.hash(&mut hasher_c);
        assert_eq!(hasher_a.finish(), hasher_b.finish());
        assert_ne!(hasher_a.finish(), hasher_c.finish());
    }

    #[test]
    fn default_trait() {
        let v: MyBox<Vec<i32>> = MyBox::default();
        assert!(v.is_empty());
    }

    #[test]
    fn from_trait_constructor() {
        let s: MyBox<String> = String::from("from trait").into();
        assert_eq!(*s, "from trait");
    }

    #[test]
    fn try_new_succeeds() {
        let num = MyBox::try_new(64).expect("allocation should succeed");
        assert_eq!(*num, 64);
    }

    #[test]
    fn try_new_zst() {
        let zst = MyBox::try_new(()).expect("zst allocation should succeed");
        assert_eq!(*zst, ());
    }

    #[test]
    fn try_new_on_heap_struct() {
        let s = MyBox::try_new(String::from("try_new"))
            .expect("string allocation should succeed");
        assert_eq!(s.len(), "try_new".len());
    }

    #[test]
    fn into_inner_returns_value() {
        let b = MyBox::new(String::from("inner"));
        let inner = b.into_inner();
        assert_eq!(inner, "inner");
    }

    #[test]
    fn into_inner_drops_heap_allocation() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);

        struct Counter {
            _id: u8,
        }
        impl Drop for Counter {
            fn drop(&mut self) {
                DROP_COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        DROP_COUNT.store(0, Ordering::SeqCst);
        let counter = MyBox::new(Counter { _id: 7 });
        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 0);
        {
            let _inner = counter.into_inner();
        }
        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn try_new_returns_err() {
        assert!(MyBox::<i32>::try_new(0).is_ok());
    }
}