Skip to content

Instantly share code, notes, and snippets.

@nayutaya
Created March 2, 2010 11:08
Show Gist options
  • Save nayutaya/319435 to your computer and use it in GitHub Desktop.
Save nayutaya/319435 to your computer and use it in GitHub Desktop.
require "stringio"
module MessagePackPure
def self.unpack(binary)
io = StringIO.new(binary)
return self.read(io)
end
def self.read(io)
type = io.read(1).unpack("C")[0]
if (type & 0b10000000) == 0b00000000 # positive fixnum
return type
elsif (type & 0b11100000) == 0b10100000 # fixraw
size = (type & 0b00011111)
return io.read(size)
elsif (type & 0b11110000) == 0b10010000 # fixarray
size = (type & 0b00001111)
return size.times.map { read(io) }
end
case type
when 0xC0 then nil
when 0xCB # double
return io.read(8).unpack("G")[0]
when 0xCC # uint8
return io.read(1).unpack("C")[0]
when 0xDE # map16
size = io.read(2).unpack("n")[0]
ary = size.times.map {
key = read(io)
value = read(io)
[key, value]
}
return Hash[ary]
else raise("Unknown Type -- #{'0x%02X' % type}")
end
end
end
if $0 == __FILE__
require "test/unit"
require "rubygems"
require "msgpack"
class MessagePackPureTest < Test::Unit::TestCase
def setup
@module = MessagePackPure
end
def test_nil
assert_equal(nil, @module.unpack(MessagePack.pack(nil)))
end
def test_positive_fixnum
(0..127).each { |n|
assert_equal(n, @module.unpack(MessagePack.pack(n)))
}
end
def test_uint8
assert_equal(128, @module.unpack(MessagePack.pack(128)))
assert_equal(2 ** 8 - 1, @module.unpack(MessagePack.pack(2 ** 8 - 1)))
end
def test_map16
map = {}
(1..16).each { |i| map[i] = i }
assert_equal(map, @module.unpack(MessagePack.pack(map)))
end
def test_fixraw
assert_equal("", @module.unpack(MessagePack.pack("")))
assert_equal("a", @module.unpack(MessagePack.pack("a")))
end
def test_fixarray
assert_equal([], @module.unpack(MessagePack.pack([])))
assert_equal([1], @module.unpack(MessagePack.pack([1])))
end
def test_double
assert_equal(0.5, @module.unpack(MessagePack.pack(0.5)))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment