Class: Esbuild::StdioProtocol::PacketDecoder

Inherits:
Object
  • Object
show all
Defined in:
lib/esbuild/stdio_protocol.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(buf, offset, size) ⇒ PacketDecoder

Returns a new instance of PacketDecoder.



10
11
12
13
14
# File 'lib/esbuild/stdio_protocol.rb', line 10

def initialize(buf, offset, size)
  @buf = buf
  @offset = offset
  @end = offset + size
end

Instance Attribute Details

#offsetObject (readonly)

Returns the value of attribute offset.



8
9
10
# File 'lib/esbuild/stdio_protocol.rb', line 8

def offset
  @offset
end

Instance Method Details

#decode_packetObject



16
17
18
19
20
21
22
23
# File 'lib/esbuild/stdio_protocol.rb', line 16

def decode_packet
  id = read32
  is_request = (id & 1) == 0
  id >>= 1

  value = visit
  Packet.new(id, is_request, value)
end

#read32Object



75
76
77
# File 'lib/esbuild/stdio_protocol.rb', line 75

def read32
  read8 | (read8 << 8) | (read8 << 16) | (read8 << 24)
end

#read8Object

Raises:

  • (ArgumentError)


68
69
70
71
72
73
# File 'lib/esbuild/stdio_protocol.rb', line 68

def read8
  raise ArgumentError, "Reading past buffer" if @offset >= @end
  byte = @buf.getbyte(@offset)
  @offset += 1
  byte
end

#read_stringObject



61
62
63
64
65
66
# File 'lib/esbuild/stdio_protocol.rb', line 61

def read_string
  size = read32
  result = @buf.byteslice(@offset, size)
  @offset += size
  result
end

#visitObject



25
26
27
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
54
55
56
57
58
59
# File 'lib/esbuild/stdio_protocol.rb', line 25

def visit
  kind = read8
  case kind
  when 0
    # Null
    nil
  when 1
    # Bool
    read8 == 1
  when 2
    # Integer
    read32
  when 3
    # String
    read_string.force_encoding(Encoding::UTF_8)
  when 4
    # Bytes
    read_string
  when 5
    # Array
    size = read32
    size.times.map { visit }
  when 6
    # Object
    result = {}
    size = read32
    size.times do
      key = read_string.force_encoding(Encoding::UTF_8)
      result[key] = visit
    end
    result
  else
    raise ArgumentError, "Invalid packet #{kind}"
  end
end