Skip to content

feat(stable-api): Add RB_OBJ_FREEZE for object freezing #672

@ianks

Description

@ianks

Summary

Add stable API method for freezing Ruby objects, equivalent to the C macro RB_OBJ_FREEZE.

Motivation

Object freezing is a common operation for:

  • Creating immutable values
  • Thread-safe data structures (frozen objects are Ractor-shareable)
  • Performance optimization (frozen string literals)

Currently, users must call rb_obj_freeze() which is a function call. The inline version can be more efficient for simple cases.

Ruby Source Reference

// include/ruby/internal/fl_type.h

#define RB_OBJ_FREEZE rb_obj_freeze_inline

static inline void
RB_OBJ_FREEZE_RAW(VALUE obj)
{
    rb_obj_freeze_inline(obj);
}

// rb_obj_freeze_inline is declared as RUBY_SYMBOL_EXPORT
void rb_obj_freeze_inline(VALUE obj);

Note: The actual implementation calls rb_obj_freeze_inline() which handles:

  • Setting the RUBY_FL_FREEZE flag
  • Freezing singleton class if present
  • Other internal bookkeeping

Proposed API

/// Freeze an object, making it immutable (akin to `RB_OBJ_FREEZE`).
///
/// After freezing, any attempt to modify the object will raise FrozenError.
/// Frozen objects are also safe to share across Ractors.
///
/// # Safety
/// This function is unsafe because it modifies the object's internal state.
/// The caller must ensure the VALUE is a valid Ruby object.
unsafe fn rb_obj_freeze(&self, obj: VALUE);

Implementation Notes

  • For most cases, simply set RUBY_FL_FREEZE flag
  • Need to handle singleton class freezing for some object types
  • May need to call the C function for correctness
  • Reference: include/ruby/internal/fl_type.h:911-925

Checklist

  • Add method to StableApiDefinition trait
  • Implement for each Ruby version
  • Add C fallback in compiled.c
  • Add public macro wrapper in macros.rs
  • Add tests verifying freeze behavior
  • Test interaction with Ractor shareability

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions