-
Notifications
You must be signed in to change notification settings - Fork 2
/
buffer.go
58 lines (49 loc) · 996 Bytes
/
buffer.go
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
package purr
import (
"bytes"
"fmt"
"io"
"crypto/md5"
lua "github.com/yuin/gopher-lua"
)
const luaBufferTypeName = "buffer"
func luaBufferLoader(L *lua.LState) int {
mod := L.SetFuncs(L.NewTable(), bufferExports)
L.Push(mod)
return 1
}
var bufferExports = map[string]lua.LGFunction{
"size": bufferSize,
"get_md5": getBufMD5,
}
func bufferSize(L *lua.LState) int {
buf := getBufferUserData(L, 1)
if buf == nil {
return 0
}
L.Push(lua.LNumber(buf.Len()))
return 1
}
func getBufMD5(L *lua.LState) int {
buf := getBufferUserData(L, 1)
if buf == nil {
return 0
}
h := md5.New()
if _, err := io.Copy(h, buf); err != nil {
L.ArgError(1, err.Error())
return 0
}
md5Str := fmt.Sprintf("%x", h.Sum(nil))
L.Push(lua.LString(md5Str))
return 1
}
func getBufferUserData(L *lua.LState, index int) *bytes.Buffer {
ud := L.CheckUserData(index)
buf, ok := ud.Value.(*bytes.Buffer)
if !ok {
L.ArgError(index, "bytes.buffer expected!!")
return nil
}
return buf
}