#! @file moveable.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the moveable trait, which a type implements to move what it holds #! into a new value, and `move`, which moves a value through it, or byte for #! byte. module core; #! Defines that a type or generic must conform to being moveable, where the data #! of one object is handed to a new one and the source left empty. #! #! The function is static, and gives the moved value back rather than filling a #! destination that already exists, so that returning it writes straight into #! whatever takes it and nothing throwaway is built on the way. #! #! The source is `&mut` because a move empties it, which is the whole difference #! between this and `copyable`. What it leaves is valid but empty rather than #! dead, so closing it afterwards is harmless. pub trait moveable { #! Builds a value from what another holds, leaving the other empty. #! @param other The value to move from, which is left empty but valid. #! @returns The new value, holding what the other held. def move_of(other: &mut self): self; } #! Moves a value out of where it stands, leaving it empty. #! @tparam T The type of the value. #! @param src The value to move from, which holds nothing after. #! @returns The moved value, which whatever takes it owns. A type that is #! `moveable` is moved by its `move_of`, and any other byte for byte. #! @remarks The source is left valid but empty rather than dead, so closing it #! afterwards is harmless: one that closes, or holds what does, is #! zeroed. Plain data, which nothing closes, is left as it was. pub def move(src: &mut T): T { if const T is moveable { return T::move_of(src); } # Plain data, which nothing closes, is copied as it is. if const !(T is closeable) { return src; } # Fallback: read the value out byte for byte, then leave the source zeroed, so it # is not closed twice: by a store of each word where it is one to four words, as # most that close are, and by `memset` otherwise. val made := bits_of(src as *T); val words := src as *mut u64; if const size_of::() == 8 { words[0] = 0; } else if const size_of::() == 16 { words[0] = 0; words[1] = 0; } else if const size_of::() == 24 { words[0] = 0; words[1] = 0; words[2] = 0; } else if const size_of::() == 32 { words[0] = 0; words[1] = 0; words[2] = 0; words[3] = 0; } else { memset(src as *mut u8, 0, size_of::()); } return made; } # The value a pointer points at, byte for byte. A `return` hands over what a pointer # points at without emptying it, so the caller decides what is left there. def bits_of(from: *T): T { return from[0]; }