Debian Codegraph @

CorsixTH/Src/lua_rnc.cpp

raw
1 #include "lua_rnc.h"
2
3 #include "config.h"
4
5 #include <array>
6
7 #include "rnc.h"
8 #include "th_lua.h"
9
10 //! Provides lua function to decompress RNC data
11 /*!
12 @param L Lua state where the function is called from. In lua a call
13 to this function has one parameter which is the RNC compressed data.
14 The return value is the decompressed data.
15 */
16
17 namespace {
18
19 int l_decompress(lua_State* L) {
20 size_t inlen;
21 const uint8_t* in =
22 reinterpret_cast<const uint8_t*>(luaL_checklstring(L, 1, &inlen));
23
24 // Verify that the data contains an RNC signature, and that the input
25 // size matches the size specified in the data header.
26 if (inlen < rnc_header_size || inlen != rnc_input_size(in)) {
27 lua_pushnil(L);
28 lua_pushliteral(L, "Input is not RNC compressed data");
29 return 2;
30 }
31 size_t outlen = rnc_output_size(in);
32
33 // Allocate scratch area as Lua userdata so that if something horrible
34 // happens, it'll be cleaned up by Lua's GC. Remember that most Lua API
35 // calls can throw errors, so they all have to be wrapped with code to
36 // detect errors and free the buffer if said buffer was not managed by Lua.
37 void* outbuf = lua_newuserdata(L, outlen);
38
39 lua_pushnil(L);
40 switch (rnc_unpack(in, (uint8_t*)outbuf)) {
41 case rnc_status::ok:
42 lua_pushlstring(L, (const char*)outbuf, outlen);
43 return 1;
44
45 case rnc_status::file_is_not_rnc:
46 lua_pushliteral(L, "Input is not RNC compressed data");
47 break;
48
49 case rnc_status::huf_decode_error:
50 lua_pushliteral(L, "Invalid Huffman coding");
51 break;
52
53 case rnc_status::file_size_mismatch:
54 lua_pushliteral(L, "Size mismatch");
55 break;
56
57 case rnc_status::packed_crc_error:
58 lua_pushliteral(L, "Incorrect packed CRC");
59 break;
60
61 case rnc_status::unpacked_crc_error:
62 lua_pushliteral(L, "Incorrect unpacked CRC");
63 break;
64
65 default:
66 lua_pushliteral(L, "Unknown error decompressing RNC data");
67 break;
68 }
69 return 2;
70 }
71
72 constexpr std::array<luaL_Reg, 2> rnclib{
73 {{"decompress", l_decompress}, {nullptr, nullptr}}};
74
75 } // namespace
76
77 int luaopen_rnc(lua_State* L) {
78 luaT_register(L, "rnc", rnclib);
79 return 1;
80 }