Document of c-modernization-kit (porter) 1.0.0

Loading...
Searching...
No Matches
compress_linux.c
Go to the documentation of this file.
1
18
19#ifndef _WIN32
20
21 #include <string.h>
22
23 #include <arpa/inet.h>
24 #include <zlib.h>
25
26 #include "compress.h"
27
28/* doxygen コメントはヘッダに記載 */
29 int potr_compress(uint8_t *dst, size_t *dst_len, const uint8_t *src, size_t src_len)
30{
31 uint32_t orig_len_nbo;
32 z_stream z;
33 int ret;
34
35 if (dst == NULL || dst_len == NULL || src == NULL || src_len == 0)
36 {
37 return -1;
38 }
39
40 if (*dst_len < POTR_COMPRESS_HEADER_SIZE + 1U)
41 {
42 return -1;
43 }
44
45 /* 先頭 4 バイトに元サイズ (NBO) を書く */
46 orig_len_nbo = htonl((uint32_t)src_len);
47 memcpy(dst, &orig_len_nbo, POTR_COMPRESS_HEADER_SIZE);
48
49 /* raw DEFLATE (windowBits = -15) で圧縮 */
50 memset(&z, 0, sizeof(z));
51 z.next_in = (Bytef *)(uintptr_t)src;
52 z.avail_in = (uInt)src_len;
53 z.next_out = dst + POTR_COMPRESS_HEADER_SIZE;
54 z.avail_out = (uInt)(*dst_len - POTR_COMPRESS_HEADER_SIZE);
55
56 if (deflateInit2(&z, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK)
57 {
58 return -1;
59 }
60
61 ret = deflate(&z, Z_FINISH);
62 deflateEnd(&z);
63
64 if (ret != Z_STREAM_END)
65 {
66 return -1;
67 }
68
69 *dst_len = POTR_COMPRESS_HEADER_SIZE + (size_t)z.total_out;
70 return 0;
71}
72
73/* doxygen コメントはヘッダに記載 */
74 int potr_decompress(uint8_t *dst, size_t *dst_len, const uint8_t *src, size_t src_len)
75{
76 uint32_t orig_len_nbo;
77 uint32_t orig_len;
78 z_stream z;
79 int ret;
80
81 if (dst == NULL || dst_len == NULL || src == NULL || src_len <= POTR_COMPRESS_HEADER_SIZE)
82 {
83 return -1;
84 }
85
86 /* 先頭 4 バイトから元サイズを取得 */
87 memcpy(&orig_len_nbo, src, POTR_COMPRESS_HEADER_SIZE);
88 orig_len = ntohl(orig_len_nbo);
89
90 if (*dst_len < (size_t)orig_len)
91 {
92 return -1;
93 }
94
95 /* raw DEFLATE を解凍 */
96 memset(&z, 0, sizeof(z));
97 z.next_in = (Bytef *)(uintptr_t)(src + POTR_COMPRESS_HEADER_SIZE);
98 z.avail_in = (uInt)(src_len - POTR_COMPRESS_HEADER_SIZE);
99 z.next_out = (Bytef *)dst;
100 z.avail_out = (uInt)*dst_len;
101
102 if (inflateInit2(&z, -15) != Z_OK)
103 {
104 return -1;
105 }
106
107 ret = inflate(&z, Z_FINISH);
108 inflateEnd(&z);
109
110 if (ret != Z_STREAM_END)
111 {
112 return -1;
113 }
114
115 *dst_len = (size_t)z.total_out;
116 return 0;
117}
118
119#else /* _WIN32 */
120 #pragma warning(disable : 4206)
121#endif /* _WIN32 */
compress.h
データ圧縮・解凍モジュールの内部ヘッダー。
POTR_COMPRESS_HEADER_SIZE
#define POTR_COMPRESS_HEADER_SIZE
圧縮ペイロード先頭に付加する元サイズフィールドのバイト数。
Definition compress.h:39
potr_decompress
int potr_decompress(uint8_t *dst, size_t *dst_len, const uint8_t *src, size_t src_len)
圧縮データを解凍します。
Definition compress_linux.c:74
potr_compress
int potr_compress(uint8_t *dst, size_t *dst_len, const uint8_t *src, size_t src_len)
データを圧縮します。
Definition compress_linux.c:29