module Rubellite::Docs::A_GETTING_STARTED::TYPE_SYSTEM

Overview

Type Conversions & Value Marshaling

Rubellite provides an automatic, zero-copy type mapping system for primitive scalars, alongside deep marshaling for collections like Arrays, Hashes, Tuples, and NamedTuples.

Executive Summary & Key Topics

Topic Method / Anchor Description
Scalar Primitives & Flonum Encoding .topic_01_scalar_mapping Unboxed 64-bit integer, floating point, boolean, and nil representation.

Related Guides & Source References

Defined in:

rubellite/docs/a_getting_started/type_system.cr

Class Method Summary

Class Method Detail

def self.topic_01_scalar_mapping : Nil #

Scalar Primitives & Flonum Encoding: Unboxed 64-bit integer, floating point, boolean, and nil representation.

Rubellite exploits CRuby's 64-bit tagged pointer representations (USE_FLONUM):

Crystal Type Ruby Representation Tagging Mechanism
`Nil` `Qnil` (0x04) Immediate constant
`Bool` (`true` / `false`) `Qtrue` (0x14) / `Qfalse` (0x00) Immediate constant
`Int` (e.g. `Int32`, `Int64`) `FIXNUM` LSB tag `0x01` (unboxed 63-bit int)
`Float64` `FLONUM` Bits tagged `0x02` (unboxed double)
`String` `T_STRING` Heap allocated with UTF-8 encoding
`Symbol` `ID` / `T_SYMBOL` Interned symbol ID

Working Examples

require "rubellite"

Rubellite.init

# Convert Crystal scalars and collections to Ruby values (auto-inits)
val_int = 42.to_ruby
val_str = "Hello Crystal".to_ruby
val_arr = [1, 2, 3].to_ruby

# Unpack Ruby values back into Crystal types
puts val_int.as_crystal # => 42_i64
puts val_str.as_crystal # => "Hello Crystal"

# Typed collection unboxing
raw_arr = Ruby.eval("[10, 20, 30]")
typed_arr = raw_arr.to_a(Int32) # Array(Int32)

# Deep recursive unboxing for nested structures
complex_rb = Ruby.eval("{ 'tags' => ['cr', 'rb'], 'score' => 99 }")
native_map = complex_rb.as_crystal_deep # Hash(String, Rubellite::DeepValue)

Common Pitfalls & Safety Caveats

  • Warning: Large integers exceeding 63 bits are converted to Ruby Bignum automatically, which incurs heap allocation.
  • Warning: Use as_crystal_deep for recursively converting entire nested trees into Crystal collections.

Frequently Asked Questions (FAQ)

  • Q: Can I convert Crystal NamedTuples to Ruby? A: Yes, NamedTuples are converted into Ruby Hashes with Symbol keys.

  • Q: What scalar unboxers exist on Value? A: Value provides as_i, as_i64, as_f, as_s, as_bool, and as_nil.


[View source]