File: Compress.k

package info (click to toggle)
kaya 0.2.0-6
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 3,012 kB
  • ctags: 1,307
  • sloc: cpp: 6,691; haskell: 4,833; sh: 2,868; yacc: 768; makefile: 700; perl: 87
file content (58 lines) | stat: -rw-r--r-- 1,576 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/** -*-C-*-ish
    Kaya standard library
    Copyright (C) 2004, 2005 Edwin Brady

    This file is distributed under the terms of the GNU Lesser General
    Public Licence. See COPYING for licence.
*/

module Compress; 

import Regex;
import Prelude;
import Strings;
import Binary;

%include "zlib_glue.h";
%imported "zlib_glue";
%link "z";

foreign "zlib_glue.o" {
    Ptr compressBuffer(Ptr ind, Int len, outint buflen) = compressBuffer;
    Ptr uncompressBuffer(Ptr ind, Int len, outint buflen) = uncompressBuffer;
}

"Compress a block of binary data."
public Binary compressBinary(Binary b)
{
    initlen = blockSize(b);
    buflen = 0;
    dat = compressBuffer(blockData(b), initlen, buflen);
    return createInitialisedBlock(dat, buflen);
}

"Uncompress a block of binary data (you must know the uncompressed length)"
public Binary uncompressBinary(Binary b, var Int outlen) {
    newdat = uncompressBuffer(blockData(b), blockSize(b), outlen);
    return createInitialisedBlock(newdat, outlen);
}

"Compress a string"
public String compressString(String instr) {
  initlen = byteLength(instr)+1;
  b = createBlock(initlen);
  pokeString(b,0,instr);
  bin = compressBinary(b);
  outstr = String(initlen)+"\n"+Binary::base64Encode(bin);
  return outstr;
}

"Uncompress a string generated with compressString.
Unlike uncompressBinary you do not need to know the original length"
public String uncompressString(String instr) {
  odata = split("\n",instr);
  bin = Binary::base64Decode(odata[1]);
  raw = uncompressBinary(bin,Int(odata[0]));
  return peekString(raw,0);
}