Guest User

Untitled

a guest
Oct 16th, 2013
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.77 KB | None | 0 0
  1. =begin
  2.  
  3.   * Name: lib/source_buffer.rb
  4.   * Description: SourceBuffer object for Freeman.
  5.   * Author: Charles "MisutoWolf" Baker
  6.     * GitHub: https://github.com/misutowolf
  7.   * Date: 10/11/2013
  8.   * License: MIT
  9.  
  10. =end
  11.  
  12. class SourceBuffer
  13.  
  14.   # Accessors
  15.   attr_accessor :buffer, :length, :position
  16.  
  17.   # Set contents of buffer
  18.   def set(buffer)
  19.     @buffer = buffer.encode('binary')
  20.     @length = buffer.length
  21.     @position = 0
  22.   end
  23.  
  24.   # Reset buffer (empty), set length/position to zero.
  25.   def reset
  26.     @buffer = ''
  27.     @length = 0
  28.     @position = 0
  29.   end
  30.  
  31.   # Returns number of bytes remaining in buffer to read
  32.   def get_remaining_bytes
  33.     @length-@position
  34.   end
  35.  
  36.   # Get data from buffer (number of bytes specified).
  37.   def get(length=-1)
  38.  
  39.     if length == 0
  40.       ''
  41.     end
  42.  
  43.     remaining = get_remaining_bytes
  44.  
  45.     if length == -1
  46.       length=remaining
  47.     elsif length > remaining
  48.       ''
  49.     end
  50.  
  51.     data = @buffer[@position,length]
  52.     @position+=length
  53.     data
  54.  
  55.   end
  56.  
  57.   # Get a single byte from the buffer.
  58.   def get_byte
  59.     get(1).ord
  60.   end
  61.  
  62.   # Get a 16-bit unsigned integer from the buffer.
  63.   def get_short
  64.     get(2).unpack('s')
  65.   end
  66.  
  67.   # Get a 32-bit floating-point from the buffer.
  68.   def get_float
  69.     get(4).unpack('f')
  70.   end
  71.  
  72.   # Get a 32-bit signed integer (long) from the buffer.
  73.   def get_long
  74.     get(4).unpack('l')
  75.   end
  76.  
  77.   # Get a 32-bit unsigned integer (long) from the buffer
  78.   def get_ulong
  79.     get(4).unpack('L')
  80.   end
  81.  
  82.   # Get a null ('\0') terminated string from the buffer.
  83.   def get_string
  84.     zero_byte = @buffer.index('\0',@position)
  85.     if zero_byte == nil
  86.       string = ''
  87.     else
  88.       string = get(zero_byte-@position)
  89.       @position+=2
  90.     end
  91.     string
  92.   end
  93.  
  94. end
Advertisement
Add Comment
Please, Sign In to add comment