Is it possible to compress a string the way a text file can be compressed?

Is it possible to compress a string the way a text file can be compressed?

If yes, how can it be done using Crystal?

I think could essentially just do something like:

require "compress/gzip"
 
compressed_string = String.build do |io|
  Compress::Gzip::Writer.open(io) do |gzip|
    gzip << "Compress me"
  end
end

Tho what’s your use case for wanting to do this?

Thanks a lot.

It could come in handy to reduce the size of my (very crude) prototype of virtual file system: GitHub - serge-hulne/bakerstreet: Virtual file system for servers written in Crystal lang (aimed at embedding text resources (.html, .css,. js) in app)

The idea behind this vfs is : shipping Webview-based apps as one single file (the html, css, js, svg resources being embedded in the executable).

The two obvious candidates for vfs under Crystal don’t work at the moment under Windows, yet I want my system to be portable between macOS, Linux and Windows, so I resorted to write my own vfs.

PS: If I may : how do you carry out the reverse operation (decompression of the compressed string) ?

The endgame is : I’m working on a clone of Wails which uses Crystal in place of Go.

I expect my first 100% cross-platform version to be ready very soon.

3 Likes

Probably something like:

io = IO::Memory.new compressed_string

string = Compress::Gzip::Reader.open(io) do |gzip|
  gzip.gets_to_end
end

Thanks!