Class: Esbuild::StdioProtocol::PacketEncoder

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

Instance Method Summary collapse

Constructor Details

#initializePacketEncoder

Returns a new instance of PacketEncoder.



81
82
83
84
85
# File 'lib/esbuild/stdio_protocol.rb', line 81

def initialize
  @format = ""
  @elements = []
  @size = 0
end

Instance Method Details

#encode_packet(packet) ⇒ Object



87
88
89
90
91
92
93
# File 'lib/esbuild/stdio_protocol.rb', line 87

def encode_packet(packet)
  write32 0
  write32((packet.id << 1) | (packet.is_request ? 0 : 1))
  visit(packet.value)
  @elements[0] = @size - 4
  @elements.pack(@format)
end

#visit(value) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/esbuild/stdio_protocol.rb', line 95

def visit(value)
  case value
  when nil
    write8 0
  when true, false
    write8 1
    write8(value ? 1 : 0)
  when Integer
    write8 2
    write32 value
  when String
    if value.encoding == Encoding::BINARY
      write8 4
    else
      write8 3
      value = value.encode(Encoding::UTF_8) unless value.encoding == Encoding::UTF_8
    end
    write_string value
  when Array
    write8 5
    write32 value.size
    value.each { |item| visit(item) }
  when Hash
    write8 6
    write32 value.size
    value.each do |key, val|
      write_string key
      visit val
    end
  else
    raise ArgumentError, "Don't know how to encode #{value.inspect}"
  end
end

#write32(value) ⇒ Object



137
138
139
140
141
# File 'lib/esbuild/stdio_protocol.rb', line 137

def write32(value)
  @elements << value
  @format << "L<"
  @size += 4
end

#write8(value) ⇒ Object



143
144
145
146
147
# File 'lib/esbuild/stdio_protocol.rb', line 143

def write8(value)
  @elements << value
  @format << "C"
  @size += 1
end

#write_string(string) ⇒ Object



129
130
131
132
133
134
135
# File 'lib/esbuild/stdio_protocol.rb', line 129

def write_string(string)
  string = string.to_s
  write32 string.bytesize
  @elements << string
  @format << "a*"
  @size += string.bytesize
end