Skip to content

Instantly share code, notes, and snippets.

@fowlmouth
Created August 28, 2012 19:51
Show Gist options
  • Save fowlmouth/3503440 to your computer and use it in GitHub Desktop.
Save fowlmouth/3503440 to your computer and use it in GitHub Desktop.
import zlib
proc compress(source: string): string =
var
sourcelen = source.len
destlen = sourcelen + (sourcelen.float * 0.1).int + 16
result = ""
result.setLen destLen
var res = zlib.compress(cstring(result), addr destLen, cstring(source), sourceLen)
if res != Z_OK:
echo "Error occured: ", res
elif destLen < result.len:
result.setLen(destLen)
proc uncompress(source: string): string =
var
sourceLen = source.len
destLen = sourceLen + (sourcelen * 100).int + 64
result = ""
result.setLen destLen
var res = zlib.uncompress(cstring(result), addr destLen, cstring(source), sourceLen)
if res != Z_OK:
echo "Error occured: ", res
elif destLen != result.len: #this should always happen
result.setLen destLen
when isMainModule:
import strutils
var r = compress("Hello")
echo repr(r)
var rr = uncompress(r)
echo repr(rr)
assert rr == "Hello"
proc `*`(a: string; b: int): string {.inline.} = result = repeatStr(b, a)
var s = "yo dude sup bruh homie" * 50
r = compress(s)
echo s.len, " -> ", r.len
rr = uncompress(r)
echo r.len, " -> ", rr.len
assert rr == s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment