Files
sakurac/core/traits/copyable.sakura
T
2026-10-28 22:13:49 -05:00

49 lines
2.0 KiB
Plaintext

#! @file copyable.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the copyable trait, which a type implements to be copied, and
#! `copy`, which copies a value through it, or byte for byte where nothing it
#! holds closes.
module core;
#! A type whose values can be copied, by a static function building a copy of
#! another value.
#!
#! The function is static, and gives the copy 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.
#!
#! A type that must not be copied simply does not implement this trait, which is
#! why the function gives the copy rather than an error: the type system says
#! what cannot be copied, and running out of memory stops the program, as
#! `acquire` does.
pub trait copyable {
#! Builds a copy of a value, which owns copies of whatever the value owns.
#! @param other The value to copy.
#! @returns The copy.
def copy_of(other: &self): self;
}
#! Shortcut function for copying a value, giving the copy back.
#! @tparam T The type of the value.
#! @param src The source object to copy.
#! @returns The copy, which whatever takes it owns. A type that is `copyable` is
#! copied by its `copy_of`, and one that closes nothing byte for byte.
#! @remarks The copy is given back rather than written into a destination that
#! already exists, so that returning it writes straight into whatever
#! takes it. A type that closes, or holds what does, and is not
#! `copyable` is an error where it is copied, since its bytes would
#! share what it closes, and both copies would close it.
pub def copy<T>(src: &T): T {
if const T is copyable {
return T::copy_of(src);
}
if const T is closeable {
compile_error("`copy` copies a value that closes, or holds one that does, only through `copyable`, which this type does not implement.");
}
return src;
}