How safe is this SafeBox implementation?

36 views
Skip to first unread message

Dean Thompson

unread,
Nov 5, 2018, 6:51:48 AM11/5/18
to Crystal


This seems to me like a much safer -- albeit slower -- implementation of Box functionality. Criticism and improvements warmly welcomed!

class SafeBox
  @@interned_type_strings = {} of String => String

  getter type_id : Int32
  getter type_string : String
  getter box : Void*

  def initialize(type_id, type_string, box)
    @type_id = type_id
    if ts = @@interned_type_strings[type_string]?
      @type_string = ts
    else
      @@interned_type_strings[type_string] = type_string
      @type_string = type_string
    end
    @box = box
  end
end

class SafeBoxer(T)
  def self.box(object : T) : SafeBox
    SafeBox.new(T.crystal_type_id,
      T.to_s,
      Box(T).box(object))
  end

  def self.unbox(safe_box : SafeBox)
    if safe_box.type_id != T.crystal_type_id
      raise "Tried to unbox a SafeBox of #{safe_box.type_string} as a #{T}"
    else
      Box(T).unbox(safe_box.box)
    end
  end
end

box = SafeBoxer(Int32).box(42)
SafeBoxer(Int32).unbox(box) # => 42
SafeBoxer(String).unbox(box) # raises

Reply all
Reply to author
Forward
0 new messages