Module: PhpUnpack
- Defined in:
- lib/ruby-common/common/PhpUnpack.rb
Constant Summary collapse
- NAME =
"name"- CODE =
"code"
Class Method Summary collapse
- .decode(input, code) ⇒ Object
- .encode(input, code) ⇒ Object
- .pack(format, *inputs) ⇒ Object
- .unpack(format, input, byte_slice = true) ⇒ Object
Class Method Details
.decode(input, code) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/ruby-common/common/PhpUnpack.rb', line 28 def self.decode(input, code) case code when 'c' decoded_data = input.unpack('c') bytes_offset = 1 when 'C' decoded_data = input.unpack('C') bytes_offset = 1 when 'n' decoded_data = input.unpack('n') bytes_offset = 2 when 'N' decoded_data = input.unpack('N') bytes_offset = 4 when 'J' decoded_data = input.unpack1('Q>') bytes_offset = 8 when 'v' decoded_data = input.unpack('v') bytes_offset = 2 else raise ArgumentError, "Unrecognized instruction: #{code}" end [decoded_data, bytes_offset] end |
.encode(input, code) ⇒ Object
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/ruby-common/common/PhpUnpack.rb', line 68 def self.encode(input, code) case code when 'c' [input.to_i].pack('c') when 'C' [input.to_i].pack('C') when 'n' [input.to_i].pack('n') when 'N' [input.to_i].pack('N') when 'J' [input.to_i].pack('J') when 'v' [input.to_i].pack('v') else raise ArgumentError, "Unrecognized instruction: #{code}" end end |
.pack(format, *inputs) ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/ruby-common/common/PhpUnpack.rb', line 55 def self.pack(format, *inputs) instructions = format.split('') raise ArgumentError, "Invalid format length, expected #{inputs.length} number of codes" unless instructions.length == inputs.length buffer = StringIO.new instructions.each_with_index do |code, i| encoded_data = encode(inputs[i], code) buffer.write(encoded_data) end buffer.string end |
.unpack(format, input, byte_slice = true) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/ruby-common/common/PhpUnpack.rb', line 7 def self.unpack(format, input, byte_slice = true) instructions = format.split('/') offset = 0 result = {} instructions.each do |instruction| code_and_name = get_code_and_name(instruction) code = code_and_name[CODE] name = code_and_name[NAME] decoded_data, bytes_offset = decode(input, code) result[name] = decoded_data offset = offset + bytes_offset if byte_slice input.slice!(0, bytes_offset) end end result end |