|
| 1 | +// Package hex implements hex encode/decode functionality for lua. |
| 2 | +package hex |
| 3 | + |
| 4 | +import ( |
| 5 | + "encoding/hex" |
| 6 | + "io" |
| 7 | + |
| 8 | + lio "github.com/vadv/gopher-lua-libs/io" |
| 9 | + lua "github.com/yuin/gopher-lua" |
| 10 | +) |
| 11 | + |
| 12 | +const ( |
| 13 | + hexEncoderType = "hex.Encoder" |
| 14 | + hexDecoderType = "hex.Decoder" |
| 15 | +) |
| 16 | + |
| 17 | +// LVHexEncoder creates a new Lua user data for the hex encoder |
| 18 | +func LVHexEncoder(L *lua.LState, writer io.Writer) lua.LValue { |
| 19 | + ud := L.NewUserData() |
| 20 | + ud.Value = writer |
| 21 | + L.SetMetatable(ud, L.GetTypeMetatable(hexEncoderType)) |
| 22 | + return ud |
| 23 | +} |
| 24 | + |
| 25 | +// LVHexDecoder creates a new Lua user data for the hex decoder |
| 26 | +func LVHexDecoder(L *lua.LState, reader io.Reader) lua.LValue { |
| 27 | + ud := L.NewUserData() |
| 28 | + ud.Value = reader |
| 29 | + L.SetMetatable(ud, L.GetTypeMetatable(hexDecoderType)) |
| 30 | + return ud |
| 31 | +} |
| 32 | + |
| 33 | +// DecodeString decodes the encoded string with the encoding |
| 34 | +func DecodeString(L *lua.LState) int { |
| 35 | + encoded := L.CheckString(1) |
| 36 | + L.Pop(L.GetTop()) |
| 37 | + decoded, err := hex.DecodeString(encoded) |
| 38 | + if err != nil { |
| 39 | + L.Push(lua.LNil) |
| 40 | + L.Push(lua.LString(err.Error())) |
| 41 | + return 2 |
| 42 | + } |
| 43 | + L.Push(lua.LString(decoded)) |
| 44 | + return 1 |
| 45 | +} |
| 46 | + |
| 47 | +// EncodeToString decodes the string with the encoding |
| 48 | +func EncodeToString(L *lua.LState) int { |
| 49 | + decoded := L.CheckString(1) |
| 50 | + L.Pop(L.GetTop()) |
| 51 | + encoded := hex.EncodeToString([]byte(decoded)) |
| 52 | + L.Push(lua.LString(encoded)) |
| 53 | + return 1 |
| 54 | +} |
| 55 | + |
| 56 | +// registerHexEncoder Registers the encoder type and its methods |
| 57 | +func registerHexEncoder(L *lua.LState) { |
| 58 | + mt := L.NewTypeMetatable(hexEncoderType) |
| 59 | + L.SetGlobal(hexEncoderType, mt) |
| 60 | + L.SetField(mt, "__index", lio.WriterFuncTable(L)) |
| 61 | +} |
| 62 | + |
| 63 | +// registerHexDecoder Registers the decoder type and its methods |
| 64 | +func registerHexDecoder(L *lua.LState) { |
| 65 | + mt := L.NewTypeMetatable(hexDecoderType) |
| 66 | + L.SetGlobal(hexDecoderType, mt) |
| 67 | + L.SetField(mt, "__index", lio.ReaderFuncTable(L)) |
| 68 | +} |
| 69 | + |
| 70 | +func NewEncoder(L *lua.LState) int { |
| 71 | + writer := lio.CheckIOWriter(L, 1) |
| 72 | + L.Pop(L.GetTop()) |
| 73 | + encoder := hex.NewEncoder(writer) |
| 74 | + L.Push(LVHexEncoder(L, encoder)) |
| 75 | + return 1 |
| 76 | +} |
| 77 | + |
| 78 | +func NewDecoder(L *lua.LState) int { |
| 79 | + reader := lio.CheckIOReader(L, 1) |
| 80 | + L.Pop(L.GetTop()) |
| 81 | + decoder := hex.NewDecoder(reader) |
| 82 | + L.Push(LVHexDecoder(L, decoder)) |
| 83 | + return 1 |
| 84 | +} |
0 commit comments