forked from forhappy/lua-snappy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lua-snappy.cc
103 lines (95 loc) · 2.81 KB
/
lua-snappy.cc
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
93
94
95
96
97
98
99
100
101
102
103
/*
* ========================================================================
*
* Filename: lua-snappy.c
*
* Description: Google snappy lua binding.
*
* Created: 03/30/2013 08:17:59 PM
*
* Author: Fu Haiping (forhappy), haipingf@gmail.com
* Company: ICT ( Institute Of Computing Technology, CAS )
*
* ========================================================================
*/
#include <stdio.h>
#include <stdlib.h>
extern "C" {
#include <lua.h>
#include <lauxlib.h>
int luaopen_snappy(lua_State *L);
}
#include "snappy/snappy-c.h"
static int lsnappy_compress(lua_State *L)
{
size_t src_len = 0;
const char* src = luaL_checklstring(L, 1, &src_len);
size_t dst_max_size = snappy_max_compressed_length(src_len);
char* dstmem = (char*)malloc(dst_max_size);
if (dstmem != NULL) {
if (snappy_compress(src, src_len, dstmem,
&dst_max_size) == SNAPPY_OK) {
lua_pushlstring(L, dstmem, dst_max_size);
free(dstmem);
return 1;
}
free(dstmem);
}
return luaL_error(L, "snappy: not enough memory.");
}
static int lsnappy_uncompress(lua_State *L)
{
size_t src_len = 0;
size_t dst_max_size = 0;
const char* src = luaL_checklstring(L, 1, &src_len);
if (snappy_uncompressed_length(src, src_len, &dst_max_size)
!= SNAPPY_OK) {
lua_pushlstring(L, "", 0);
}
char* dstmem = (char*)malloc(dst_max_size);
if (dstmem != NULL) {
if (snappy_uncompress(src, src_len, dstmem,
&dst_max_size) == SNAPPY_OK) {
lua_pushlstring(L, dstmem, dst_max_size);
free(dstmem);
return 1;
}
free(dstmem);
}
return luaL_error(L, "snappy: not enough memory.");
}
static int lsnappy_validate_compressed_buffer(lua_State *L)
{
size_t src_len = 0;
size_t dst_max_size = 0;
const char* src = luaL_checklstring(L, 1, &src_len);
if(snappy_validate_compressed_buffer(src, src_len) == SNAPPY_OK) {
lua_pushboolean(L, 1);
return 1;
}
lua_pushboolean(L, 0);
return 1;
}
static const luaL_Reg snappy[] =
{
{"compress", lsnappy_compress},
{"uncompress", lsnappy_uncompress},
{"decompress", lsnappy_uncompress},
{"validate_compressed_buffer", lsnappy_validate_compressed_buffer},
{NULL, NULL}
};
int luaopen_snappy(lua_State *L)
{
#if LUA_VERSION_NUM == 502
luaL_newlib(L, snappy);
#else
luaL_register(L, "snappy", snappy);
#endif
lua_pushliteral (L, "Copyright (C) 2013 Fu Haiping(forhappy)");
lua_setfield(L, -2, "_COPYRIGHT");
lua_pushliteral (L, "lua-snappy: lua binding of google's snappy(a fast compressor/decompressor)");
lua_setfield(L, -2, "_DESCRIPTION");
lua_pushliteral (L, "0.1.0");
lua_setfield(L, -2, "_VERSION");
return 1;
}