#! @file box.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains `box`, one value on the heap, which it owns alone, as C++'s #! `unique_ptr` and Rust's `Box`: for a value that outlives the scope making it #! without being copied, one too large for a frame, or a structure linking to #! more of itself. module core; #! One value on the heap, which the box owns alone and closes where the box #! closes. #! #! A box is one word, the value's address, which is never null, so a #! `maybe>` is one word too, holding `nothing` where the address is #! null. Moving a box moves the address, never the value, and leaves the box #! moved from empty: closing it again does nothing, and reaching its value #! reaches through `null`. #! @tparam T What it holds. pub struct box : owning, moveable { var _at: &mut T; } #! Moves a value to the heap. #! @param value The value, which the box then owns. #! @returns The box. pub def box::new(value: T): box { val size := size_of::(); val at := allocate_for::(size == 0 ? 1 : size) as *mut T; at[0] = move(&mut value); return box:: { _at = through(at) }; } #! Lends the value a box holds. #! @param this The box. #! @returns The value, good while the box holds it. pub def box::get(&this): &T { return this._at; } #! Lends the value a box holds, to be changed. #! @param this The box. #! @returns The value, good while the box holds it. pub def box::get(&mut this): &mut T { return this._at; } #! Whether a box holds a value, which one moved from or taken from does not. #! @param this The box. #! @returns Whether it does. pub def box::holds(&this): bool { return this._at as *T != null; } #! Moves the value out of a box, giving back its memory. #! @param this The box, which is empty after. #! @returns The value. pub def box::take(&mut this): T { val at := this._at as *mut T; var made := move(through(at)); raw_release(at as *mut u8); (this as *mut u64)[0] = 0; return made; } #! Closes the value a box holds and gives back its memory. #! @param this The box, which is empty after, so closing it again does #! nothing. pub def box::close(&mut this): void { val at := this._at as *mut T; return if at == null; (this as *mut u64)[0] = 0; close(through(at)); raw_release(at as *mut u8); } #! Moves a box, leaving the one moved from empty. #! @param other The box to move from. #! @returns The box holding what it held. pub def box::move_of(other: &mut box): box { val made := box:: { _at = other._at }; (other as *mut u64)[0] = 0; return made; }