zlib_helpers.nim 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # xxx this test is bad (echo instead of error, etc)
  2. import zip/zlib
  3. proc compress*(source: string): string =
  4. var
  5. sourcelen = source.len
  6. destLen = sourcelen + (sourcelen.float * 0.1).int + 16
  7. result = ""
  8. result.setLen destLen
  9. # see http://www.zlib.net/zlib-1.2.11.tar.gz for correct definitions
  10. var destLen2 = destLen.Ulongf
  11. var res = zlib.compress(cstring(result), addr destLen2, cstring(source), sourceLen.Ulong)
  12. if res != Z_OK:
  13. echo "Error occurred: ", res
  14. elif destLen2.int < result.len:
  15. result.setLen(destLen2.int)
  16. proc uncompress*(source: string, destLen: var int): string =
  17. result = ""
  18. result.setLen destLen
  19. var destLen2 = destLen.Ulongf
  20. var res = zlib.uncompress(cstring(result), addr destLen2, cstring(source), source.len.Ulong)
  21. if res != Z_OK:
  22. echo "Error occurred: ", res
  23. when true:
  24. import strutils
  25. var r = compress("Hello")
  26. echo repr(r)
  27. var ln = "Hello".len
  28. var rr = uncompress(r, ln)
  29. echo repr(rr)
  30. assert rr == "Hello"
  31. proc `*`(a: string; b: int): string {.inline.} = result = repeat(a, b)
  32. var s = "yo dude sup bruh homie" * 50
  33. r = compress(s)
  34. echo s.len, " -> ", r.len
  35. ln = s.len
  36. rr = uncompress(r, ln)
  37. echo r.len, " -> ", rr.len
  38. assert rr == s