-1

I am trying to save compressed strings to a file and load them later for use in the game. I kept getting "in 'finish': buffer error" errors when loading the data back up for use. I came up with this:

    require "zlib"

    def deflate(string)
      zipper = Zlib::Deflate.new
      data = zipper.deflate(string, Zlib::FINISH)
    end

    def inflate(string)
      zstream = Zlib::Inflate.new
      buf = zstream.inflate(string)
      zstream.finish
      zstream.close
      buf
    end

    setting = ["nothing","nada","nope"]
    taggedskills = ["nothing","nada","nope","nuhuh"]

    File.open('testzip.txt','wb') do |w|
        w.write(deflate("hello world")+"\n")
        w.write(deflate("goodbye world")+"\n")
        w.write(deflate("etc")+"\n")
        w.write(deflate("etc")+"\n")
        w.write(deflate("Setting: name "+setting[0]+" set"+(setting[1].class == String ? "str" : "num")+" "+setting[1].to_s)+"\n")
        w.write(deflate("Taggedskill: "+taggedskills[0]+" "+taggedskills[1]+" "+taggedskills[2]+" "+taggedskills[3])+"\n")
        w.write(deflate("etc")+"\n")
    end

    File.open('testzip.txt','rb') do |file|
        file.each do |line|
            p inflate(line)
        end
    end

It was throwing errors at the "Taggedskill:" point. I don't know what it is, but trying to change it to "Skilltag:", "Skillt:", etc. continues to throw a buffer error, while things like "Setting:" or "Thing:" work fine, while changing the setting line to "Taggedskill:" continues to work fine. What is going on here?

sawa
  • 156,411
  • 36
  • 254
  • 350
user1796160
  • 437
  • 2
  • 5
  • 12

1 Answers1

1

In testzip.txt, you are storing newline separated binary blobs. However, binary blobs may contain newlines by themselves, so when you open testzip.txt and split it by line, you may end up splitting one binary blob that inflate would understand, into two binary blobs that it does not understand.

Try to run wc -l testzip.txt after you get the error. You'll see the file contains one more line, than the number of lines you are putting in.

What you need to do, is compress the whole file at once, not line by line.

Tobi
  • 65,270
  • 5
  • 29
  • 36