Class: Estore::Connection::Buffer

Inherits:
Object
  • Object
show all
Defined in:
lib/estore/connection/buffer.rb

Overview

Buffer receives data from the TCP connection, and parses the binary packages. Parsed packages are given back to the given handler as they are decoded.

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Buffer

Returns a new instance of Buffer.



7
8
9
10
11
# File 'lib/estore/connection/buffer.rb', line 7

def initialize(&block)
  @mutex = Mutex.new
  @buffer = ''.force_encoding('BINARY')
  @handler = block
end

Instance Method Details

#<<(bytes) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/estore/connection/buffer.rb', line 13

def <<(bytes)
  bytes = bytes.force_encoding('BINARY') if
    bytes.respond_to? :force_encoding

  @mutex.synchronize do
    @buffer << bytes
  end

  consume_packages
end

#consume_packagesObject



24
25
26
27
28
29
# File 'lib/estore/connection/buffer.rb', line 24

def consume_packages
  while (pkg = read_package)
    handle(pkg)
    discard_bytes(pkg)
  end
end

#discard_bytes(pkg) ⇒ Object



38
39
40
41
42
# File 'lib/estore/connection/buffer.rb', line 38

def discard_bytes(pkg)
  @mutex.synchronize do
    @buffer = @buffer[(4 + pkg.bytesize)..-1]
  end
end

#handle(pkg) ⇒ Object



44
45
46
47
48
# File 'lib/estore/connection/buffer.rb', line 44

def handle(pkg)
  code, flags, uuid_bytes, package = parse(pkg)
  command = Estore::Connection.command_name(code)
  @handler.call(command, package, Package.parse_uuid(uuid_bytes), flags)
end

#parse(pkg) ⇒ Object



50
51
52
53
54
55
56
57
# File 'lib/estore/connection/buffer.rb', line 50

def parse(pkg)
  [
    pkg[0].unpack('C').first,
    pkg[1].unpack('C').first,
    pkg[2...(2 + 16)],
    pkg[18..-1]
  ]
end

#read_packageObject



31
32
33
34
35
36
# File 'lib/estore/connection/buffer.rb', line 31

def read_package
  return nil if @buffer.length < 4
  package_length = @buffer[0...4].unpack('l<').first
  bytes = @buffer[4...(4 + package_length)].dup
  bytes if bytes.bytesize >= package_length
end