Advertisement
Zeriab

[RGSS] StringBuffer

Jan 31st, 2014
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 2.12 KB | None | 0 0
  1. class StringBuffer < IO
  2.    MODE_STRING = 1
  3.    MODE_FILE_MARSHAL = 2
  4.    MODE_FILE_BINMODE = 3
  5.    
  6.    attr_reader :mtime
  7.    ##
  8.    # Initialization of the String Buffer
  9.    # The mode can be MODE_STRING, MODE_FILE_MARSHAL or MODE_FILE_BINMODE
  10.    #
  11.    def initialize(data = nil, mode = MODE_FILE_MARSHAL, compressed = true)
  12.      if data.nil?
  13.        @data = ''
  14.      else
  15.        # Check which type the data is
  16.        case mode
  17.        when MODE_STRING
  18.          @data = data
  19.        when MODE_FILE_MARSHAL
  20.          if FileTest.exists?(data)
  21.            File.open(data, 'rb') {|f|
  22.              @mtime = f.mtime
  23.            }
  24.          end
  25.          begin
  26.            @data = load_data(data)
  27.          rescue
  28.            @data = ''
  29.          end
  30.        when MODE_FILE_BINMODE
  31.          if FileTest.exists?(data)
  32.            File.open(data, 'rb') {|f|
  33.              f.binmode
  34.              self.mtime = f.mtime
  35.              @data = f.read
  36.            }
  37.          end
  38.        end
  39.        # Decompress the data if it is compressed
  40.        if compressed
  41.          @data = Zlib::Inflate.inflate(@data)
  42.        end
  43.      end
  44.    end
  45.  
  46.    ##
  47.    # Save to file
  48.    # The mode can be MODE_FILE_MARSHAL or MODE_FILE_BINMODE
  49.    #
  50.    def save(filename, mode = MODE_FILE_MARSHAL, compress = true)
  51.      # Check whether the data should be compressed
  52.      if compress
  53.        data = Zlib::Deflate.deflate(@data)
  54.      else
  55.        data = @data
  56.      end
  57.      # Check whether to save in binary or marshal mode
  58.      case mode
  59.      when MODE_FILE_MARSHAL
  60.        save_data(data, filename)
  61.      when MODE_FILE_BINMODE
  62.        File.open(filename, 'w+') {|f|
  63.          f.binmode
  64.          f.print data
  65.        }
  66.      end
  67.      data
  68.    end
  69.  
  70.    ##
  71.    # Get data
  72.    #
  73.    def data
  74.      return @data
  75.    end
  76.  
  77.    ##
  78.    # Binary mode
  79.    #
  80.    def binmode
  81.      # Do nothing
  82.    end
  83.  
  84.    ##
  85.    # Write data
  86.    #
  87.    def write(data)
  88.      @data += data
  89.    end
  90.  
  91.    ##
  92.    # Get char
  93.    #
  94.    def getc
  95.      return @data.slice!(0)
  96.    end
  97.  
  98.    ##
  99.    # Read an amount of bytes
  100.    #
  101.    def read(amount)
  102.      return @data.slice!(0...amount)
  103.    end
  104. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement