forked from funny/link
/
codec_string.go
49 lines (39 loc) · 966 Bytes
/
codec_string.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
package link
import (
"io"
"github.com/funny/binary"
)
func String(spliter binary.Spliter) CodecType {
return stringCodecType{spliter}
}
type stringCodecType struct {
Spliter binary.Spliter
}
func (codecType stringCodecType) NewEncoder(w io.Writer) Encoder {
return stringEncoder{
codecType.Spliter,
binary.NewWriter(w),
}
}
func (codecType stringCodecType) NewDecoder(r io.Reader) Decoder {
return stringDecoder{
codecType.Spliter,
binary.NewReader(r),
}
}
type stringEncoder struct {
Spliter binary.Spliter
Writer *binary.Writer
}
func (encoder stringEncoder) Encode(msg interface{}) error {
encoder.Writer.WritePacket([]byte(msg.(string)), encoder.Spliter)
return encoder.Writer.Flush()
}
type stringDecoder struct {
Spliter binary.Spliter
Reader *binary.Reader
}
func (decoder stringDecoder) Decode(msg interface{}) error {
*(msg.(*string)) = string(decoder.Reader.ReadPacket(decoder.Spliter))
return decoder.Reader.Error()
}