Advertisement
LeonMMS

Untitled

Aug 29th, 2019
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 2.19 KB | None | 0 0
  1. #==============================================================================
  2. # ** Buffer
  3. #------------------------------------------------------------------------------
  4. #  Esta classe lê e escreve dados binários.
  5. #------------------------------------------------------------------------------
  6. #  Autor: Valentine
  7. #==============================================================================
  8.  
  9. class Buffer_Writer
  10.  
  11.   def initialize
  12.     @write_buffer = []
  13.     @write_pack = ''
  14.   end
  15.  
  16.   def write_byte(byte)
  17.     @write_buffer << byte
  18.     @write_pack << 'c'
  19.   end
  20.  
  21.   def write_boolean(value)
  22.     write_byte(value ? 1 : 0)
  23.   end
  24.  
  25.   def write_short(short)
  26.     @write_buffer << short
  27.     @write_pack << 's'
  28.   end
  29.  
  30.   def write_int(int)
  31.     @write_buffer << int
  32.     @write_pack << 'i'
  33.   end
  34.  
  35.   def write_long(long)
  36.     @write_buffer << long
  37.     # q representa um número de 64 bits, diferentemente
  38.     #de l que representa um número de 32 bits
  39.     @write_pack << 'q'
  40.   end
  41.  
  42.   def write_string(str)
  43.     write_short(str.bytesize)
  44.     str.each_byte { |c| write_byte(c) }
  45.   end
  46.  
  47.   def to_s
  48.     @write_buffer.pack(@write_pack)
  49.   end
  50.  
  51. end
  52.  
  53. #==============================================================================
  54. # ** Buffer_Reader
  55. #==============================================================================
  56. class Buffer_Reader
  57.  
  58.   def initialize(str)
  59.     @read_bytes = []
  60.     # O método bytes não é usado, pois, nesta versão do
  61.     #Ruby, ele retorna Enumerator em vez de Array
  62.     str.each_byte { |c| @read_bytes << c }
  63.     @read_pos = 0
  64.   end
  65.  
  66.   def read_byte
  67.     byte = @read_bytes[@read_pos]
  68.     @read_pos += 1
  69.     byte
  70.   end
  71.  
  72.   def read_boolean
  73.     read_byte == 1
  74.   end
  75.  
  76.   def read_short
  77.     read(2, 's')
  78.   end
  79.  
  80.   def read_int
  81.     read(4, 'i')
  82.   end
  83.  
  84.   def read_long
  85.     read(8, 'q')
  86.   end
  87.  
  88.   def read_string
  89.     size = read_short
  90.     read(size, "A#{size}")
  91.   end
  92.  
  93.   def read_time
  94.     Time.new(read_short, read_byte, read_byte)
  95.   end
  96.  
  97.   private
  98.  
  99.   def read(n, format)
  100.     bytes = @read_bytes[@read_pos, @read_pos + n]
  101.     @read_pos += n
  102.     bytes.pack('C*').unpack(format)[0]
  103.   end
  104.  
  105. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement