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