Skip to content

Instantly share code, notes, and snippets.

@bew
Last active August 12, 2017 01:24
Show Gist options
  • Save bew/0d667cf3f5ff9fa1354fe175b8dc51a1 to your computer and use it in GitHub Desktop.
Save bew/0d667cf3f5ff9fa1354fe175b8dc51a1 to your computer and use it in GitHub Desktop.
Cool micro RPC fake calls with object serialization, deserialization, method call
module SharedNode
ADDRESS_PROXY = {} of Int32 => {UInt64, Node.class}
@@last_id = 0
def self.add_node(node)
@@last_id += 1
ADDRESS_PROXY[@@last_id] = {node.as(Void*).address, node.class}
@@last_id
end
module Getter(T)
def self.by_id(obj_id)
unless entry = ADDRESS_PROXY[obj_id]
raise "bad id"
end
obj_ptr, obj_type = entry
raise "bad ptr type" unless obj_type == T
Pointer(Void).new(obj_ptr).as(T)
end
end
end
class Node
def serial
{SharedNode.add_node(self), self.class.name}
end
end
class Path < Node
def initialize(@type : TypeNode)
end
def resolve
@type
end
end
class TypeNode < Node
getter name : String
def initialize(@name)
end
end
module RPCAction
def self.path_resolve(args)
obj_id = args.first
path = SharedNode::Getter(Path).by_id(obj_id)
path.resolve
end
end
# create the node
node = Path.new(TypeNode.new("MyClass"))
# pseudo serialize it
serial = node.serial
# send the `serial` to some process
# wait for RPC call
# here is an RPC call
args = [serial.first] # fake args
rpc_action = "path_resolve"
# dynamic dispatch the call
result = case rpc_action
when "path_resolve"
RPCAction.path_resolve(args)
else
raise "bad action"
end
# send back the result (or display it :p)
pp result, result.serial
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment