@@ -2,8 +2,8 @@ use std::ops::{Deref, DerefMut};
22
33use bytes:: Bytes ;
44use mlua:: {
5- BorrowedBytes , Error , FromLua , Lua , MetaMethod , Result , String as LuaString , UserData , UserDataMethods ,
6- UserDataRegistry , Value ,
5+ BorrowedBytes , Error , FromLua , Lua , MetaMethod , Result , String as LuaString , Table , UserData ,
6+ UserDataMethods , UserDataRegistry , Value ,
77} ;
88
99/// A Lua userdata wrapper around [`Bytes`].
@@ -28,6 +28,10 @@ impl DerefMut for LuaBytes {
2828
2929impl UserData for LuaBytes {
3030 fn register ( registry : & mut UserDataRegistry < Self > ) {
31+ registry. add_function ( "new" , |_, data : LuaString | {
32+ Ok ( Self ( Bytes :: copy_from_slice ( & data. as_bytes ( ) ) ) )
33+ } ) ;
34+
3135 registry. add_method ( "len" , |_, this, ( ) | Ok ( this. len ( ) ) ) ;
3236
3337 registry. add_method ( "is_empty" , |_, this, ( ) | Ok ( this. is_empty ( ) ) ) ;
@@ -95,3 +99,18 @@ impl Deref for AsBytesRefImpl<'_> {
9599 }
96100 }
97101}
102+
103+ /// A loader for the `bytes` module.
104+ fn loader ( lua : & Lua ) -> Result < Table > {
105+ let t = lua. create_table ( ) ?;
106+ t. set ( "Bytes" , lua. create_proxy :: < LuaBytes > ( ) ?) ?;
107+ Ok ( t)
108+ }
109+
110+ /// Registers the `bytes` module in the given Lua state.
111+ pub fn register ( lua : & Lua , name : Option < & str > ) -> Result < Table > {
112+ let name = name. unwrap_or ( "@bytes" ) ;
113+ let value = loader ( lua) ?;
114+ lua. register_module ( name, & value) ?;
115+ Ok ( value)
116+ }
0 commit comments