insomnia

Manipulate native MoonBit object in MoonBit

moon add tonyfettes/insomnia@0.3.2
Download zip
Version
0.3.2
License
Apache-2.0
Last updated
7 months ago
Downloads
22

Dependencies

README

#tonyfettes/insomnia

A MoonBit library for managing object metadata and reference counting in the MoonBit runtime system.

#Overview

insomnia provides low-level APIs for working with MoonBit object headers, metadata, and reference counting. This library is particularly useful for implementing custom memory management strategies, interfacing with C code, and managing external resources that require explicit cleanup.

#Features

  • Object Metadata Management: Work with different types of object metadata (Regular, RefArray, ValArray, External)
  • Reference Counting: Manual reference count manipulation with incref and decref
  • External Objects: Create objects with custom finalizers for resource management
  • Type-Safe Encoding: Encode and decode metadata to/from compact UInt representations

#Object Types

#Regular Objects

Regular objects have a fixed layout with pointer and non-pointer fields:

///|
let meta = Regular({ ptr_field_offset: 0, n_ptr_fields: 2, tag: 42 })

  • ptr_field_offset: Offset where pointer fields begin
  • n_ptr_fields: Number of pointer fields
  • tag: 8-bit type identifier

#Reference Arrays

Arrays that store pointers to other objects:

///|
let meta = RefArray({
object_size_shift: 3, // Each element is 1 << 3 = 8 bytes
len: 100,
})

#Value Arrays

Arrays that store primitive values or non-pointer data:

///|
let meta = ValArray({ len: 100 })

#External Objects

Objects that manage external resources with custom finalizers:

///|
fn my_finalizer(ptr : @c.Pointer[Unit]) -> Unit {
// Clean up resources
println("Finalizing object")
}

///|
let obj = make_external_object(my_finalizer, 64)

#Example Usage

// Create an external object with a finalizer
fn cleanup(ptr : @c.Pointer[Unit]) -> Unit {
println("Cleaning up external resource")
}

let obj = make_external_object(cleanup, 1024)

// Manually manage reference counts
incref(obj)
// ... use object ...
decref(obj) // Will call finalizer when count reaches 0

// Work with object metadata
let header = object_header(obj)
let meta = header.meta()
match meta {
External(e) => println("External object of size \{e.size}")
_ => ()
}

#Safety Notes

This library provides low-level access to MoonBit's memory management system. Incorrect usage can lead to:

  • Memory leaks: Forgetting to call decref
  • Use-after-free: Calling decref too many times
  • Dangling pointers: Accessing objects after they've been freed

Only use these APIs when you need explicit control over memory management or when interfacing with external C code.

#License

Apache-2.0

#
External

pub struct External {
size : UInt
}

Metadata for external objects with custom finalizers.

External objects are used for managing resources that require custom finalization logic.
impl Show for External
impl ToJson for External

#
External::finalizer

fn External::finalizer(self : External, object :
Pointer
[Unit]) -> Finalizer

Get the finalizer associated with an external object.

Retrieves the finalizer function pointer stored at the end of the external object's data. The finalizer is located at offset size from the object pointer.

Parameters

  • object: Pointer to the external object

Returns the finalizer function for this object.

#
External::set_finalizer

fn External::set_finalizer(self : External, object :
Pointer
[Unit], finalizer : FuncRef[(
Pointer
[Unit]) -> Unit]) -> Unit

Set the finalizer for an external object.

Stores a finalizer function pointer at the end of the external object's data (at offset size from the object pointer). This finalizer will be called when the object is garbage collected.

Parameters

  • object: Pointer to the external object
  • finalizer: Function to be called when the object is finalized

#
Finalizer

type Finalizer

Abstract type representing a finalizer function for an external object.

#
Finalizer::to_funcref

fn Finalizer::to_funcref(self : Finalizer) -> FuncRef[(
Pointer
[Unit]) -> Unit]

Convert a Finalizer to a function reference.

This function converts a Finalizer object into a function reference that can be called to clean up resources associated with an external object.

#
Meta

pub(all) enum Meta {
Regular(Regular)
RefArray(RefArray)
ValArray(ValArray)
External(External)
}

Metadata descriptor for MoonBit objects.
impl Show for Meta
impl ToJson for Meta

#
Meta::of_uint

fn Meta::of_uint(meta : UInt) -> Meta

Decode metadata from a UInt value.

Parses a 32-bit unsigned integer to extract object metadata. The top 2 bits determine the object kind (Regular, RefArray, ValArray, or External), and the remaining bits encode kind-specific information.

Parameters

  • meta: The encoded metadata as a UInt

Returns the decoded Meta enum value.

#
Meta::to_uint

fn Meta::to_uint(self : Meta) -> UInt

Encode metadata to a UInt value.

Converts a Meta enum value into a 32-bit unsigned integer encoding. The top 2 bits indicate the object kind, and the remaining bits encode kind-specific information such as field offsets, array lengths, or object sizes.

Returns the encoded metadata as a UInt.

#
Object

type Object

Wrapper type around @c.Pointer for easier access to object header fields.

#
Object::meta

fn Object::meta(self : Object) -> Meta

Get the metadata of an object.

Retrieves and decodes the metadata stored in the object's header.

Returns the decoded Meta enum describing the object's type and layout.

#
Object::rc

fn Object::rc(self : Object) -> Int

Get the reference count of an object.

Returns the current reference count stored in the object's header.

Returns the reference count as an Int.

#
Object::set_meta

fn Object::set_meta(self : Object, meta : Meta) -> Unit

Set the metadata of an object.

Encodes and stores metadata in the object's header.

Parameters

  • meta: The Meta enum value to encode and store

#
Object::set_rc

fn Object::set_rc(self : Object, rc : Int) -> Unit

Set the reference count of an object.

Updates the reference count stored in the object's header.

Parameters
  • rc: The new reference count value

#
Object::to_pointer

fn Object::to_pointer(self : Object) ->
Pointer
[Unit]

Convert an Object to a generic pointer.

Returns a pointer to the beginning of the object's data (excluding the header).

Returns a pointer to the object's data.

#
RefArray

pub struct RefArray {
object_size_shift : UInt
len : UInt
}

Metadata for reference arrays (arrays of pointers).

Reference arrays store pointers to other objects.
impl Show for RefArray
impl ToJson for RefArray

#
Regular

pub struct Regular {
ptr_field_offset : UInt
n_ptr_fields : UInt
tag : UInt
}

Metadata for regular objects with pointer and non-pointer fields.

Regular objects have a fixed layout with a specific number of pointer fields and non-pointer fields. The ptr_field_offset indicates where pointer fields start, n_ptr_fields indicates how many pointer fields there are, and tag is an 8-bit tag for enum type.
impl Show for Regular
impl ToJson for Regular

#
ValArray

pub struct ValArray {
object_size_shift : UInt
len : UInt
}

Metadata for value arrays (arrays of non-pointer values).

Value arrays store primitive values or values of value types.
impl Show for ValArray
impl ToJson for ValArray

#
decref

fn decref(object :
Pointer
[Unit]) -> Unit

Decrement the reference count of an object.

Decreases the reference count by one. When the reference count reaches zero, the object will be deallocated. If the object has a finalizer, it will be called before deallocation.

Parameters

  • object: Pointer to the object whose reference count should be decremented

#
incref

fn incref(object :
Pointer
[Unit]) -> Unit

Increment the reference count of an object.

Increases the reference count by one. This should be called when creating a new reference to an existing object.

Parameters

  • object: Pointer to the object whose reference count should be incremented

#
make_external_object

fn make_external_object(drop : FuncRef[(
Pointer
[Unit]) -> Unit], size : UInt64) ->
Pointer
[Unit]

Create a new external object with a custom finalizer.

Allocates memory for an external object and associates it with a finalizer function that will be called when the object is garbage collected.

Parameters

  • drop: The finalizer function to call when the object is collected
  • size: The size of the object's data in bytes

Returns a pointer to the newly allocated external object.

#
object_header

fn object_header(object :
Pointer
[Unit]) -> Object

Get the object header from a data pointer.

Given a pointer to an object's data, returns an Object handle that provides access to the object's header (containing reference count and metadata).

Parameters

  • object: Pointer to the object's data

Returns an Object handle for accessing the header.

#
size_in_array

fn[T] size_in_array(_ : FuncRef[(T) -> Unit]) ->
Size

#
size_in_ref

fn[T] size_in_ref(_ : FuncRef[(T) -> Unit]) ->
Size

Powered by MoonBit

Site sourceReport issuePackagesBuild queueSkillsStatistics

© 2026 mooncakes.io