lifetime

    Explicit synchronous lifetimes with removable, idempotent cleanup for MoonBit

    Download zip
    Author
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    7 hours ago
    Downloads
    11

    #Hosi121/lifetime

    Explicit synchronous resource lifetimes for MoonBit, with no external dependency.

    let life = @lifetime.Lifetime()
    let release = life.own(fn() { /* close a resource */ })
    let child = life.child()
    ignore(child.own(fn() { /* remove a subscription */ }))
    release.close() // releases early, removing its parent registration
    life.close() // also closes the child; repeat calls do nothing

    Lifetime is never reopened. Allocate another one for a replacement operation. own returns an idempotent Release. close invokes outstanding cleanup in reverse registration order; already released entries are skipped. Registration on a closed lifetime invokes cleanup immediately. Closing a child early removes its parent registration. Cleanup may close the same lifetime or another release.

    All cleanup must be synchronous and nonthrowing, including foreign exceptions. The type of the callback excludes checked errors, but cannot prevent host JS exceptions or aborts. The library does not collect or recover cleanup failures. It is not thread-safe, does not perform async cleanup, and has no finalizer. Always close the lifetime: open lifetimes may retain resource/closure cycles.

    Ordinary lexical ownership is usually clearer with MoonBit defer/errdefer. This type is for ownership that a caller can end explicitly, across callbacks or API boundaries. It does not statically prove that a resource is used only while open.

    Pure MoonBit; verified on JS, native and Wasm GC. For cancellation-aware callback handoff on JS, use the separate Hosi121/lifetime_js module.

    Source, runnable example and design comparison. Apache-2.0; see LICENSE and NOTICE in this package.

    Lifetime

    pub struct Lifetime {
    // private fields
    }

    One lifetime, never reopened. A new operation gets a new lifetime.

    Lifetime::Lifetime

    fn Lifetime::Lifetime() -> Lifetime

    Lifetime::child

    fn Lifetime::child(self : Lifetime) -> Lifetime

    Lifetime::close

    fn Lifetime::close(self : Lifetime) -> Unit

    Lifetime::is_open

    fn Lifetime::is_open(self : Lifetime) -> Bool

    Lifetime::own

    fn Lifetime::own(self : Lifetime, cleanup : () -> Unit) -> Release

    Adopt cleanup immediately, even if acquisition completed after close. Cleanup must not throw. Releases run in reverse registration order.

    Release

    pub struct Release {
    // private fields
    }

    An idempotent release which removes itself from its parent.

    Release::close

    fn Release::close(self : Release) -> Unit

    Source Files

    Powered by MoonBit

    Site sourceReport issuePackagesBuild queueSkillsStatistics

    © 2026 mooncakes.io