77#include < bee/nonstd/unreachable.h>
88
99namespace bee ::lua_socket {
10+ #if LUA_VERSION_NUM >= 505
11+ struct luabuf {
12+ luabuf (lua_State* L, size_t len) {
13+ allocf = lua_getallocf (L, &ud);
14+ buf = (char *)allocf (ud, NULL , 0 , (size_t )len + 1 );
15+ this ->len = len;
16+ }
17+ ~luabuf () {
18+ if (buf) {
19+ allocf (ud, buf, (size_t )len + 1 , 0 );
20+ }
21+ }
22+ void pushresultsize (lua_State* L, int rc) {
23+ buf[rc] = ' \0 ' ;
24+ lua_pushexternalstring (L, buf, rc, allocf, ud);
25+ buf = nullptr ;
26+ }
27+ void * ud;
28+ lua_Alloc allocf;
29+ char * buf;
30+ size_t len;
31+ };
32+ #endif
33+
1034 namespace endpoint {
1135 static int value (lua_State* L) {
1236 const auto & ep = lua::checkudata<net::endpoint>(L, 1 );
@@ -166,9 +190,8 @@ namespace bee::lua_socket {
166190 static int recv (lua_State* L, net::fd_t fd) {
167191 auto len = lua::optinteger<int , LUAL_BUFFERSIZE>(L, 2 );
168192#if LUA_VERSION_NUM >= 505
169- void * ud;
170- lua_Alloc allocf = lua_getallocf (L, &ud);
171- char * buf = (char *)allocf (ud, NULL , 0 , (size_t )len + 1 );
193+ luabuf b (L, (size_t )len);
194+ char * buf = b.buf ;
172195#else
173196 luaL_Buffer b;
174197 luaL_buffinit (L, &b);
@@ -184,8 +207,7 @@ namespace bee::lua_socket {
184207 return 1 ;
185208 case net::socket::recv_status::success:
186209#if LUA_VERSION_NUM >= 505
187- buf[rc] = ' \0 ' ;
188- lua_pushexternalstring (L, buf, rc, allocf, ud);
210+ b.pushresultsize (L, rc);
189211#else
190212 luaL_pushresultsize (&b, rc);
191213#endif
@@ -216,9 +238,8 @@ namespace bee::lua_socket {
216238 auto len = lua::optinteger<int , LUAL_BUFFERSIZE>(L, 2 );
217239 auto & ep = lua::newudata<net::endpoint>(L);
218240#if LUA_VERSION_NUM >= 505
219- void * ud;
220- lua_Alloc allocf = lua_getallocf (L, &ud);
221- char * buf = (char *)allocf (ud, NULL , 0 , (size_t )len + 1 );
241+ luabuf b (L, (size_t )len);
242+ char * buf = b.buf ;
222243#else
223244 luaL_Buffer b;
224245 luaL_buffinit (L, &b);
@@ -228,8 +249,7 @@ namespace bee::lua_socket {
228249 switch (net::socket::recvfrom (fd, rc, ep, buf, len)) {
229250 case net::socket::status::success:
230251#if LUA_VERSION_NUM >= 505
231- buf[rc] = ' \0 ' ;
232- lua_pushexternalstring (L, buf, rc, allocf, ud);
252+ b.pushresultsize (L, rc);
233253#else
234254 luaL_pushresultsize (&b, rc);
235255#endif
0 commit comments