-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Compress.c
92 lines (80 loc) · 2.33 KB
/
Compress.c
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Copyright CircumScriptor and DarkNeutrino 2021
#include <Server/Structs/ServerStruct.h>
#include <Util/Compress.h>
#include <Util/Log.h>
#include <Util/Queue.h>
#include <Util/Utlist.h>
#include <Util/Alloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <zlib.h>
static z_stream* g_compressor = NULL;
/**
* @brief Initialize compressor library (global compressor)
*
* @param level Level of compression
* @return 0 on success
*/
static int _compress_init(server_t* server, int level)
{
(void) server;
if (g_compressor != NULL) {
LOG_ERROR("Compressor is already initialized");
return 1;
} else {
g_compressor = (z_stream*) spadesx_malloc(sizeof(z_stream));
}
g_compressor->zalloc = Z_NULL;
g_compressor->zfree = Z_NULL;
g_compressor->opaque = Z_NULL;
if (deflateInit(g_compressor, level) < 0) {
LOG_ERROR("Failed to initialize compressor");
return 1;
}
return 0;
}
/**
* @brief Close compressor library (global compressor)
*
* @return 0 on success
*/
static int _compress_close(void)
{
if (g_compressor == NULL) {
LOG_ERROR("Compressor is not initialized");
return 1;
}
if (deflateEnd(g_compressor) != 0) {
LOG_ERROR("Failed to close compressor");
return 1;
}
free(g_compressor);
g_compressor = NULL;
return 0;
}
queue_t* compress_queue(server_t* server, uint8_t* data, uint32_t length, uint32_t chunkSize)
{
_compress_init(server, 5);
if (g_compressor == NULL) {
LOG_ERROR("Compressor is not initialized");
return NULL;
}
queue_t* parent = NULL;
queue_t* node;
g_compressor->next_in = (uint8_t*) data;
g_compressor->avail_in = length;
do {
node = (queue_t*) spadesx_malloc(sizeof(*node));
node->block = (uint8_t*) spadesx_malloc(chunkSize);
g_compressor->avail_out = chunkSize;
g_compressor->next_out = node->block;
if (deflate(g_compressor, Z_FINISH) < 0) {
LOG_ERROR("Failed to compress data");
return NULL;
}
node->length = chunkSize - g_compressor->avail_out;
DL_APPEND(parent, node);
} while (g_compressor->avail_out == 0);
_compress_close();
return parent;
}