可以使用AF_ALG进行压缩,以下是一个使用AF_ALG进行zlib压缩和解压缩的示例代码:
压缩:
#include
#include
#include
#include
#include
#include
#define BUFSIZE 4096
int zlib_compress(int algfd, const uint8_t *src, size_t srclen, uint8_t *dst, size_t *dstlen) {
int ret = -1;
unsigned char buffer[BUFSIZE];
z_stream zs;
memset(&zs, 0, sizeof(zs));
zs.zalloc = Z_NULL;
zs.zfree = Z_NULL;
zs.opaque = Z_NULL;
if (deflateInit(&zs, Z_DEFAULT_COMPRESSION) != Z_OK) {
printf("deflateInit error.\n");
goto exit;
}
zs.next_in = (Bytef *)src;
zs.avail_in = srclen;
while (zs.avail_in > 0) {
zs.next_out = buffer;
zs.avail_out = BUFSIZE;
int ret = deflate(&zs, Z_NO_FLUSH);
if (ret == Z_STREAM_ERROR || (ret == Z_BUF_ERROR && zs.avail_in != 0)) {
printf("deflate error.\n");
goto cleanup;
}
size_t have = BUFSIZE - zs.avail_out;
if (write(algfd, buffer, have) != have) {
printf("write error.\n");
goto cleanup;
}
}
for (;;) {
zs.next_out = buffer;
zs.avail_out = BUFSIZE;
ret = deflate(&zs, Z_FINISH);
if (ret == Z_STREAM_ERROR || (ret == Z_BUF_ERROR && zs.avail_in != 0)) {
printf("deflate error.\n");
goto cleanup;
}
size_t have = BUFSIZE - zs.avail_out;
if (write(algfd, buffer, have) != have) {
printf("write error.\n");
goto cleanup;
}
if (ret == Z_STREAM_END) {