#! @file owning.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the owning trait, which a type names to own what it holds and close it #! where its values go away, and the function closing a value where it stands. module core; #! Defines that a type owns what it holds, such as memory or a file, and #! disposes of it in `close`. A value of a type naming `owning` is closed where #! its scope ends, as RAII does, so that something like an allocator or #! collection has released its data by the time it goes away. #! #! A type is owning only by naming the trait, so a `close` meant to be called by #! hand never becomes a destructor by accident. A reference to an owning value #! owns nothing, so it is never owning, though `close` is called through it. #! #! Unlike `copyable` and `moveable`, nothing fails where a type is not owning: #! generic code asks `if const T is owning`, or calls `close`, which closes #! whatever is given as its scope ending would. pub trait owning { #! Disposes of what the value owns, as its scope ending does. #! @param this The value to close, which should be left empty, so closing it #! again does nothing. def close(&mut this): void; } #! Closes a value where it stands, as its scope ending would: through its own #! `close` where it is `owning`, then each value it holds that closes, such as #! a `string` in a field, the last first. A value that closes nothing is left #! alone. #! @tparam T The type of the value. #! @param value The value to close, which is left empty. #! @remarks Containers close their elements with it, so that an element holding #! something that closes is closed as a local holding it would be. pub def close(value: &mut T): void { if const T is closeable { close_where_it_is(value); memset(value as *mut u8, 0, size_of::()); } } # Closes a value where it is, as the compiler closes a local whose scope ends: # its own `close` where it is `owning`, then each field that closes, the last # first, or the field a union holds, or each element of a fixed array. @intrinsic def close_where_it_is(value: &mut T): void;