Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.44.0

0.44.0 / src / std / interop / result.lucb

#==============================================================================================
#
#   result - Owned native values and outcomes
#
#   DESCRIPTION:
#       A native value with explicit backing storage, and a callback's success value or failure
#       text, each carrying an explicit owner a Base caller releases.
#
#==============================================================================================

## A native value with explicit backing storage. The value may borrow that storage;
## clone retains it, release ends the obligation. Plain/static values need no owner.
pub struct Owned[T]:
    ## The native value, which may borrow the owner's storage.
    pub let value: T
    ## The object backing the value, or none for a plain value.
    pub let owner: ownership.Object*? = none

    ## Another edge to the value's owner, when it has one.
    pub func clone() -> Owned[T]:
        if let owner = self.owner:
            _ = ownership.retain(owner)
        return self

    ## End this value's obligation to its owner.
    pub func release():
        if let owner = self.owner:
            ownership.release_held(owner)

    ## Visit the owner as a strong reference.
    pub func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
        if let owner = self.owner:
            ownership.check_thread(owner)
            visit(owner, context)

let no_error: ErrorCode = ErrorCode.package(0)

## A callback's success value or failure text, each with an explicit owner. A Base
## caller can consume a failure without leaving managed error text pending anywhere.
## get borrows until release; it never transfers ownership of the contained value.
pub struct Outcome[T]:
    let result: Owned[T]?
    ## The failure code, or `package(0)` on success.
    pub let code: ErrorCode
    let message: Owned[str]?

    ## A successful outcome carrying `value`.
    pub static func success(value: Owned[T]) -> Outcome[T]:
        return Outcome[T](value, no_error, none)

    ## A failed outcome with `code` and `message`.
    pub static func failure(code: ErrorCode, message: Owned[str]) -> Outcome[T]:
        return Outcome[T](none, code, message)

    ## Whether the outcome succeeded.
    pub func is_success() -> bool:
        return self.message == none

    ## The success value, or the failure as an error.
    pub func get() -> T!:
        if let message = self.message:
            error(self.code, message.value)
        return (self.result else trap("an outcome has no result")).value

    ## A copy of the outcome, retaining its owned value or message.
    pub func clone() -> Outcome[T]:
        if let message = self.message:
            return Outcome[T].failure(self.code, message.clone())
        return Outcome[T].success((self.result else trap("an outcome has no result")).clone())

    ## Release the outcome's owned value or message.
    pub func release():
        if let result = self.result:
            result.release()
        if let message = self.message:
            message.release()

    ## Visit the outcome's strong references.
    pub func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
        if let result = self.result:
            result.trace(visit, context)
        if let message = self.message:
            message.trace(visit, context)

func drop_text(object: ownership.Object*):
    _ = object

func trace_text(object: ownership.Object*, visit: func(ownership.Object*, void*) -> unit, context: void*):
    _ = object

var text_info: ownership.Info = ownership.Info(name = "native owned text", size = 0,
                                               finish = none, drop = drop_text, trace = trace_text)

## Own a copy of text from a temporary buffer or a native error before it expires.
pub func copy_text(value: str) -> Owned[str]!:
    let size = memory.size_of(ownership.Object) +? value.length else error(memory.exhausted, "owned text is too large")
    let owner = try ownership.reserve(&text_info, size)
    let bytes = u8[]((u8*)owner + memory.size_of(ownership.Object), value.length)
    memory.copy(bytes, value.bytes, value.length)
    return Owned[str]((str)bytes, owner)

## A successful unit outcome, for a callback that reports only success or failure. It saves
## every such callback from spelling `Outcome[unit].success(Owned[unit](()))`.
pub func success_unit() -> Outcome[unit]:
    return Outcome[unit].success(Owned[unit](()))

## A failed unit outcome carrying `code` and an owned copy of `message`, the bridge from a
## Base `!` failure to the `Outcome` a callback returns: `expr catch failure: return
## interop.failure_unit(failure.code, failure.message)`. If copying the message itself runs
## out of memory, the outcome reports memory.exhausted with a static note instead of pending
## managed text.
pub func failure_unit(code: ErrorCode, message: str) -> Outcome[unit]:
    let text = copy_text(message) catch exhausted:
        _ = exhausted
        return Outcome[unit].failure(memory.exhausted, Owned[str]("out of memory copying an error message"))
    return Outcome[unit].failure(code, text)

test "the unit outcome helpers carry success and copied failure text":
    var good = success_unit()
    assert(good.is_success())
    good.release()
    var bad = failure_unit(memory.exhausted, "boom")
    assert(not bad.is_success())
    bad.get() catch failure:
        assert(failure.message == "boom")
    bad.release()