/
zerialize.go
97 lines (78 loc) · 1.69 KB
/
zerialize.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package minetest
import (
"bytes"
"errors"
"fmt"
"io"
"strconv"
)
func SerializeString(s func(io.Writer) error) (string, error) {
buf := &bytes.Buffer{}
err := s(buf)
return buf.String(), err
}
type ErrInvalidInvAction struct {
Action string
}
func (err *ErrInvalidInvAction) Error() string {
return fmt.Sprintf("Invalid Inventory Action '%s'!", err.Action)
}
// Reads space or colon speperated strings from io.Reader
func ReadString(r io.Reader, colon bool) (str string) {
var p = make([]byte, 1)
for {
_, err := r.Read(p)
if err != nil {
if errors.Is(err, io.EOF) {
return
} else {
panic(SerializationError{err})
}
}
if p[0] == " "[0] || (colon && p[0] == ":"[0]) {
return
} else {
str += string(p[0])
}
}
}
// Reads space speperated uint16 from io.Reader
func ReadUint16(r io.Reader, colon bool) (i uint16) {
str := ReadString(r, colon)
ii, err := strconv.ParseUint(str, 10, 16)
if err != nil {
panic(SerializationError{err})
}
return uint16(ii)
}
func ReadInt(r io.Reader, colon bool) (i int) {
str := ReadString(r, colon)
ii, err := strconv.ParseUint(str, 10, 32)
if err != nil {
panic(SerializationError{err})
}
return int(ii)
}
// Stolen from https://github.com/anon55555/mt/blob/bcc58cb3048faa146ed0f90b330ebbe791d53b5c/zerialize.go#L26
type Deserializer interface {
Deserialize(r io.Reader)
}
func Deserialize(r io.Reader, d interface{}) error {
return pcall(func() { d.(Deserializer).Deserialize(r) })
}
type SerializationError struct {
error
}
func pcall(f func()) (rerr error) {
defer func() {
switch r := recover().(type) {
case SerializationError:
rerr = r.error
case nil:
default:
panic(r)
}
}()
f()
return
}