]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.fastlz/native/fastlz_write.c
Merge commit '876ede6'
[simantics/platform.git] / bundles / org.simantics.fastlz / native / fastlz_write.c
1 /*******************************************************************************\r
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
3  * in Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 #include <stdio.h>\r
13 #include <stdlib.h>\r
14 #include <string.h>\r
15 #include "fastlz.h"\r
16 \r
17 #define BLOCKSIZE (128*1024)\r
18 \r
19 char* uncompressed;\r
20 int uncompressedCapacity;\r
21 int position;\r
22 char* compressed;\r
23 int compressedCapacity;\r
24 \r
25 FILE* handle;\r
26 \r
27 void initWrite(FILE* _handle) {\r
28     uncompressedCapacity = BLOCKSIZE;\r
29     uncompressed = malloc(uncompressedCapacity);\r
30     position = 0;\r
31     compressedCapacity = 8 + BLOCKSIZE + (BLOCKSIZE/20);\r
32     compressed = malloc(compressedCapacity);\r
33     handle = _handle;\r
34 }\r
35 \r
36 void flushBuffer() {\r
37     int uncompressedSize = position;\r
38     int compressedSize = fastlz_compress(uncompressed, uncompressedSize, compressed+8);\r
39 \r
40     ((int*)compressed)[0] = compressedSize;\r
41     ((int*)compressed)[1] = uncompressedSize;\r
42     \r
43     fwrite(compressed, compressedSize+8, 1, handle);\r
44     position = 0;\r
45 }\r
46 \r
47 void deinitWrite() {\r
48     flushBuffer();\r
49 \r
50     ((int*)compressed)[0] = 0;\r
51     ((int*)compressed)[1] = 0;    \r
52     fwrite(compressed, 8, 1, handle);\r
53 \r
54     free(uncompressed);\r
55     uncompressed = 0;\r
56     free(compressed);\r
57     compressed = 0;\r
58     handle = 0;\r
59 }\r
60 \r
61 void write(char* data, int offset, int length) {\r
62     int s;\r
63 \r
64     while(length > uncompressedCapacity - position) {\r
65         s = uncompressedCapacity - position;\r
66         memcpy(uncompressed + position, data + offset, s);\r
67         offset += s;\r
68         length -= s;\r
69         position += s;\r
70         flushBuffer();\r
71     }\r
72     memcpy(uncompressed + position, data + offset, length);\r
73     position += length;\r
74 }\r