Skip to content

Commit

Permalink
Add methods for reading and writing packets
Browse files Browse the repository at this point in the history
  • Loading branch information
spuun committed May 2, 2024
1 parent 6130f53 commit f8f908c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
22 changes: 22 additions & 0 deletions spec/io_spec.cr
Original file line number Diff line number Diff line change
@@ -1,6 +1,28 @@
require "./spec_helper"

describe MQTT::Protocol::IO do
it "can read packet" do
mio = IO::Memory.new
# Write a raw PingReq
mio.write_byte(12u8 << 4)
mio.write_byte(0u8)
mio.rewind

packet = MQTT::Protocol::IO.new(mio).read_packet

packet.should be_a MQTT::Protocol::PingReq
end

it "can write packet" do
mio = IO::Memory.new

pingreq = MQTT::Protocol::PingReq.new
MQTT::Protocol::IO.new(mio).write_packet(pingreq)
mio.rewind

mio.to_slice.should eq Bytes[12u8 << 4, 0u8]
end

it "can write int" do
mio = IO::Memory.new
io = MQTT::Protocol::IO.new(mio)
Expand Down
14 changes: 14 additions & 0 deletions src/mqtt/protocol/io.cr
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require "./packets"

module MQTT
module Protocol
struct IO
Expand All @@ -8,6 +10,18 @@ module MQTT

forward_missing_to @io

def read_packet : Packet
Packet.from_io(self)
end

def write(packet : Packet)
write_packet(packet)
end

def write_packet(packet : Packet)
packet.to_io(self)
end

def read_byte
@io.read_byte || raise ::IO::EOFError.new
end
Expand Down

0 comments on commit f8f908c

Please sign in to comment.