File: pack_array.rb

package info (click to toggle)
ruby-remcached 0.4.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 200 kB
  • sloc: ruby: 1,000; sh: 9; makefile: 2
file content (46 lines) | stat: -rw-r--r-- 932 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
##
# Works exactly like Array#pack and String#unpack, except that it
# inverts 'q' & 'Q' prior packing/after unpacking. This is done to
# achieve network byte order for these values on a little-endian machine.
#
# FIXME: implement check for big-endian machines.
module Memcached::PackArray
  def self.pack(ary, fmt1)
    fmt2 = ''
    values = []
    fmt1.each_char do |c|
      if c == 'Q' || c == 'q'
        fmt2 += 'a8'
        values << [ary.shift].pack(c).reverse
      else
        fmt2 += c
        values << ary.shift
      end
    end

    values.pack(fmt2)
  end

  def self.unpack(buf, fmt1)
    fmt2 = ''
    reverse = []
    i = 0
    fmt1.each_char do |c|
      if c == 'Q' || c == 'q'
        fmt2 += 'a8'
        reverse << [i, c]
      else
        fmt2 += c
      end
      i += 1
    end

    ary = buf.unpack(fmt2)

    reverse.each do |i, c|
      ary[i], = ary[i].reverse.unpack(c)
    end

    ary
  end
end