Skip to content

feat(stable-api): Add RB_ID2SYM, RB_SYM2ID for Symbol/ID conversions #669

@ianks

Description

@ianks

Summary

Add stable API methods for converting between Symbols and IDs, equivalent to RB_ID2SYM and RB_SYM2ID.

Motivation

Symbol/ID conversions are fundamental operations in Ruby extensions for:

  • Method dispatch and respond_to? checks
  • Hash key handling (symbols are common hash keys)
  • Attribute accessors

While rb_id2sym() and rb_sym2id() functions exist, the macro versions are more efficient for static symbols.

Proposed API

/// Convert an ID to a Symbol VALUE (akin to `RB_ID2SYM`).
///
/// Returns a static Symbol VALUE for the given ID.
fn id2sym(&self, id: ID) -> VALUE;

/// Convert a Symbol VALUE to an ID (akin to `RB_SYM2ID`).
///
/// # Safety
/// The caller must ensure the VALUE is actually a Symbol.
/// For dynamic symbols, this may need to access heap data.
unsafe fn sym2id(&self, obj: VALUE) -> ID;

Implementation Notes

  • Static symbols use tagged pointers: (id << 8) | 0x0c
  • Dynamic symbols (Ruby 2.2+) are heap-allocated
  • Need to handle both static and dynamic symbol cases
  • Reference: include/ruby/internal/symbol.h

Checklist

  • Add methods to StableApiDefinition trait
  • Implement for each Ruby version
  • Handle static vs dynamic symbols
  • Add C fallback in compiled.c
  • Add public macro wrappers in macros.rs
  • Add tests for both static and dynamic symbols

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