Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #==============================================================================
- # ** Buffer
- #------------------------------------------------------------------------------
- # Esta classe lê e escreve dados binários.
- #------------------------------------------------------------------------------
- # Autor: Valentine
- #==============================================================================
- class Buffer_Writer
- def initialize
- @write_buffer = []
- @write_pack = ''
- end
- def write_byte(byte)
- @write_buffer << byte
- @write_pack << 'c'
- end
- def write_boolean(value)
- write_byte(value ? 1 : 0)
- end
- def write_short(short)
- @write_buffer << short
- @write_pack << 's'
- end
- def write_int(int)
- @write_buffer << int
- @write_pack << 'i'
- end
- def write_long(long)
- @write_buffer << long
- # q representa um número de 64 bits, diferentemente
- #de l que representa um número de 32 bits
- @write_pack << 'q'
- end
- def write_string(str)
- write_short(str.bytesize)
- str.each_byte { |c| write_byte(c) }
- end
- def to_s
- @write_buffer.pack(@write_pack)
- end
- end
- #==============================================================================
- # ** Buffer_Reader
- #==============================================================================
- class Buffer_Reader
- def initialize(str)
- @read_bytes = []
- # O método bytes não é usado, pois, nesta versão do
- #Ruby, ele retorna Enumerator em vez de Array
- str.each_byte { |c| @read_bytes << c }
- @read_pos = 0
- end
- def read_byte
- byte = @read_bytes[@read_pos]
- @read_pos += 1
- byte
- end
- def read_boolean
- read_byte == 1
- end
- def read_short
- read(2, 's')
- end
- def read_int
- read(4, 'i')
- end
- def read_long
- read(8, 'q')
- end
- def read_string
- size = read_short
- read(size, "A#{size}")
- end
- def read_time
- Time.new(read_short, read_byte, read_byte)
- end
- private
- def read(n, format)
- bytes = @read_bytes[@read_pos, @read_pos + n]
- @read_pos += n
- bytes.pack('C*').unpack(format)[0]
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement