my_box 0.2.3

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
//! # MyBox
//!
//! A small, practical reimplementation of `Box<T>` in safe-Rust style.
//!
//! This crate does one thing: it moves a value onto the heap, hands you a
//! pointer-sized handle, and cleans up when you're done. Nothing fancy — just
//! enough to be useful in real code and to show how the standard `Box<T>`
//! works under the hood.
//!
//! ```rust
//! use my_box::MyBox;
//!
//! let num = MyBox::new(42);
//! assert_eq!(*num, 42);
//!
//! let player = MyBox::new(String::from("Ryu"));
//! println!("{}", *player);
//! ```
//!
//! ## Why does this exist?
//!
//! Most Rust code never needs this — `std::boxed::Box` already does all of this
//! and more, with optimizations the compiler can reason about. This crate is
//! here because sometimes you want to see the full picture: `alloc`, `write`,
//! `drop_in_place`, `dealloc`, and the trait glue that makes the `*` operator
//! work the way you expect.
//!
//! If you're writing production code, use `Box<T>`. If you're learning, or
//! you need a `try_new` that doesn't panic on OOM, this might be useful.
//!
//! ## 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);
//! ```
//!
//! ## What's included
//!
//! - **Normal heap allocation** — `MyBox::new` and `MyBox::try_new`
//! - **ZST support** — won't crash on `()` or `PhantomData`
//! - **Recursive types** — `Box<List<T>>` works because the indirection is a known size
//! - **Trait objects** — `Box<dyn Trait>` is just a fat pointer, works fine
//! - **Thread safety** — `Send`/`Sync` forwarded to `T`
//! - **Full access** — `Deref`, `DerefMut`, `AsRef`, `AsMut`, `Borrow`, `BorrowMut`
//! - **Standard traits** — `Clone`, `PartialEq`, `PartialOrd`, `Ord`, `Hash`, `Debug`, `Display`, `Default`, `From`
//! - **Raw pointer interop** — `into_raw` / `from_raw` for when you need to cross an unsafe boundary

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};

#[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 {}

#[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> {
    #[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("allocation failed: out of memory");
            ptr::write(non_null_ptr.as_ptr(), value);
            Self { ptr: non_null_ptr }
        }
    }

    #[must_use = "ignoring the 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 })
        }
    }

    pub fn as_ptr(&self) -> *mut T {
        self.ptr.as_ptr()
    }

    pub fn into_raw(self) -> *mut T {
        let raw = self.ptr.as_ptr();
        std::mem::forget(self);
        raw
    }

    pub unsafe fn from_raw(raw: *mut T) -> Self {
        Self {
            ptr: NonNull::new_unchecked(raw),
        }
    }

    pub fn into_inner(self) -> T {
        unsafe {
            let value = ptr::read(self.ptr.as_ptr());
            let layout = Layout::new::<T>();
            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("allocation failed: out of memory (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());
    }
}