Module: RTunnel::IOExtensions

Defined in:
lib/rtunnel/io_extensions.rb

Instance Method Summary collapse

Instance Method Details

#read_varsizeObject

reads a size (non-negative Integer) from the stream using a varint encoding



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rtunnel/io_extensions.rb', line 18

def read_varsize
  size = 0
  multiplier = 1
  loop do
    char = getc
    # TODO(costan): better exception
    unless char
      raise RTunnel::TruncatedDataError.new("Encoded varsize truncated")
    end
    more, size_add = char.divmod(0x80)
    size += size_add * multiplier
    break if more == 0
    multiplier *= 0x80
  end
  size
end

#read_varstringObject

reads a variable-length string that was previously written with write_varstr



42
43
44
45
46
47
48
49
50
# File 'lib/rtunnel/io_extensions.rb', line 42

def read_varstring
  length = read_varsize
  return '' if length == 0
  str = read(length)
  if ! str or str.length != length
    raise RTunnel::TruncatedDataError, "Encoded varstring truncated"
  end
  str
end

#write_varsize(size) ⇒ Object

writes a size (non-negative Integer) to the stream using a varint encoding



7
8
9
10
11
12
13
14
15
# File 'lib/rtunnel/io_extensions.rb', line 7

def write_varsize(size)
  chars = []
  loop do
    size, char = size.divmod(0x80)
    chars << (char | ((size > 0) ? 0x80 : 0))
    break if size == 0
  end
  write chars.pack('C*')
end

#write_varstring(str) ⇒ Object

writes a string and its length, so it can later be read with read_varstr



36
37
38
39
# File 'lib/rtunnel/io_extensions.rb', line 36

def write_varstring(str)
  write_varsize str.length
  write str
end